JBoss AS6

EJB Specific Deployment descriptors in WebLogic and JBoss

Hi,

An EJB container is the component that manages a particular class of EJB. In JBoss there is one instance of the org.jboss.ejb.Container created for each unique configuration of an EJB that is deployed. The actual object that is instantiated is a subclass of Container and the creation of the container instance is managed by the EJBDeployer MBean.

The JBoss EJB container architecture employs a modular plug-in approach. All key aspects of the EJB container may be replaced by custom versions of a plug-in and/or an interceptor by a developer. This approach allows for fine tuned customization of the EJB container behavior to optimally suite your needs. Most of the EJB container behavior is configurable through the EJB JAR META-INF/jboss.xml descriptor and the default server-wide equivalent standardjboss.xml descriptor.

In order to migrate the EJB based application from WebLogic to JBoss most of the peoplefaces challenges specially when it comes to the container specific deployment descriptors. So here in this example we will see what kind of entries goes inside the WebLogic specific EJB Deployment descriptor “weblogic-ejb-jar.xml” and how those parameter and configurations can be moved insside the JBoss specific EJB Deployment descriptors like “jboss.xml” (for JBoss AS4/5/6) and “jboss-ejb3.xml” (for JBoss AS7).

First of all we will see where to find the XSDs based on which we can write these JBoss specific deployment descriptors.

WebLogic XSDs

WebLogic Schemas are present inside : “${WLS_INSTALLATION}/modules/com.bea.core.descriptor.wl.binding_1.2.0.0.jar” file.

Location: “WLS1031/modules/com.bea.core.descriptor.wl.binding_1.2.0.0/META-INF/schemas/weblogic-ejb-jar.xsd”

JBoss XSDs

JBoss Schemas are present inside the ${JBOSS_HOME}/docs/schema/jboss_5_1.xsd (JBoss AS6 and earlier versions)

JBoss Schemas are present inside the ${JBOSS_HOME}/docs/schema/jboss-ejb3-2_0.xsd (JBoss AS7)

Here we will see with all the possible elements inside “weblogic-ejb-jar.xml” file how it looks :

Before Migration (weblogic-ejb-jar.xml)

<weblogic-ejb-jar id="{someID}" version="{someString}">
  <description>{someDescription}</description>
  <weblogic-enterprise-bean id="{someID}">
    <ejb-name>{someEjbName}</ejb-name>
    <transaction-descriptor id="{someID}">
      <trans-timeout-seconds>{someTxTimeout}</trans-timeout-seconds>
    </transaction-descriptor>
    <iiop-security-descriptor id="{someID}">
      <transport-requirements id="{someID}">
        <integrity id="{someID}">{someString}</integrity>
        <confidentiality id="{someID}">{someString}</confidentiality>
        <client-cert-authentication id="{someID}">{someString}</client-cert-authentication>
      </transport-requirements>
      <client-authentication id="{someID}">{someString}</client-authentication>
      <identity-assertion id="{someID}">{someString}</identity-assertion>
    </iiop-security-descriptor>
    <enable-call-by-reference>{some-true-false}</enable-call-by-reference>
    <network-access-point>{someString}</network-access-point>
    <clients-on-same-server>{some-true-false}</clients-on-same-server>
    <run-as-principal-name>{some-Role-Name}</run-as-principal-name>
    <create-as-principal-name id="{someID}">{someString}</create-as-principal-name>
    <remove-as-principal-name id="{someID}">{someString}</remove-as-principal-name>
    <passivate-as-principal-name id="{someID}">{someString}</passivate-as-principal-name>
    <jndi-name>{someJndiName}</jndi-name>
    <local-jndi-name>{someJndiName}</local-jndi-name>
    <dispatch-policy>{some-dispatch-policyType}</dispatch-policy>
    <remote-client-timeout>{someTxTimeout}</remote-client-timeout>
    <stick-to-first-server>{some-true-false}</stick-to-first-server>
  </weblogic-enterprise-bean>
  <security-role-assignment>{some-Role-Name}</security-role-assignment>
  <run-as-role-assignment>{some-Role-Name}</run-as-role-assignment>
  <security-permission>{some-security-permissionType}</security-permission>
  <transaction-isolation id="{someID}">
    <isolation-level id="{someID}">{someString}</isolation-level>
    <method id="{someID}">
      <description>{someDescription}</description>
      <ejb-name>{someEjbName}</ejb-name>
      <method-intf>{something}</method-intf>
      <method-name>{something}</method-name>
      <method-params>{something}</method-params>
    </method>
  </transaction-isolation>

  <message-destination-descriptor>{some-message-destination-descriptorType}</message-destination-descriptor>
  <idempotent-methods id="{someID}">
    <method id="{someID}">
      <description>{someDescription}</description>
      <ejb-name>{someEjbName}</ejb-name>
      <method-intf>{something}</method-intf>
      <method-name>{something}</method-name>
      <method-params>{something}</method-params>
    </method>
  </idempotent-methods>
  <retry-methods-on-rollback id="{someID}">
    <description>{someDescription}</description>
    <retry-count>{someTxTimeout}</retry-count>
    <method id="{someID}">
      <description>{someDescription}</description>
      <ejb-name>{someEjbName}</ejb-name>
      <method-intf>{something}</method-intf>
      <method-name>{something}</method-name>
      <method-params>{something}</method-params>
    </method>
  </retry-methods-on-rollback>
  <enable-bean-class-redeploy>{some-true-false}</enable-bean-class-redeploy>
  <timer-implementation id="{someID}">{someString}</timer-implementation>
  <disable-warning id="{someID}">{someString}</disable-warning>
  <work-manager>{something}</work-manager>
  <component-factory-class-name>{someString}</component-factory-class-name>
  <weblogic-compatibility id="{someID}">
    <entity-always-uses-transaction>{some-true-false}</entity-always-uses-transaction>
  </weblogic-compatibility>
</weblogic-ejb-jar>

After Migration (jboss.xml) to JBoss AS5/6

Now if we will try to migrate a weblogic based EJB Application to JBoss AS 5/6 then it will look something like following:

<jboss version="{someString}" metadata-complete="{true-false}" id="{someID}">
  <loader-repository>{someClassLoaderRepositoryName}</loader-repository>
  <jmx-name>{someJMXName}</jmx-name>
  <security-domain>{someSecurityDomainName}</security-domain>
  <missing-method-permissions-excluded-mode></missing-method-permissions-excluded-mode>
  <unauthenticated-principal></unauthenticated-principal>
  <jndi-binding-policy>{someStringJndiPolicy}</jndi-binding-policy>
  <jacc-context-id></jacc-context-id>
  <webservices id="{someID}">
    <context-root>{someStringValue}</context-root>
    <webservice-description>{some-webservice-descriptionType}</webservice-description>
  </webservices>
  <enterprise-beans>
  <service id="{someID}">
    <ejb-name>{someEJBName}</ejb-name>
    <mapped-name>{someMBeanObjectName}</mapped-name>
    <business-local>{someRemoteInterfaceEJBClass}</business-local>
    <business-remote>{someRemoteInterfaceEJBClass}</business-remote>
    <ejb-class>{someEJBClass}</ejb-class>
    <security-identity id="{someID}">
      <description>{someStringDescription}</description>
      <run-as-principal>{someRoleName}</run-as-principal>
    </security-identity>
    <object-name>{someJMXName}</object-name>
    <management></management>
    <xmbean></xmbean>
    <local-binding>
      <description>{someStringDescription}</description>
      <jndi-name>{someStringJndiPType}</jndi-name>
    </local-binding>
    <remote-binding id="{someID}">
      <description>{someStringDescription}</description>
      <jndi-name>{someStringJndiPType}</jndi-name>
      <client-bind-url></client-bind-url>
      <interceptor-stack></interceptor-stack>
      <proxy-factory></proxy-factory>
      <invoker-name></invoker-name>
    </remote-binding>
    <jndi-name>{someStringJndiPType}</jndi-name>
    <home-jndi-name>{someStringJndiPType}</home-jndi-name>
    <local-jndi-name>{someStringJndiPType}</local-jndi-name>
    <jndi-binding-policy>{someStringJndiPolicy}</jndi-binding-policy>
    <clustered></clustered>
    <cluster-config id="{someID}">
      <description>{someStringDescription}</description>
      <partition-name></partition-name>
      <home-load-balance-policy></home-load-balance-policy>
      <session-state-manager-jndi-name>{someStringValue}</session-state-manager-jndi-name>
    </cluster-config>
    <security-domain>{someMBeanObjectName}</security-domain>
    <method-attributes id="{someID}">
      <method id="{someID}">
        <method-name>{some-method-nameType}</method-name>
        <read-only>{some-boolean}</read-only>
        <idempotent>{some-boolean}</idempotent>
        <transaction-timeout></transaction-timeout>
      </method>
    </method-attributes>
    <depends>{someMBeanObjectName}</depends>
    <annotation id="{someID}">
      <description>{someStringDescription}</description>
      <annotation-class></annotation-class>
      <annotation-implementation-class></annotation-implementation-class>
      <injection-target>{someInjectionTarget}</injection-target>
      <property id="{someID}">
        <description>{someStringDescription}</description>
        <property-name>{someStringValue}</property-name>
        <property-value>{someStringValue}</property-value>
      </property>
    </annotation>
    <ignore-dependency id="{someID}">
      <description>{someStringDescription}</description>
      <injection-target>{someInjectionTarget}</injection-target>
    </ignore-dependency>
    <aop-domain-name></aop-domain-name>
    <pool-config>
      <pool-value></pool-value>
      <pool-max-size></pool-max-size>
      <pool-timeout></pool-timeout>
    </pool-config>
    <concurrent></concurrent>
    <jndi-ref id="{someID}">
      <description>{someStringDescription}</description>
      <jndi-ref-name>{someStringJndiPType}</jndi-ref-name>
    </jndi-ref>
    <port-component id="{someID}">
      <port-component-name>{someStringValue}</port-component-name>
      <port-component-uri>{someStringValue}</port-component-uri>
      <auth-method>{someStringValue}</auth-method>
      <transport-guarantee>{someStringValue}</transport-guarantee>
      <secure-wsdl-access>{some-boolean}</secure-wsdl-access>
    </port-component>
    <ejb-timeout-identity id="{someID}">
      <description>{someStringDescription}</description>
      <run-as-principal>{someRoleName}</run-as-principal>
    </ejb-timeout-identity>
  </service>
  </enterprise-beans>
  <assembly-descriptor id="{someID}">
    <security-role>{some-security-roleType}</security-role>
    <message-destination>{some-message-destinationType}</message-destination>
  </assembly-descriptor>
  <resource-managers id="{someID}">
    <description>{someStringDescription}</description>
    <resource-manager id="{someID}" res-class="{someStringValue}">
      <description>{someStringDescription}</description>
      <res-name>{someMBeanObjectName}</res-name>
    </resource-manager>
  </resource-managers>
</jboss>

So now as we know the tags which we can use in an order while migrating from WebLogic to JBoss, it will be an easy task now. :)
To know more about these common JBoss specific deployment descriptors please refer to the following link:
http://docs.jboss.org/jbossas/docs/Server_Configuration_Guide/4/html/ENC_Usage_Conventions-EJB_References_with_jboss.xml_and_jboss_web.xml.html
.
.
Thanks :)
Middleware Magic Team


How to download JBoss Server ?

Hi,

JBoss is worlds one of the most popular and reliable application server which provides you a lots of features including full customization.  It comes in two flavours

1). JBoss Community Release

2). JBoss RedHat Enterprise Release

Community Versus Enterprise JBoss Which one is Best?

The JBoss Community releases are the base of JBoss Enterprise Releases. But the JBoss Enterprise Release has many additional advantages in terms of standard life cycles and support and Many additional advantages and features which are required, mandatory and essential in running a Production environment using JBoss. For more informations of JBoss Community Release Vs JBoss Enterprise Release please refer to the following article:

JBoss Application ServerCommunity Release can be downloaded from the following link:
http://www.jboss.org/jbossas/downloads/

JBoss Enterprise Releases can be downloaded from the following link:
http://www.jboss.com/downloads/

The JBoss Enterprise release can be downloaded with “Subscription” as well as “Evaluation Version for 30 Days” In the above page you will get these options so based on your requirement you can choose.

If you already have a RedHat Subscription then you can download the software’s through the following link:
https://access.redhat.com/jbossnetwork/restricted/listSoftware.html

There are many JBoss  Community Releases and projects are going on in parallel which can be found in the following link:
http://www.jboss.org/projects/matrix

.
.
Thanks
MiddlewareMagic


Creating Read Only Users for jmx-console and web-console

Hi,

JBoss AS6 provides admin-console, jmx-console and web-console for server monitoring and management purpose. By default the username and password for accessing these applications are “admin”, “admin”. But many times we want to create some more users who can login to these applications as a Read Only user so that these users will not have any privilege to make any configuration changes rather they can just do the monitoring part.

It is possible in JBoss AS6 to create read Only users fore jmx-console and web-console BUT Currently the admin-console application does not support read only users access so we CAN NOT create a read only user for “admin-console”. So in this demonstration we will see how we can create a Read Only (Monitor Role) in JBoss AS6 for web-console & jmx-console applications.

Step1). We need to edit the “$PROFILE/deploy/jmx-console.war/WEB-INF/web.xml” file by un-commenting the following section mentioned.

    <filter>
      <filter-name>JmxOpsAccessControlFilter</filter-name>
      <filter-class>org.jboss.jmx.adaptor.html.JMXOpsAccessControlFilter</filter-class>
      <init-param>
        <description>Comma-delimited Roles that define the JMX Operation denoting updation of Attributes</description>
        <param-name>updateAttributes</param-name>
        <param-value>UpdateAttributeRole</param-value>
      </init-param>
      <init-param>
        <description>Comma-delimited Roles that define the JMX Operation denoting Invocation of Operations</description>
        <param-name>invokeOp</param-name>
        <param-value>InvokeOpRole</param-value>
      </init-param>
   </filter>
   <filter-mapping>
      <filter-name>JmxOpsAccessControlFilter</filter-name>
      <servlet-name>HtmlAdaptor</servlet-name>
   </filter-mapping>

Step2). Now we need to edit the “$PROFILE/conf/props/jmx-console-roles.properties” like ollowing:
NOTE: to make read only role for “web-console” make the below mentioned changes inside “$PROFILE/deploy/management/console-mgr.sar/web-console.war/WEB-INF/classes/web-console-roles.properties” file.

# A sample roles.properties file for use with the UsersRolesLoginModule
admin=JBossAdmin,HttpInvoker,UpdateAttributeRole,InvokeOpRole
MyReadOnlyUserName=JBossAdmin

Here you can see that “MReadOnlyUserName” does not have the “UpdateAttributeRole,InvokeOpRole” roles means this user can not perform any update operation as well as this user can not perform any method Invocation operation from the console.

Step3). Similarly edit the “$PROFILE/conf/props/jmx-console-users.properties” like following :
NOTE: to make read only users for “web-console” make the below mentioned changes inside “$PROFILE/deploy/management/console-mgr.sar/web-console.war/WEB-INF/classes/web-console-users.properties” file.

# A sample users.properties file for use with the UsersRolesLoginModule
admin=admin
MyReadOnlyUserName=MyReadOnlyPassword

Step4). Setup is done so now you can restart your JBoss AS6 Profile and access in the jmx-console. Login as newly created user

username as MyReadOnlyUserName
password as MyReadOnlyPassword

You will receive a 403 error code “Access to the specified resource has been forbidden”, if you will try to make any configuration changes with this user credentials like changing the thread pool size…etc. But these changes you can easily make using the Non-Read only user credentials.

.
.
Thanks
Middleware Magic Team


How to create a Service Archieve SAR file in JBoss AS6

Hi,
NOTE: this article is focused on JBoss AS6 and earlier versions. For JBoss AS7 service archives please refer to: http://middlewaremagic.com/jboss/?p=366

SAR files are called as Service Archives. The extension of SAR files are *.sar which contains a “META-INF/jboss-service.xml” file, this file describes the custom MBeans which has to be exposed at the time of deployment or JBoss Startup. JBoss’s service archive architecture is based on the JMX and the SAR files which are basically JBoss specific can be deployed in the jboss inorder to publish your MBean based services. At the time of JBoss startup these service archive deployer (SARDeployer) instantiates the JBoss service classes and exposes them as manageable beans through JMX. These beans can be viewed and edited from the jmx-console as well.

One of the best usage of the service archieve is to monitor the servers activities. In this simple example we will try to get JBoss Server’s basic informations using the JBoss MBean “jboss.system:type=Server” using our SAR file.

Step1). Create a directory somewhere in your file system like “/home/userone/ServerMonitorService.sar”.

Step2). Create an MBean interface by extending the interface “org.jboss.system.ServiceMBean” as following. “MyServerMonitorMBean.java” inside the “/home/userone/ServerMonitorService.sar” directory.

package custom.mbean;
import org.jboss.system.ServiceMBean;
public interface MyServerMonitorMBean extends org.jboss.system.ServiceMBean
  {
      public void setFrequency(String frequency);
      public String getFrequency();
  }

Step3). Now provide an implementation class of the above MBean interface as “MyServerMonitor.java” inside the directory “/home/userone/ServerMonitorService.sar”. Make sure that this class extends the “org.jboss.system.ServiceMBeanSupport” class because this class provides some useful methods like “startService()” and “stopService()” which are the life cycle methids of our beans.

package custom.mbean;
import javax.management.*;
import java.io.*;
import java.util.*;
import java.rmi.*;
import javax.naming.*;
public class MyServerMonitor extends org.jboss.system.ServiceMBeanSupport implements MyServerMonitorMBean
  {
      boolean flag=true;
      public String Frequency;
      private MBeanServerConnection server=null;
      public void setFrequency(String Frequency)
      {
          System.out.println("nt Server Watch Frequency is set to : "+Frequency+"-Milliseconds");
          this.Frequency=Frequency;
      }
      public String getFrequency()
      {
          System.out.println("nt Server Watch Frequency is set to : "+Frequency+"-Milliseconds");
          return this.Frequency;
      }
      public MyServerMonitor()
      {
         System.out.println("nnt ServiceMonitorMBean is activated...inside ServiceMonitor() constructor--setting default Frequency=10000 Miliseconds");;
      }

     public void startService() throws Exception
      {
         log.info("nntStarting MyServerMonitor");
            try{
            Hashtable ht=new Hashtable();
            ht.put(Context.INITIAL_CONTEXT_FACTORY,"org.jboss.security.jndi.JndiLoginInitialContextFactory");
            ht.put(Context.PROVIDER_URL,"localhost:1099");
            ht.put(Context.SECURITY_PRINCIPAL,"admin");
            ht.put(Context.SECURITY_CREDENTIALS,"admin");
            System.out.println("nt 1- Gotting InitialContext...... ");
            Context ctx = new InitialContext(ht);
            System.out.println("nt 2- Got InitialContext: "+ctx);
            server = (MBeanServerConnection) ctx.lookup("jmx/invoker/RMIAdaptor");
            }
            catch(Exception e)
            {
                System.out.println("nnt Exception inside MyServerMonitor..."+e);
            }
            Frequency="5000";
            ServerMonitorRunner runner=new ServerMonitorRunner();
      }

      public void monitor() throws Exception
      {
            String data="";
            data=data+"nnt===================MyServerMonitor.monitor()===================";
            data=data+"nBuildOS = "+ (String)server.getAttribute(new ObjectName("jboss.system:type=Server"), new String("BuildOS"));
            data=data+"nVersionName = "+ (String)server.getAttribute(new ObjectName("jboss.system:type=Server"), new String("VersionName"));
            data=data+"nBuildDate = "+ (String)server.getAttribute(new ObjectName("jboss.system:type=Server"), new String("BuildDate"));
            data=data+"nInShutdown = "+ (Boolean)server.getAttribute(new ObjectName("jboss.system:type=Server"), new String("InShutdown"));
            data=data+"nStartDate = "+ (java.util.Date)server.getAttribute(new ObjectName("jboss.system:type=Server"), new String("StartDate"));
            data=data+"nStarted = "+ (Boolean)server.getAttribute(new ObjectName("jboss.system:type=Server"), new String("Started"));
            data=data+"nBuildNumber = "+ (String)server.getAttribute(new ObjectName("jboss.system:type=Server"), new String("BuildNumber"));
            data=data+"nBuildJVM = "+ (String)server.getAttribute(new ObjectName("jboss.system:type=Server"), new String("BuildJVM"));
            data=data+"nVersionNumber = "+ (String)server.getAttribute(new ObjectName("jboss.system:type=Server"), new String("VersionNumber"));
            data=data+"nt===============================================================";
            System.out.println(data);
      }

     public void stopService() throws Exception
      {
         log.info("nntStopping MyServerMonitor");
      }
     class ServerMonitorRunner extends Thread
       {
           ServerMonitorRunner()
            {
                this.start();
            }
           public void run()
             {
                for(; ;)
                  {
                    try{
                          Thread.sleep(Integer.parseInt(Frequency));
                          monitor();
                       }
                    catch(InterruptedException ie){ ie.printStackTrace();}
                    catch(Exception e){ e.printStackTrace();}

                  }
             }
       }
  }

Step4). Now the most important part, here we need to declare the MBean inside the “/home/userone/ServerMonitorService.sar/META-INF/jboss-service.xml” file as following:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE server>
<server>
    <mbean code="custom.mbean.MyServerMonitor" name="service.server.monitor:service=MyMonitor">
         <attribute name="Frequency">5000</attribute>
         <depends>jboss.jmx:type=adaptor,name=Invoker,protocol=jrmp,service=proxyFactory</depends>
    </mbean>
</server>

NOTE: here inside the tag we have used the tag because our MBean is dependent on another MBean “jboss.jmx:type=adaptor,name=Invoker,protocol=jrmp,service=proxyFactory”…this is why because our MBean code is performing ic.lookup() using the “jmx/invoker/RMIAdaptor” so we need to make sure that the “jboss.jmx:type=adaptor,name=Invoker,protocol=jrmp,service=proxyFactory” service gets activated before our MBean. otherwise we will see NullPointerException while performing lookup inside our bean.

Step5). Deploy the “ServerMonitorService.sar” inside the “${PROFILE}/deploy” directory of your JBoss. And then you will start seeing the following kind of messages in the server Console :

12:55:53,949 INFO  [STDOUT]
	 ServiceMonitorMBean is activated...inside ServiceMonitor() constructor--setting default Frequency=10000 Miliseconds
12:55:53,952 INFO  [STDOUT]
	 Server Watch Frequency is set to : 5000-Milliseconds
12:55:53,952 INFO  [MyServerMonitor]

	Starting MyServerMonitor
12:55:53,952 INFO  [STDOUT]
	 1- Gotting InitialContext......
12:55:53,964 INFO  [STDOUT]
	 2- Got InitialContext: javax.naming.InitialContext@588a4b96
12:55:59,167 INFO  [STDOUT]

	===================MyServerMonitor.monitor()===================
BuildOS = Linux(i386,2.6.18-194.8.1.el5)
VersionName = JBoss AS
InShutdown = false
StartDate = Sun Oct 16 12:19:59 IST 2011
Started = true
BuildJVM = 17.0-b16(Sun Microsystems Inc.)
VersionNumber = 6.0.
	===============================================================

The MyServerMonitor.monitor() will be executed after every 5 Seconds as we have set this frequency as 5 seconds inside the jboss-service.xml file.

Step6). If you want to change this frequency to something else then you can login to jmx-console and then search for “service.server.monitor” in the left Panel then by clicking on it you will be able to see the frequency which you can change.

.
.
Thanks
Middleware Magic Team


Binding Custom Strings in JBoss AS6 JNDI tree

Hi,

Many times we want to create some customer JNDI names which will hold some string objects to perform some application specific functionality. In general terms we can say “We want to bind some strings to the JBoss AS6 server’s JNDI tree.” so in order to do that we have the following two options

Option-1).

According to J2EE Specifications we can write the following kind of tag inside our application’s “WEB-INF/web.xml” file:

<?xml version='1.0' encoding='UTF-8'?>
<web-app>
  <env-entry>
    <env-entry-name>TestJNDIKey</env-entry-name>
    <env-entry-type>java.lang.String</env-entry-type>
    <env-entry-value>Some_Application_Specific_JNDIData</env-entry-value>
  </env-entry>
</web-app>

Once your web.xml file has the above kind of entry then you can use the following kind of Code snippet inside your application code (like servlet or jsp) to get the JNDI entry’s bind value.

   InitialContext ctx = new InitialContext();
   Context envCtx = (Context) ctx.lookup("java:comp/env");
   String jndiData = (String) envCtx.lookup("TestJNDIKey");

Option-2).

Open the “jboss-services.xml” file from the following location “$JBOSS_HOME/server/$PROFILE/conf” directory and then add the following kind of <mbean> declaration using “org.jboss.naming.JNDIBindingServiceMgr”

<mbean code="org.jboss.naming.JNDIBindingServiceMgr" name="jboss.testing:name=test">
       <attribute name="BindingsConfig" serialDataType="jbxb">
         <jndi:bindings xmlns:xs="http://www.w3.org/2001/XMLSchema-instance"
                        xmlns:jndi="urn:jboss:jndi-binding-service:1.0"
                        xs:schemaLocation="urn:jboss:jndi-binding-service resource:jndi-binding-service_1_0.xsd">
             <jndi:binding name="TestJNDIKey">
                 <jndi:value trim="true">Hello, SomeValue!</jndi:value>
             </jndi:binding>
         </jndi:bindings>
        </attribute>
</mbean>

Option-3).

If you don;t want to edit the “jboss-services.xml” file provided by JBoss AS6 then in that case you can create your own Service file with some name like “test-service.xml” inside your “/WEB-INF” directory.
NOTE: the file name must end with “*-service.xml”

OR

Create a file with some name like “test-service.xml” and then place it inside your “$PROFILE/deploy” directory, so that as soon as you will start your JBoss AS6 instance the Service will be activated and the JNDI name will be binded in the JNDI tree of your JBoss.

So you can add the following MBean declaration somewhere in the file Either inside “/server/
/conf/jboss-service.xml” Or add the following declaration inside “/WEB-INF/test-service.xml” file:

<?xml version="1.0" encoding="UTF-8"?>
<server>
<mbean code="org.jboss.naming.JNDIBindingServiceMgr" name="jboss.tests:name=example1">
       <attribute name="BindingsConfig" serialDataType="jbxb">
         <jndi:bindings xmlns:xs="http://www.w3.org/2001/XMLSchema-instance"
                        xmlns:jndi="urn:jboss:jndi-binding-service:1.0"
                        xs:schemaLocation="urn:jboss:jndi-binding-service resource:jndi-binding-service_1_0.xsd">
             <jndi:binding name="TestJNDIKey">
                 <jndi:value trim="true">Hello, SomeValue!</jndi:value>
             </jndi:binding>
         </jndi:bindings>
        </attribute>
</mbean>
</server>

Step2). Now restart your JBoss AS6 profile like

./run.sh -c default_Test -b 10.10.10.10

Above means you are starting the JBoss profile “default_Test” on Listen address 10.10.10.10.

Step3). You can use the the following client to access the JNDI name remotely/locally.

import java.util.Properties;
import javax.naming.Context;
import javax.naming.InitialContext;
public class ExClient
   {
       public static void main(String args[]) throws Exception
        {
          Properties env = new Properties();
          env.setProperty(Context.INITIAL_CONTEXT_FACTORY,"org.jboss.naming.NamingContextFactory");
          env.setProperty(Context.PROVIDER_URL,"10.10.10.10:1099");
          Context ctx = new InitialContext(env);
          System.out.println("nntCreated InitialContext, env=" + env);
          Object data = ctx.lookup("TestJNDIKey");
          System.out.println("nntlookup(MyJNDIName): " + (String)data);
         }
   }

.
.
Thanks
Middleware Magic Team


Implementing UsernameToken in WebService WITHOUT Basic Authentication (pure wsee)

Hi,

Here we are going to see how too secure WebService using WSEE standards of UsernameToken. The element is introduced in the WSS-SOAP Message Security documents as a way of providing a username and a element may be specified. Passwords of type wsse:PasswordText are not limited to actual passwords. wsse:PasswordText merely implies that the information held in the password is “in the clear text”, as opposed to holding a “digest” of the information

In this sample we will not use the Basic Authentication mechanism rather we will use the WSEE standards inside our webService to secure it using UsernameToken. In our previous example “Implementing UsernameToken in WebService with Basic Authentication” we used the UsernameToken in association with the BASIC Authentication so an extra header was being added in the Http response as “header=authorization=Basic a2VybWl0OnRoZWZyb2c=”.

But in this current demo we will not use the BASIC authentication rather we will use the WSEE standard UsernameToket authorization mechanism. The <security-domain> we are going to use as “java:/jaas/JBossWS” which is already defined inside the “$PROFILE/conf/login-config.xml” file as following :

  <!--
    A template configuration for the JBossWS security domain.
    This defaults to the UsersRolesLoginModule the same as other and should be
    changed to a stronger authentication mechanism as required.
  -->
  <application-policy name="JBossWS">
    <authentication>
      <login-module code="org.jboss.security.auth.spi.UsersRolesLoginModule"
        flag="required">
        <module-option name="usersProperties">props/jbossws-users.properties</module-option>
        <module-option name="rolesProperties">props/jbossws-roles.properties</module-option>
        <module-option name="unauthenticatedIdentity">anonymous</module-option>
      </login-module>
    </authentication>
  </application-policy>

Step1). Create a directory somewhere in your filesystem as “/home/userone/UserNameToken_With_WSSE” here we will write the WebService WAR and the Standalone client application.

Step2). Create a webservice application directory with name “UserNameTokenService.war” inside “/home/userone/UserNameToken_With_WSSE” .

Step3). Write the “UsernameEndpoint.java” endpoint interface inside the directory “/home/userone/UserNameToken_With_WSSE/UserNameTokenService.war/WEB-INF/classes” as following:

package test.wssecurity;
import javax.jws.WebMethod;
import javax.jws.WebResult;
import javax.jws.WebService;
import javax.jws.soap.SOAPBinding;

@WebService(name = "UsernameEndpoint", targetNamespace = "http://test/wssecurity")
@SOAPBinding(style = SOAPBinding.Style.RPC)
public interface UsernameEndpoint {
    @WebMethod
    @WebResult(partName = "return")
    public String getUsernameToken();

}

Step4).Write the service implementation class “UsernameBean.java” inside the directory “/home/userone/UserNameToken_With_WSSE/UserNameTokenService.war/WEB-INF/classes” as following:

package test.wssecurity;
import java.security.Principal;
import javax.annotation.Resource;
import javax.jws.WebMethod;
import javax.jws.WebResult;
import javax.jws.WebService;
import javax.jws.soap.SOAPBinding;
import javax.xml.ws.WebServiceContext;
import org.jboss.ws.annotation.EndpointConfig;

@WebService(name = "UsernameEndpoint", serviceName = "UsernameService", targetNamespace = "http://test/wssecurity")
@EndpointConfig(configName = "Standard WSSecurity Endpoint")
@SOAPBinding(style = SOAPBinding.Style.RPC)

public class UsernameBean
{
   @WebMethod
   @WebResult(partName = "return")
   public String getUsernameToken()
   {
      System.out.println("nt[WebService- UsernameBean] getUsernameToken: " + "HelloWorld");
      return "Hello ...";
   }
}

Step4). Write the “web.xml” file as following inside directory “/home/userone/UserNameToken_With_WSSE/UserNameTokenService.war/WEB-INF”:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd" version="2.4">
  <servlet>
    <servlet-name>UsernameService</servlet-name>
    <servlet-class>org.jboss.wsf.stack.jbws.EndpointServlet</servlet-class>
    <init-param>
      <param-name>jboss.ws.endpoint</param-name>
      <param-value>test.wssecurity.UsernameBean</param-value>
    </init-param>
  </servlet>
  <servlet-mapping>
    <servlet-name>UsernameService</servlet-name>
    <url-pattern>/*</url-pattern>
  </servlet-mapping>

  <security-constraint>
    <web-resource-collection>
      <web-resource-name>UsernameService</web-resource-name>
      <url-pattern>/*</url-pattern>
      <http-method>GET</http-method>
      <http-method>POST</http-method>
    </web-resource-collection>
 </security-constraint>

  <security-role>
    <role-name>friend</role-name>
  </security-role>
</web-app>

Step5). Write the “jboss-web.xml” file as following inside directory “/home/userone/UserNameToken_With_WSSE/UserNameTokenService.war/WEB-INF”:

<?xml version="1.0" encoding="UTF-8"?>
<jboss-web>
  <security-domain>java:/jaas/JBossWS</security-domain>
</jboss-web>

Step6). Write the “jboss-wsee-server.xml” file as following inside directory “/home/userone/UserNameToken_With_WSSE/UserNameTokenService.war/WEB-INF”:
NOTE: jboss-wsee-server.xml is the security configuration file used on the server-side. This applies to all incoming requests to a web service endpoint, as well as the outgoing responses sent by the web service endpoint.

<?xml version="1.0" encoding="UTF-8"?>
<jboss-ws-security xmlns="http://www.jboss.com/ws-security/config" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                   xsi:schemaLocation="http://www.jboss.com/ws-security/config http://www.jboss.com/ws-security/schema/jboss-ws-security_1_0.xsd">
<config>
  <!-- Enable Authentication via Username Token. We do not care about the roles, but users should be authenticated! -->
  <authorize>
      <unchecked/>
  </authorize>
  <!-- Force presence of wsse:usernameToken header in requests -->
  <requires>
      <username/>
  </requires>
</config>
</jboss-ws-security>"

Step7). Now compile the classes present inside the “/home/userone/UserNameToken_With_WSSE/UserNameTokenService.war/WEB-INF/classes” directory as following:

$ javac -d . UsernameEndpoint.java
$ javac -d . UsernameBean.java

Step8). deploy the “UserNameTokenService.war” WebApplication directory inside “$PROFILE/deploy” directory of JBoss. As soon as you will deploy above webservice inside the JBoss profile you will be able to see following kind of messages inside your JBoss Console:

17:51:27,443 INFO  [DefaultEndpointRegistry] register: jboss.ws:context=UserNameTokenService,endpoint=UsernameService
17:51:27,561 INFO  [TomcatDeployment] deploy, ctxPath=/UserNameTokenService
17:51:28,128 INFO  [WSDLFilePublisher] WSDL published to: file:/home/userone/jboss-6/jboss-as/server/default/data/wsdl/UserNameTokenService.war/UsernameService1873434917945303908.wsdl

Now you will be able to access the WSDL from the following URL: http://localhost:8080/UserNameTokenService?wsdl
as following:

<definitions xmlns="http://schemas.xmlsoap.org/wsdl/" xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:tns="http://test/wssecurity" xmlns:xsd="http://www.w3.org/2001/XMLSchema" name="UsernameService" targetNamespace="http://test/wssecurity">
	<types/>
	<message name="UsernameEndpoint_getUsernameToken"/>
	<message name="UsernameEndpoint_getUsernameTokenResponse">
		<part name="return" type="xsd:string"/>
	</message>
	<portType name="UsernameEndpoint">
		<operation name="getUsernameToken">
			<input message="tns:UsernameEndpoint_getUsernameToken"/>
			<output message="tns:UsernameEndpoint_getUsernameTokenResponse"/>
		</operation>
	</portType>
	<binding name="UsernameEndpointBinding" type="tns:UsernameEndpoint">
		<soap:binding style="rpc" transport="http://schemas.xmlsoap.org/soap/http"/>
			<operation name="getUsernameToken">
		<soap:operation soapAction=""/>
			<input>
				<soap:body namespace="http://test/wssecurity" use="literal"/>
			</input>
			<output>
				<soap:body namespace="http://test/wssecurity" use="literal"/>
			</output>
		</operation>
	</binding>
	<service name="UsernameService">
		<port binding="tns:UsernameEndpointBinding" name="UsernameEndpointPort">
			<soap:address location="http://127.0.0.1:8080/UserNameTokenService"/>
		</port>
	</service>
</definitions>

Writing Client to Access UsernameToken Secure Service

Step9). Create a directory with name “Client” inside the directory “/home/userone/UserNameToken_With_WSSE” and then use the “$JBOSS_HOME/bin/wsconsume.sh” script to generate the client artifacts:
NOTE:
before running the wsconsume.sh script make sure that you set the JAVA_HOME inside this script which should point to any JDK higher to 1.5
JAVA_HOME=/home/userone/jdk1.6.0_21

./wsconsume.sh -k -o /home/userone/UserNameToken_With_WSSE/Client -p client.wssecurity -s /home/userone/UserNameToken_With_WSSE/Client http://localhost:8080/UserNameTokenService?wsdl

./wsconsume.sh -k -o /home/userone/UserNameToken_With_WSSE/Client -p client.wssecurity -s /home/userone/UserNameToken_With_WSSE/Client http://localhost:8080/UserNameTokenService?wsdl
parsing WSDL...

[INFO] Trying to read authorization file : "/home/jsenshar/.metro/auth"...

generating code...

client/wssecurity/UsernameEndpoint.java
client/wssecurity/UsernameService.java

compiling code...

javac -d /home/userone/UserNameToken_With_WSSE/Client -classpath :/home/userone/jdk1.6.0_21/lib/tools.jar:/home/userone/jboss-6/jboss-as/client/activation.jar:/home/userone/jboss-6/jboss-as/client/getopt.jar:/home/userone/jboss-6/jboss-as/client/wstx.jar:/home/userone/jboss-6/jboss-as/client/jbossall-client.jar:/home/userone/jboss-6/jboss-as/client/log4j.jar:/home/userone/jboss-6/jboss-as/client/mail.jar:/home/userone/jboss-6/jboss-as/client/jbossws-spi.jar:/home/userone/jboss-6/jboss-as/client/jbossws-common.jar:/home/userone/jboss-6/jboss-as/client/jbossws-framework.jar:/home/userone/jboss-6/jboss-as/client/jaxws-tools.jar:/home/userone/jboss-6/jboss-as/client/jaxws-rt.jar:/home/userone/jboss-6/jboss-as/client/stax-api.jar:/home/userone/jboss-6/jboss-as/client/jaxb-api.jar:/home/userone/jboss-6/jboss-as/client/jaxb-impl.jar:/home/userone/jboss-6/jboss-as/client/jaxb-xjc.jar:/home/userone/jboss-6/jboss-as/client/streambuffer.jar:/home/userone/jboss-6/jboss-as/client/stax-ex.jar:/home/userone/jboss-6/jboss-as/client/javassist.jar:/home/userone/jboss-6/jboss-as/client/jboss-xml-binding.jar:/home/userone/jboss-6/jboss-as/client/jbossws-native-client.jar:/home/userone/jboss-6/jboss-as/client/jbossws-native-core.jar:/home/userone/jboss-6/jboss-as/client/jbossws-native-jaxws.jar:/home/userone/jboss-6/jboss-as/client/jbossws-native-jaxws-ext.jar:/home/userone/jboss-6/jboss-as/client/jbossws-native-jaxrpc.jar:/home/userone/jboss-6/jboss-as/client/jbossws-native-saaj.jar -Xbootclasspath/p:/home/userone/jboss-6/jboss-as/lib/endorsed/jbossws-native-jaxws.jar:/home/userone/jboss-6/jboss-as/lib/endorsed/jaxb-api.jar /home/userone/UserNameToken_With_WSSE/Client/client/wssecurity/UsernameEndpoint.java /home/userone/UserNameToken_With_WSSE/Client/client/wssecurity/UsernameService.java

Above command line utility will generate all the required client side artifacts inside the “/home/userone/UserNameToken_With_WSSE/Client/” directory.

Step10). Now we will need to write the WebService client program “SimpleUsernameTestCase.java” inside “/home/userone/UserNameToken_With_WSSE/Client” directory as following:

package client.wssecurity;
import java.io.File;
import java.net.URL;
import java.util.Map;
import javax.xml.namespace.QName;
import javax.xml.ws.BindingProvider;
import javax.xml.ws.Service;
import org.jboss.ws.core.StubExt;
import org.jboss.wsf.test.JBossWSTestSetup;

public class SimpleUsernameTestCase
{
   private static UsernameEndpoint port;
    public static void main(String ar[]) throws Exception
    {
         URL wsdlURL = new File("META-INF/wsdl/UsernameService.wsdl").toURL();
         URL securityURL = new File("META-INF/jboss-wsse-client.xml").toURL();
         QName serviceName = new QName("http://test/wssecurity", "UsernameService");

         Service service = Service.create(wsdlURL, serviceName);
         port = (UsernameEndpoint)service.getPort(UsernameEndpoint.class);
         System.out.println("nt Got the Service Port: "+port);

         ((StubExt)port).setSecurityConfig(securityURL.toExternalForm());
         ((StubExt)port).setConfigName("Standard WSSecurity Client");

         BindingProvider bp=(BindingProvider)port;
         bp.getRequestContext().put(StubExt.PROPERTY_AUTH_TYPE, StubExt.PROPERTY_AUTH_TYPE_WSSE);

         Map<String, Object> reqContext = bp.getRequestContext();

         // As the <security-domain>java:/jaas/JBossWS</security-domain>
         // Username & passwords are defined inside "$PROFILE/conf/props/jbossws-users.properties" file.

         //  NOTE:  Make sure to uncomment the username & password in this file
         reqContext.put(BindingProvider.USERNAME_PROPERTY, "kermit");
         reqContext.put(BindingProvider.PASSWORD_PROPERTY, "thefrog");

         String retObj = port.getUsernameToken();
         System.out.println("nt port.getUsernameToken(): "+retObj);
    }
}

Step11). Access the WSDL file from URL “http://localhost:8080/UserNameTokenService?wsdl” then save it inside the “/home/userone/UserNameToken_With_WSSE/Client/META-INF/wsdl” directory with some name as “UsernameService.wsdl”.

Step12). Create a file “jboss-wsse-client.xml” inside “/home/userone/UserNameToken_With_WSSE/Client/META-INF” as following:
NOTE: “jboss-wsse-client.xml” is the security configuration used on the client-side. This applies to all outgoing requests sent by a client, as well the response messages that are received by the client.

<?xml version="1.0" encoding="UTF-8"?>
<jboss-ws-security xmlns="http://www.jboss.com/ws-security/config" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://www.jboss.com/ws-security/config http://www.jboss.com/ws-security/schema/jboss-ws-security_1_0.xsd">
  <config>
      <username/>
  </config>
</jboss-ws-security>

Step13). Compile/Run the client program as following:

 javac -d . SimpleUsernameTestCase.java
 java -Djava.endorsed.dirs=/home/userone/jboss-6/jboss-as/lib/endorsed client.wssecurity.SimpleUsernameTestCase
log4j:WARN No appenders could be found for logger (org.jboss.ws.metadata.builder.jaxws.JAXWSWebServiceMetaDataBuilder).
log4j:WARN Please initialize the log4j system properly.

	 Got the Service Port: org.jboss.ws.core.jaxws.client.ClientImpl@67dacccc

	 port.getUsernameToken(): Hello ...

NOTE: Make sure that you use the “-Djava.endorsed.dirs=/home/userone/jboss-6/jboss-as/lib/endorsed” JAVA_OPTS while running your JBoss WebService client in order to make sure that your Client is using the JBoss WS stack.

Step15). If you want to see the SOAP Envelope along with the SOAP Headers then you can enable the following category inside the “$PROFILE/conf.jboss-log4j.xml” file by uncommenting the following section in it:

   <!-- Enable JBossWS message tracing  -->
   <category name="org.jboss.ws.core.MessageTrace">
     <priority value="TRACE"/>
   </category>

The SOAP messages will start appearing inside the “$PROFILE/log/server.log” file.

2011-10-16 18:38:58,310 TRACE [org.jboss.ws.core.MessageTrace] (http-127.0.0.1-8080-1) Incoming Request Message
<env:Envelope xmlns:env='http://schemas.xmlsoap.org/soap/envelope/'>
 <env:Header>
  <wsse:Security env:mustUnderstand='1' xmlns:ds='http://www.w3.org/2000/09/xmldsig#' xmlns:wsse='http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd' xmlns:wsu='http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd'>
   <wsse:UsernameToken wsu:Id='token-1-1318770538053-1595417149'>
    <wsse:Username>kermit</wsse:Username>
    <wsse:Password Type='http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText'>thefrog</wsse:Password>
   </wsse:UsernameToken>
  </wsse:Security>
 </env:Header>
 <env:Body>
  <ns1:getUsernameToken xmlns:ns1='http://test/wssecurity'/>
 </env:Body>
</env:Envelope>
2011-10-16 18:38:58,342 INFO  [STDOUT] (http-127.0.0.1-8080-1)
	[WebService- UsernameBean] getUsernameToken: HelloWorld
2011-10-16 18:38:58,348 TRACE [org.jboss.ws.core.MessageTrace] (http-127.0.0.1-8080-1) Outgoing Response Message
<env:Envelope xmlns:env='http://schemas.xmlsoap.org/soap/envelope/'>
 <env:Header/>
 <env:Body>
  <ns1:getUsernameTokenResponse xmlns:ns1='http://test/wssecurity'>
   <return>Hello ...</return>
  </ns1:getUsernameTokenResponse>
 </env:Body>
</env:Envelope>

.
.
Thanks
Middleware Magic Team


How to configure mod_cluster with JBoss ?


Like mod_jk, mod_cluster is also a httpd based load balancer which uses a communication channel to forward requests from the httpd to one of a set of application server nodes. So the question comes Why mod_cluster ? To answer this question we will let you know few advantages of mod_cluster over mod_jk and other httpd-based load balancers.

Hence in this article we would share you why should one use mod_cluster ? and how to configure mod_cluster with JBoss ? Hopping all our subscribers would take the advantage of this article and would help them to choose which is the best option for httpd based load balancer for there requirement.

Why should one use mod_cluster ?

  • Dynamic configuration:
  • Server side load balance:
  • AJP is optional:
  • Web application lifecycle control:

To know all the Advantages and Great features of mod_cluster refer to :

Steps to configure mod_cluster with JBoss

I have divided this configuration into two parts to, so that it would be much more easier to understand follow the steps. Here the following are the two parts

  1. Apache side configuration
  2. JBoss side configuration

Apache side configuration

  1. Download the required binaries for your OS from below link, example for RHEL x64 bit its [dynamic libraries linux2-x64]
  2. http://www.jboss.org/mod_cluster/downloads/1-1-0.html

  3. Copy following .so files to your “<Apache_Home>/modules” folder.
  4. mod_proxy.so
    mod_proxy_ajp.so
    mod_slotmem.so
    mod_manager.so
    mod_proxy_cluster.so
    mod_advertise.so

  5. Edit your httpd.conf (i.e. /conf/http.conf) and add following lines at the bottom of the file. However this virtualhost setting is a sample, you might have to make some changes as per your own environment.
  6. ############### mod_cluster Setting - STARTED ###############
    LoadModule slotmem_module modules/mod_slotmem.so
    LoadModule manager_module modules/mod_manager.so
    LoadModule proxy_cluster_module modules/mod_proxy_cluster.so
    LoadModule advertise_module modules/mod_advertise.so
    <VirtualHost *:80>
    	<Directory />
    		Order deny,allow
    		Allow from all
    	</Directory>
    	<Location /mod_cluster_manager>
    		SetHandler mod_cluster-manager
    		Order deny,allow
    		Allow from all
    	</Location>
    	KeepAliveTimeout 60
    	MaxKeepAliveRequests 0
    	ManagerBalancerName testcluster
    	AdvertiseFrequency 5
    </VirtualHost>
    ############### mod_cluster Setting - ENDED ###############
    

    NOTE:

    You have to COMMENT the follwoing module (i.e. mod_proxy_balancer.so) in “httpd.conf” file, or else you would get error while starting your Apache, this is been done because we are now using mod_proxy_cluster.so instead of mod_proxy_balancer.so

    #LoadModule proxy_balancer_module modules/mod_proxy_balancer.so
    
  7. Restart Apache.
  8. NOTE:

    You have to do the following things before starting the APACHE

    Command:

    setenforce 0
    

    The above command will disable SE Linux for your current running session. However if you want to disable it permanently then follow the below steps

    vi /etc/selinux/config
    
    #SELINUX=enforcing (comment this line and add the below line)
    SELINUX=disabled
    

    May be this would need to restart your system, this way you will be sure that the changes have taken place.

JBoss side configuration

  1. Copy “mod-cluster.sar” from “/home/testusr/AS6/mod_cluster” to “/server/cluster_node1/deploy”
  2. Edit “mod-cluster-jboss-beans.xml” from “<JBOSS_HOME>/server/cluster_node1/deploy/mod-cluster.sar/META-INF/mod-cluster-jboss-beans.xml” so that it has following.
  3. BELOW

    <bean name="HAModClusterConfig" class="org.jboss.modcluster.config.ha.HAModClusterConfig" mode="On Demand">
    
    <!-- START Comma separated list of address:port listing the httpd servers where mod_cluster is running. -->
        <property name="proxyList">${jboss.modcluster.proxyList:localhost:80}</property>
        <property name="domain">${jboss.Domain:DefaultDomain}</property>
    <!-- END Comma separated list of address:port listing the httpd servers where mod_cluster is running. -->
    
  4. Edit “server.xml” from “/server/all/deploy/jbossweb.sar/server.xml” so that it has following lines.
  5. <!-- START mod_cluster setting -->
         <Listener  className="org.jboss.web.tomcat.service.deployers.MicrocontainerIntegrationLifecycleListener" delegateBeanName="HAModClusterService"/>
    <!-- END mod_cluster setting -->
    

    NOTE:
    Make sure you add above line BEFORE/ABOVE

       <Service name="jboss.web">
    

    and

    <!-- START mod_cluster setting -->
         <Engine name="jboss.web" defaultHost="localhost" jvmRoute="${jboss.jvmRoute}">
    <!-- END mod_cluster setting -->
    

    NOTE:
    Make sure you replace above line instead of this line

          <Engine name="jboss.web" defaultHost="localhost">
    
  6. Edit “jboss-beans.xml” (/server/all/deploy/jbossweb.sar/META-INF/jboss-beans.xml) and add the below line in “bean” element
  7. <depends>HAModClusterService</depends>
    

Command to start the servers

Below is the command to start the serves in a cluster which are on the same Box/Physical Machine

NODE-1:

./run.sh -c cluster_node1 -g ClusterA -u 239.255.100.101 -b localhost -Djboss.Domain=test -Djboss.messaging.ServerPeerID=1 -Djboss.service.binding.set=ports-01 -Djboss.jvmRoute="node1"

NODE-2:

./run.sh -c cluster_node2 -g ClusterA -u 239.255.100.101 -b localhost -Djboss.Domain=test -Djboss.messaging.ServerPeerID=2 -Djboss.service.binding.set=ports-02 -Djboss.jvmRoute="node2"

URL to hit


http://localhost/mod_cluster_manager

Regards,

Middleware Magic


Configuring mod_jk to connect to JBoss

Hi,

Here is a simple step by step procedure to connect to JBoss instance for load balancing purpose through apache webserver. In most of the production environments this is the most common need.

The prerequisite for this exercise is to have the the Apache WebServer installed already in your Machine and the JBoss should be installed in your environment. The “mod_jk” module can be downloaded later to work on this setup. If you want to download the apache software and the mod_jk then you can refer to the link mentioned in the Step6):

JBoss Cluster Creation/Configuration Part:

Step1). As “all” and “production” profiles which are present inside the “E:jboss-AS6-5.1jboss-asserver” location are by default clustering enabled so you can chose any one of them to create your own clustered node. In this exercise we will use “all” profile to create JBoss Clusters.

So first copy the “all” profile and paste it in the same location “E:jboss-AS6-5.1jboss-asserver” with some different name like “all_node1″ and “all_node2″. like this your 2 JBoss Clustered Nodes are ready.

Step2). Now open the “server.xml” file present inside the “E:jboss-AS6-5.1jboss-asserverall_node1deployjbossweb.sar” location and then add the “jvmRoute” attribute of the Engine Tag like following:By default the line which you are going to change will look like following:
=============By default it will look like below==================

<Engine name="jboss.web" defaultHost="localhost">

=============After Change it will look like below==================

<Engine name="jboss.web" defaultHost="localhost" jvmRoute="node1">

Step3). Same changes we need to do for “all_node2″ profile as well. So open the “server.xml” file present inside the “E:jboss-AS6-5.1jboss-asserverall_node2deployjbossweb.sar” location and then add the “jvmRoute” attribute of the Engine Tag like following:
=============By default it will look like below==================

<Engine name="jboss.web" defaultHost="localhost">

=============After Change it will look like below==================

<Engine name="jboss.web" defaultHost="localhost" jvmRoute="node2">

Why We need “jvmRoute”?

jvmRoute Identifier must be used in load balancing scenarios to enable session affinity. The identifier, which must be unique across all Tomcat 6 servers which participate in the cluster, will be appended to the generated session identifier, therefore allowing the front end proxy to always forward a particular session to the same Tomcat 6 OR JBoss instance.

More information regarding this attribute can be found in the following link:
http://tomcat.apache.org/tomcat-6.0-doc/config/engine.html#Common_Attributes

Step4). Also please make sure that the AJP Connector Tag is uncommented in “E:jboss-AS6-5.1jboss-asserverall_node2deployjbossweb.sarserver.xml” file for both “all_node1″ & “all_node2″ profiles, Because the communication between Apache and JBoss will happen through this AJP connector port. Like following:

      <!-- A AJP 1.3 Connector on port 8009 -->
      <Connector protocol="AJP/1.3" port="8009" address="${jboss.bind.address}"
         redirectPort="8443" />

Step5). Now start Both the JBoss Instances by running the following command from the following dir “E:jboss-AS6-5.1jboss-as\bin”:

run.bat -c all_node1 -b 0.0.0.0 -g ClusterA -Djboss.service.binding.set=ports-01 -Djboss.messaging.ServerPeerID=1
run.bat -c all_node2 -b 0.0.0.0 -g ClusterA -Djboss.service.binding.set=ports-02 -Djboss.messaging.ServerPeerID=2

Here following are the meaning of the flags which we have used :
-c = The jboss profile which we want to start

-g = The name of the cluster. The same name of the cluster should be used by the profiles which want to join the same cluster formation.

-Djboss.service.binding.set = The advantage of this way is you don’t have to take (and maintain) a separate copy of the all folder if you want to, say, start up multiple instances of JBoss running as a cluster. For more information on this system property please refer to the following : http://community.jboss.org/wiki/ConfigurePorts

-Djboss.messaging.ServerPeerID = Each node must have a unique ServerPeerID for clustering to work!. It can be any unique integer value among all the cluster members. Means every cluster node should have a unique peer ID.

-b = The bind address in which you want to run your profile. o.o.o.o represents it will listen to all the IP Addresses associated with that box. better if we can specify a particular “IP Address” or “localhost” there rather than using “0.0.0.0″

So suppose if you are running your JBoss on two separate physical boxes which has different IP Addresses like 10.10.10.10 and 20.20.20.20 then please run the servers like following

run.bat -c all_node1 -b 10.10.10.10 -g ClusterA -Djboss.service.binding.set=ports-01 -Djboss.messaging.ServerPeerID=1
run.bat -c all_node2 -b 20.20.20.20 -g ClusterA -Djboss.service.binding.set=ports-02 -Djboss.messaging.ServerPeerID=2

Apache WebServer Configuration Part:

Step6). Download & Install the apache webserver from the following link along with the “mod_jk” file:
http://docs.redhat.com/docs/en-US/JBoss_Enterprise_Web_Platform/5/html/Administration_And_Configuration_Guide/clustering-http.html#clustering-http-modjk

Step7). Now paste the “mod_jk.so” file inside the modules directory of your apache which may be “C:Program FilesApache GroupApache2modules”

Step8). Now add the following line of configuration somewhere at the bottom inside your “C:Program FilesApache GroupApache2confhttpd.conf” file to include the mod_jk configuration file:

##### JBOSS #############
LoadModule jk_module modules/mod_jk.so

# Include mod_jk's specific configuration file
Include conf/mod_jk.conf
###########################

Step9). Now create a file with name “mod_jk.conf” inside the directory “C:Program FilesApache GroupApache2conf” as following:

##### JBOSS #############
# Load mod_jk module
# Specify the filename of the mod_jk lib
LoadModule jk_module modules/mod_jk.so

# Where to find workers.properties
JkWorkersFile conf/workers.properties

# Where to put jk logs
JkLogFile logs/mod_jk.log

# Set the jk log level [debug/error/info]
JkLogLevel info

# Select the log format
JkLogStampFormat  "[%a %b %d %H:%M:%S %Y]"

# JkOptions indicates to send SSK KEY SIZE
JkOptions +ForwardKeySize +ForwardURICompat -ForwardDirectories

# JkRequestLogFormat
JkRequestLogFormat "%w %V %T"

# Mount your applications
JkMount /* failover

# You can use external file for mount points.
# It will be checked for updates each 60 seconds.
# The format of the file is: /url=worker
# /examples/*=loadbalancer
#JkMountFile conf/uriworkermap.properties

# Add shared memory.
# This directive is present with 1.2.10 and
# later versions of mod_jk, and is needed for
# for load balancing to work properly
JkShmFile logs/jk.shm

# Add jkstatus for managing runtime data
<Location /jkstatus/>
    JkMount status
    Order deny,allow
    Deny from all
    Allow from 127.0.0.1
</Location>
###########################

Step10). Now create another most important file “worker.properties” inside “C:Program FilesApache GroupApache2conf” to tell apache to load balance between what all nodes of the JBoss clusters:

##### JBOSS #############
# Define list of workers that will be used
# for mapping requests
worker.list=failover
#,status

# Define Node2
# modify the host as your host IP or DNS name.
worker.node2.port=8209
worker.node2.host=20.20.20.20
worker.node2.type=ajp13
worker.node2.ping_mode=A
worker.node2.lbfactor=1

# Define Node1
# modify the host as your host IP or DNS name.
worker.node1.port=8109
worker.node1.host=10.10.10.10
worker.node1.type=ajp13
worker.node1.ping_mode=A
worker.node1.lbfactor=1

# Load-balancing behaviour
worker.loadbalancer.type=lb
worker.loadbalancer.balance_workers=node2,node1
worker.loadbalancer.sticky_session=False
worker.list=loadbalancer

# Status worker for managing load balancer
#worker.status.type=status
###########################

NOTE: Make sure that you are setting the correct “Hostname” and “AJP Port” for your JBoss in the above file.

Step 11). Now restart your apache server and then hit the following URL to access the JBoss:

http://localhost/jmx-console

OR

http://localhost/admin-console

.
.
Thanks
Middleware Magic


Implementing UsernameToken in WebService with Basic Authentication in JBoss AS6

Hi,

Securing WebService is one of the most basic requirement while developing and testing webservices. There are various ways for securing webservice applications. One of the technique is Securing WebServices using UserNameToken. In this technique of securing webservices the client sets a SOAP header in every request that contains a username and password. The password is sent in the header in plain text. To be secure all HTTP requests and responses should be SSL encrypted.

In this example we will see how we can secure a WebService which is going to be deployed on JBoss AS6 5.1.

Step1). Create a directory somewhere in your file system with some name like “C:/UserNameToken_WebService”. then create two directories with name “src” and “clientSrc” inside “UserNameToken_WebService” directory.

Step2). Write the WebService End point “UsernameEndpoint.java” inside “C:/UserNameToken_WebService/src” directory as following:

package wssecurity;
import javax.jws.WebMethod;
import javax.jws.WebResult;
import javax.jws.WebService;
import javax.jws.soap.SOAPBinding;

@WebService(name = "UsernameEndpoint", targetNamespace = "http://wssecurity")
@SOAPBinding(style = SOAPBinding.Style.RPC)
public interface UsernameEndpoint
  {
    @WebMethod
    @WebResult(partName = "return")
    public String getUsernameToken();

  }

Step3). Write the Service implementation class “UsernameBean.java” program inside “C:/UserNameToken_WebService/src” directory like following:

package wssecurity;
import java.security.Principal;
import javax.annotation.Resource;
import javax.jws.WebMethod;
import javax.jws.WebResult;
import javax.jws.WebService;
import javax.jws.soap.SOAPBinding;
import javax.xml.ws.WebServiceContext;
import org.jboss.ws.annotation.EndpointConfig;

@WebService(name = "UsernameEndpoint", serviceName = "UsernameService", targetNamespace = "http://wssecurity")
@EndpointConfig(configName = "Standard WSSecurity Endpoint")
@SOAPBinding(style = SOAPBinding.Style.RPC)
NOTE:e If you will not set fork="true"    in the client's run target (as mentioned in line-150 of above script) then the jvmargs wil be ignored
public class UsernameBean
{
   @Resource
   WebServiceContext wsCtx;

   @WebMethod
   @WebResult(partName = "return")
   public String getUsernameToken()
   {
      Principal principal = wsCtx.getUserPrincipal();
      System.out.println("nt[WebService- UsernameBean] getUsernameToken: " + principal);
      return "Hello User: "+principal.toString();
   }
}

Step4). Write the “jboss-wsee-server.xml” if you want to add any additional security feature for your webservice. Put it inside inside “C:/UserNameToken_WebService/src” directory like following (Currently it does not have anything specific to WSSE):

<?xml version="1.0" encoding="UTF-8"?>
<jboss-ws-security xmlns="http://www.jboss.com/ws-security/config" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://www.jboss.com/ws-security/config http://www.jboss.com/ws-security/schema/jboss-ws-security_1_0.xsd">
</jboss-ws-security>

Step5). Create a “web.xml” file inside “C:/UserNameToken_WebService/src” to describe the WebService servlet declaration like following:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd" version="2.4">
  <servlet>
    <servlet-name>UsernameService</servlet-name>
    <servlet-class>org.jboss.wsf.stack.jbws.EndpointServlet</servlet-class>
    <init-param>
      <param-name>jboss.ws.endpoint</param-name>
      <param-value>wssecurity.UsernameBean</param-value>
    </init-param>
  </servlet>

  <servlet-mapping>
    <servlet-name>UsernameService</servlet-name>
    <url-pattern>/*</url-pattern>
  </servlet-mapping>

  <security-constraint>
    <web-resource-collection>
      <web-resource-name>UsernameService</web-resource-name>
      <url-pattern>/*</url-pattern>
      <http-method>GET</http-method>
      <http-method>POST</http-method>
    </web-resource-collection>
    <auth-constraint>
      <role-name>friend</role-name>
    </auth-constraint>
  </security-constraint>
  <login-config>
    <auth-method>BASIC</auth-method>
    <realm-name>JBossWS</realm-name>
  </login-config>
  <security-role>
    <role-name>friend</role-name>
  </security-role>
</web-app>

Step6). Create a “jboss-web.xml” file inside “C:/UserNameToken_WebService/src” to describe the define the security Domain configuration for your webservice authentication/authorization purpose like following:

<?xml version="1.0" encoding="UTF-8"?>
<jboss-web>
  <security-domain>java:/jaas/JBossWS</security-domain>
</jboss-web>

NOTE: Here we are using the default web service security domain policy, which is configured already inside “$PROFILE/conf/login-config.xml” file as following:

<?xml version="1.0" encoding="UTF-8"?>
  <application-policy name="JBossWS">
    <authentication>
      <login-module code="org.jboss.security.auth.spi.UsersRolesLoginModule" flag="required">
        <module-option name="usersProperties">props/jbossws-users.properties</module-option>
        <module-option name="rolesProperties">props/jbossws-roles.properties</module-option>
        <module-option name="unauthenticatedIdentity">anonymous</module-option>
      </login-module>
    </authentication>
  </application-policy>

NOTE: And the username and password’s are mentioned in “$PROFILE/conf/props/jbossws-users.properties” this username/password is COMMENTED in this file …So please uncomment it. You can follow previous directory as following the previously posted articles if you want to create your own roles and users and application-policies:

Step7). Now we will write the Client “SimpleUsernameTestCase.java” inside “C:/UserNameToken_WebService/clientSrc” directory as following:

package client.wssecurity;
import java.io.File;
import java.net.URL;
import java.util.Map;
import javax.xml.namespace.QName;
import javax.xml.ws.BindingProvider;
import javax.xml.ws.Service;
import org.jboss.ws.core.StubExt;
import org.jboss.wsf.test.JBossWSTestSetup;

public class SimpleUsernameTestCase
{
   private static UsernameEndpoint port;
    public static void main(String ar[]) throws Exception
    {
         SimpleUsernameTestCase client=new SimpleUsernameTestCase();

         URL wsdlURL = client.getClass().getClassLoader().getResource("META-INF/wsdl/UsernameTokenService.wsdl");  //new File("META-INF/wsdl/UsernameService.wsdl").toURL();
         URL securityURL = client.getClass().getClassLoader().getResource("META-INF/jboss-wsse-client.xml");
         System.out.println("WSDL URL: "+wsdlURL);
         System.out.println("Security URL: "+securityURL);

         System.out.println(" org.jboss.ws.core.StubExt loaded .." + org.jboss.ws.core.StubExt.class.getProtectionDomain().getCodeSource().getLocation());
         QName serviceName = new QName("http://wssecurity", "UsernameService");
         Service service = Service.create(wsdlURL, serviceName);

         port = (UsernameEndpoint)service.getPort(UsernameEndpoint.class);
         System.out.println("nt2 ");

         ((org.jboss.ws.core.StubExt)port).setSecurityConfig(securityURL.toExternalForm());
         ((org.jboss.ws.core.StubExt)port).setConfigName("Standard WSSecurity Client");

         System.out.println("nt3 ");
         Map<String, Object> reqContext = ((BindingProvider)port).getRequestContext();
         reqContext.put(BindingProvider.USERNAME_PROPERTY, "kermit");
         reqContext.put(BindingProvider.PASSWORD_PROPERTY, "thefrog");
         System.out.println("nt4 ");
         String retObj = port.getUsernameToken();
         System.out.println("nt5 Call Successfuly Made.");
    }
}

Step8). Just incase if you want to add some security related informations from Client side as well in that case you can place the following file at client side. So create a file with name “C:/UserNameToken_WebService/clientSrc/META-INF/jboss-wsse-client.xml” like following:

<?xml version="1.0" encoding="UTF-8"?>
<jboss-ws-security xmlns="http://www.jboss.com/ws-security/config"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://www.jboss.com/ws-security/config http://www.jboss.com/ws-security/schema/jboss-ws-security_1_0.xsd">
  <config>
      <username/>
  </config>
</jboss-ws-security>

Step9). Now write the ant build script “build.xml” file inside “C:/UserNameToken_WebService” as following:

<project name="JBoss_Service" default="post-deploy">
<property name="jboss.home" value="/home/userone/JBoss_All/jboss-AS6/jboss-as" />
<property name="jboss.profile" value="${jboss.home}/server/default_Audit" />
<property name="java.home.dir" value="/home/userone/MyJdks/jdk1.6.0_05" />
<property name="basedir" value="." />
<property name="war.name" value="UsernameTokenService.war" />
<property name="src.dir" value="src" />
<property name="client.src.dir" value="${basedir}/clientSrc" />
<property name="dest.dir" value="build" />
<property name="client.dir" value="${basedir}/clientStuff" />
<property name="client.jar.name" value="usernameTokenClient.jar" />

<path id="jboss.classpath">
   <fileset dir="${jboss.home}/lib/endorsed">
      <include name="*.jar"/>
   </fileset>
   <fileset dir="${jboss.home}/common/lib">
      <include name="*.jar"/>
   </fileset>
   <fileset dir="${jboss.home}/lib">
      <include name="*.jar"/>
   </fileset>
   <fileset dir="${jboss.home}/client">
      <include name="*.jar"/>
      <!-- this Jar contains "org.jboss.ws.annotation.EndpointConfig"  -->
   </fileset>
   <fileset dir="${java.home.dir}/jre/lib">
       <include name="rt.jar" />
   </fileset>
   <fileset dir="${java.home.dir}/lib">
       <include name="tools.jar" />
   </fileset>
</path>

<path id="jboss.client.classpath">
   <fileset dir="${jboss.home}/lib/endorsed">
      <include name="*.jar"/>
   </fileset>

   <fileset dir="${jboss.home}/client">
      <include name="activation.jar"/>
      <include name="getopt.jar"/>
      <include name="wstx.jar"/>
      <include name="jbossall-client.jar"/>
      <include name="log4j.jar"/>
      <include name="mail.jar"/>
      <include name="jbossws-spi.jar"/>
      <include name="jbossws-common.jar"/>
      <include name="jbossws-framework.jar"/>

      <!--# Shared jaxws libs -->
      <include name="jaxws-tools.jar"/>
      <include name="jaxws-rt.jar"/>
      <include name="stax-api.jar"/>
      <include name="jaxb-api.jar"/>
      <include name="jaxb-impl.jar"/>
      <include name="jaxb-xjc.jar"/>
      <include name="streambuffer.jar"/>
      <include name="stax-ex.jar"/>

      <!--# Stack specific dependencies -->
      <include name="javassist.jar"/>
      <include name="jboss-xml-binding.jar"/>
      <include name="jbossws-native-client.jar"/>
      <include name="jbossws-native-core.jar"/>
      <include name="jbossws-native-jaxws.jar"/>
      <include name="jbossws-native-jaxws-ext.jar"/>
      <include name="jbossws-native-jaxrpc.jar"/>
      <include name="jbossws-native-saaj.jar"/>
   </fileset>

</path>

        <taskdef name="apt" classname="com.sun.tools.ws.ant.Apt">
 	  <classpath refid="jboss.classpath"/>
	</taskdef>
        <taskdef name="wsimport" classname="com.sun.tools.ws.ant.WsImport">
          <classpath refid="jboss.classpath"/>
        </taskdef>

        <target name="prepare">
           <delete dir="${dest.dir}" />
           <mkdir dir="${dest.dir}" />
           <mkdir dir="${dest.dir}/${war.name}"/>
           <mkdir dir="${dest.dir}/${war.name}/WEB-INF"/>
           <mkdir dir="${dest.dir}/${war.name}/WEB-INF/classes"/>
           <delete dir="${client.dir}" />
           <mkdir dir="${client.dir}"/>
        </target>

	<target name="build-service" depends="prepare">
	    <apt    fork="true"
	            destdir="${dest.dir}/${war.name}/WEB-INF/classes"
	            sourcedestdir="${dest.dir}/${war.name}/WEB-INF/classes"
	            sourcepath="${src.dir}">
	        <classpath>
	            <path refid="jboss.classpath"/>
	            <pathelement location="${basedir}/src"/>
	        </classpath>
	        <source dir="${basedir}">
	            <include name="src/**/*.java"/>
	        </source>
	    </apt>
	    <!-- copy handlers descriptor file -->
	    <copy todir="${dest.dir}/${war.name}/WEB-INF">
	        <fileset dir="${basedir}/src">
	            <include name="**/*.xml"/>
	        </fileset>
	    </copy>
	</target>

        <target name="deploy" depends="build-service">
             <copy todir="${jboss.profile}/deploy">
                  <fileset dir="./build"/>
             </copy>
        </target>

        <target name="post-deploy" depends="deploy">
            <echo message="*******************  NOTE  *********************" />
            <echo message="WebService deployed Successfully. As the Basic Authentication is Enabled for this webservice"/>
            <echo message="So Access the WSDL in following format from Browser"/>
            <echo message="http://kermit:thefrog@localhost:8080/UsernameTokenService?wsdl" />
            <echo message="Syntax: " />
            <echo message="http://Username:Password@localhost:8080/UsernameTokenService?wsdl" />
            <echo message="and then store it in your file system with following name:" />
            <echo message="${client.src.dir}/META-INF/wsdl/UsernameTokenService.wsdl "/>
            <echo message="And then run the ' ant client' To generate client artifacts" />
            <echo message="************************************************" />
        </target>

        <target name="client" >
            <delete dir="${client.dir}" />
            <mkdir dir="${client.dir}"/>
            <mkdir dir="${client.dir}/META-INF"/>
            <wsimport destdir="${client.dir}"
                      wsdl="${client.src.dir}/META-INF/wsdl/UsernameTokenService.wsdl"
                      package="client.wssecurity"
                      keep="true">
            </wsimport>

            <javac srcdir="${client.src.dir}" destdir="${client.dir}"  includes="SimpleUsernameTestCase.java" classpathref="jboss.client.classpath"/>
            <jar jarfile="${client.dir}/${client.jar.name}" basedir="${client.dir}" compress="true" >
                <metainf dir="${client.src.dir}/META-INF">
                    <filename name="**/*"/>
                </metainf>
            </jar>
        </target>

        <target name="run" >
            <java classname="client.wssecurity.SimpleUsernameTestCase" fork="true"  >
	        <classpath>
	            <pathelement location="${client.dir}/${client.jar.name}"/>
	            <path refid="jboss.client.classpath"/>
	        </classpath>
                <jvmarg line="-Djava.endorsed.dirs=/home/userone/JBoss_All/jboss-AS6/jboss-as/lib/endorsed" />
            </java>
        </target>
</project>

NOTE:

If you will not set fork=”true” in the client’s run target (as mentioned in line-150 of above script) then the jvmargs wil be ignored and the “Dava.endorsed.dirs” will not be honored so you will see the following kind of exception while running your client application. So you must set the “-Djava.endorsed.dirs” to tell the client to use the JBoss’s JAXWS implementation over the JVM’s.

     [java] javax.xml.ws.WebServiceException: java.lang.UnsupportedOperationException: setProperty must be overridden by all subclasses of SOAPMessage
     [java] 	at org.jboss.ws.core.jaxws.client.ClientImpl.handleRemoteException(ClientImpl.java:310)
     [java] 	at org.jboss.ws.core.jaxws.client.ClientImpl.invoke(ClientImpl.java:243)
     [java] 	at org.jboss.ws.core.jaxws.client.ClientProxy.invoke(ClientProxy.java:171)
     [java] 	at org.jboss.ws.core.jaxws.client.ClientProxy.invoke(ClientProxy.java:157)
     [java] 	at $Proxy7.getUsernameToken(Unknown Source)


Step10).
Now open a command/shell prompt and make sure that ANT and JAVA path is set properly init like following and then run the ant to build and deploy the webservice:

export PATH=/home/userone/MyJdks/jdk1.6.0_21/bin:/home/userone/JBoss_All/jboss-AS6/jboss-as/bin:/home/userone/org.apache.ant_1.6.5/bin:$PATH

[userone@localhost UserNameToken_WebService]$ ant
Buildfile: build.xml

prepare:
   [delete] Deleting directory /home/userone/Downloads/UserNameToken_WebService/build
    [mkdir] Created dir: /home/userone/Downloads/UserNameToken_WebService/build
    [mkdir] Created dir: /home/userone/Downloads/UserNameToken_WebService/build/UsernameTokenService.war
    [mkdir] Created dir: /home/userone/Downloads/UserNameToken_WebService/build/UsernameTokenService.war/WEB-INF
    [mkdir] Created dir: /home/userone/Downloads/UserNameToken_WebService/build/UsernameTokenService.war/WEB-INF/classes
   [delete] Deleting directory /home/userone/Downloads/UserNameToken_WebService/clientStuff
    [mkdir] Created dir: /home/userone/Downloads/UserNameToken_WebService/clientStuff

build-service:
      [apt] warning: Annotation types without processors: [org.jboss.ws.annotation.EndpointConfig, javax.annotation.Resource]
      [apt] 1 warning
     [copy] Copying 2 files to /home/userone/Downloads/UserNameToken_WebService/build/UsernameTokenService.war/WEB-INF

deploy:
     [copy] Copying 4 files to /home/userone/JBoss_All/jboss-AS6/jboss-as/server/default_Audit/deploy

post-deploy:
     [echo] *******************  NOTE  *********************
     [echo] WebService deployed Successfully. As the Basic Authentication is Enabled for this webservice
     [echo] So Access the WSDL in following format from Browser
     [echo] http://kermit:thefrog@localhost:8080/UsernameTokenService?wsdl
     [echo] Syntax:
     [echo] http://Username:Password@localhost:8080/UsernameTokenService?wsdl
     [echo] and then store it in your file system with following name:
     [echo] /home/userone/Downloads/UserNameToken_WebService/clientSrc/META-INF/wsdl/UsernameTokenService.wsdl
     [echo] And then run the ' ant client' To generate client artifacts
     [echo] ************************************************

BUILD SUCCESSFUL
Total time: 3 seconds

Step11). WebService deployed Successfully. As the Basic Authentication is Enabled for this webservice, So Access the WSDL in following format from Web Browser as following :

http://kermit:thefrog@localhost:8080/UsernameTokenService?wsdl

Syntax:

http://Username:Password@localhost:8080/UsernameTokenService?wsdl

And then save it in your file system with following name: “/home/userone/Downloads/UserNameToken_WebService/clientSrc/META-INF/wsdl/UsernameTokenService.wsdl” And then run the ‘ant client’ To generate client artifacts.

[userone@localhost UserNameToken_WebService]$ ant client
Buildfile: build.xml

client:
   [delete] Deleting directory /home/userone/UserNameToken_WebService/clientStuff
    [mkdir] Created dir: /home/userone/UserNameToken_WebService/clientStuff
    [mkdir] Created dir: /home/userone/UserNameToken_WebService/clientStuff/META-INF
 [wsimport] Consider using <depends>/<produces> so that wsimport won't do unnecessary compilation
 [wsimport] parsing WSDL...

 [wsimport] generating code...

 [wsimport] compiling code...

    [javac] Compiling 1 source file to /home/userone/UserNameToken_WebService/clientStuff
      [jar] Building jar: /home/userone/UserNameToken_WebService/clientStuff/usernameTokenClient.jar

BUILD SUCCESSFUL
Total time: 5 seconds
[userone@localhost UserNameToken_WebService]$

Step12). Now you can run the ant script to execute the client program:

[userone@localhost UserNameToken_WebService]$ ant run
Buildfile: build.xml

run:
     [java] WSDL URL: jar:file:/home/userone/UserNameToken_WebService/clientStuff/usernameTokenClient.jar!/META-INF/wsdl/UsernameTokenService.wsdl
     [java] Security URL: jar:file:/home/userone/UserNameToken_WebService/clientStuff/usernameTokenClient.jar!/META-INF/jboss-wsse-client.xml
     [java]  org.jboss.ws.core.StubExt loaded ..file:/home/userone/JBoss_All/jboss-AS6/jboss-as/client/jbossws-native-core.jar
     [java] log4j:WARN No appenders could be found for logger (org.jboss.ws.metadata.builder.jaxws.JAXWSWebServiceMetaDataBuilder).
     [java] log4j:WARN Please initialize the log4j system properly.

     [java] 	2

     [java] 	3

     [java] 	4

     [java] 	5 Call Successfuly Made.

BUILD SUCCESSFUL
Total time: 3 seconds

Step13). If you want to see how the SOAP messages are being sent and received then please add the following category in your “$PROFILE/conf/jboss-log4j.xml” file so that the SOAP messages will start appearing in the server.log file.

   <!-- Enable JBossWS message tracing -->
   <category name="org.jboss.ws.core.MessageTrace">
     <priority value="TRACE"/>
   </category>

Step14). Once you will enable the above category in jboss-log4j.xml file then in your server log you will be able to see the following kind of SOAP messages with the username tokens:

15:21:38,585 TRACE [org.jboss.ws.core.MessageTrace] (http-127.0.0.1-8080-1) Incoming Request Message
<env:Envelope xmlns:env='http://schemas.xmlsoap.org/soap/envelope/'>
 <env:Header>
  <wsse:Security env:mustUnderstand='1' xmlns:ds='http://www.w3.org/2000/09/xmldsig#' xmlns:wsse='http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd' xmlns:wsu='http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd'>
   <wsse:UsernameToken wsu:Id='token-1-1317030698447-695206801'>
    <wsse:Username>kermit</wsse:Username>
    <wsse:Password Type='http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText'>thefrog</wsse:Password>
   </wsse:UsernameToken>
  </wsse:Security>
 </env:Header>
 <env:Body>
  <ns1:getUsernameToken xmlns:ns1='http://wssecurity'/>
 </env:Body>
</env:Envelope>

15:21:38,590 INFO  [STDOUT] (http-127.0.0.1-8080-1)
	[WebService- UsernameBean] getUsernameToken: kermit
15:21:38,592 TRACE [org.jboss.ws.core.MessageTrace] (http-127.0.0.1-8080-1) Outgoing Response Message
<env:Envelope xmlns:env='http://schemas.xmlsoap.org/soap/envelope/'>
 <env:Header/>
 <env:Body>
  <ns1:getUsernameTokenResponse xmlns:ns1='http://wssecurity'>
   <return>Hello User: kermit</return>
  </ns1:getUsernameTokenResponse>
 </env:Body>
</env:Envelope>

Step15). If you even want to see the Http Request response details (like http headers/cookies) in the server STDOUT then in that case you can UNCOMMENT the following section in “$PROFILE/deploy/jbossweb.sar/server.xml” file

            <!--
            <Valve className="org.apache.catalina.valves.RequestDumperValve" />
            -->

Step16). Restart you JBoss AS6 profile and then you will start seeing following kind of Http Request Tracing in your server’s STDOUT while making an application call:

15:37:47,292 INFO  [ServerImpl] JBoss (Microcontainer) [5.1.0 (build: SVNTag=JBPAPP_5_1_0 date=201009150028)] Started in 25s:758ms
15:37:57,179 INFO  [[localhost]] REQUEST URI       =/UsernameTokenService
15:37:57,185 INFO  [[localhost]]           authType=null
15:37:57,187 INFO  [[localhost]]  characterEncoding=UTF-8
15:37:57,187 INFO  [[localhost]]      contentLength=-1
15:37:57,187 INFO  [[localhost]]        contentType=text/xml; charset=UTF-8
15:37:57,188 INFO  [[localhost]]        contextPath=/UsernameTokenService
15:37:57,191 INFO  [[localhost]]             header=authorization=Basic a2VybWl0OnRoZWZyb2c=
15:37:57,191 INFO  [[localhost]]             header=soapaction=""
15:37:57,191 INFO  [[localhost]]             header=content-type=text/xml; charset=UTF-8
15:37:57,191 INFO  [[localhost]]             header=jboss-remoting-version=22
15:37:57,191 INFO  [[localhost]]             header=user-agent=JBossRemoting - 2.5.3.SP1 (Flounder)
15:37:57,191 INFO  [[localhost]]             header=remotingcontenttype=remotingContentTypeNonString
15:37:57,191 INFO  [[localhost]]             header=host=127.0.0.1:8080
15:37:57,191 INFO  [[localhost]]             header=accept=text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2
15:37:57,191 INFO  [[localhost]]             header=connection=keep-alive
15:37:57,191 INFO  [[localhost]]             header=transfer-encoding=chunked
15:37:57,191 INFO  [[localhost]]             locale=en_US
15:37:57,191 INFO  [[localhost]]             method=POST
15:37:57,193 INFO  [[localhost]]           pathInfo=/
15:37:57,193 INFO  [[localhost]]           protocol=HTTP/1.1
15:37:57,193 INFO  [[localhost]]        queryString=null
15:37:57,194 INFO  [[localhost]]         remoteAddr=127.0.0.1
15:37:57,194 INFO  [[localhost]]         remoteHost=127.0.0.1
15:37:57,194 INFO  [[localhost]]         remoteUser=null
15:37:57,194 INFO  [[localhost]] requestedSessionId=null
15:37:57,194 INFO  [[localhost]]             scheme=http
15:37:57,194 INFO  [[localhost]]         serverName=127.0.0.1
15:37:57,194 INFO  [[localhost]]         serverPort=8080
15:37:57,194 INFO  [[localhost]]        servletPath=
15:37:57,194 INFO  [[localhost]]           isSecure=false
15:37:57,194 INFO  [[localhost]] ---------------------------------------------------------------
15:37:57,425 INFO  [STDOUT]
	[WebService- UsernameBean] getUsernameToken: kermit
15:37:57,439 INFO  [[localhost]] ---------------------------------------------------------------
15:37:57,440 INFO  [[localhost]]           authType=BASIC
15:37:57,440 INFO  [[localhost]]      contentLength=-1
15:37:57,440 INFO  [[localhost]]        contentType=text/xml;charset=UTF-8
15:37:57,440 INFO  [[localhost]]             header=X-Powered-By=Servlet 2.5; JBoss-5.0/JBossWeb-2.1
15:37:57,440 INFO  [[localhost]]             header=Content-Type=text/xml;charset=UTF-8
15:37:57,440 INFO  [[localhost]]             header=Transfer-Encoding=chunked
15:37:57,440 INFO  [[localhost]]             header=Date=Mon, 26 Sep 2011 10:07:57 GMT
15:37:57,440 INFO  [[localhost]]            message=null
15:37:57,440 INFO  [[localhost]]         remoteUser=kermit
15:37:57,440 INFO  [[localhost]]             status=200
15:37:57,440 INFO  [[localhost]] ===============================================================

.
.
Thanks
Middleware Magic Team


Listing & Deleting Messages from JMS Queue using JMX

Hi,

Many times due to different requirement it is desired to list all the Messages present inside the JMS Queue. Also some times it is required to delete all the messages present inside the JMS Queue. jmx-console can be used to perform the same tasks, but most of the time in production environments we disable the jmx-console or admin-console. So in such scenarios we can use the following kind of JMX code to list and if required then delete the Messages present inside the JMS Queue.

In this sample we will be using the default JMS Queue provided by JBoss as “queue/DLQ” but if you want to create your own JMS Queue then you can refer to the following article “How to create a Queue in JBoss ?“. Also we will be using a simple “QueueSend.java” program to send some test messages in the JMS Queue and then with the help of “ManageJMSQueue.java” program we will list the JMS Messages present inside the JMS Queue and if required we will delete them through the same JMX Code.

Step1). Write the Simple “QueueSend.java” program somewhere in your file system to send some JMS Messages to the JMS Queue “queue/DLQ” as following:

import java.io.*;
import java.util.Hashtable;
import javax.jms.JMSException;
import javax.jms.Queue;
import javax.jms.QueueConnection;
import javax.jms.QueueConnectionFactory;
import javax.jms.QueueSender;
import javax.jms.QueueSession;
import javax.jms.Session;
import javax.jms.TextMessage;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;

public class QueueSend
{
	public final static String JNDI_FACTORY="org.jnp.interfaces.NamingContextFactory";
	public final static String JMS_FACTORY="/XAConnectionFactory";
	public final static String QUEUE="/queue/DLQ";
	private QueueConnectionFactory qconFactory;
	private QueueConnection qcon;
	private QueueSession qsession;
	private QueueSender qsender;
	private Queue queue;
	private TextMessage msg;

public void init(Context ctx, String queueName)throws NamingException, JMSException
     {
	qconFactory = (QueueConnectionFactory) ctx.lookup(JMS_FACTORY);
	qcon = qconFactory.createQueueConnection();
	qsession = qcon.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
	queue = (Queue) ctx.lookup(queueName);
	qsender = qsession.createSender(queue);
	msg = qsession.createTextMessage();
	qcon.start();
     }

public void send(String message) throws JMSException
     {
	msg.setText(message);
	qsender.send(msg);
     }

public void close() throws JMSException
     {
	qsender.close();
	qsession.close();
	qcon.close();
     }

public static void main(String[] args) throws Exception {
	if (args.length != 1) {
	System.out.println("Usage: java QueueSend JBossURL");
	System.out.println("Example: java QueueSend localhost:1099");
	return;
	}
	InitialContext ic = getInitialContext(args[0]);
	QueueSend qs = new QueueSend();
	qs.init(ic, QUEUE);
	readAndSend(qs);
	qs.close();
	}

private static void readAndSend(QueueSend qs) throws IOException, JMSException
    {
	String line="Test Message Body with counter = ";
	BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
	boolean readFlag=true;
	System.out.println("ntStart Sending Messages (Enter QUIT to Stop):n");
        int i=1;
	while(readFlag)
	{
	   System.out.print("<Msg_Sender> ");
	   String msg=br.readLine();
	   if(msg.equals("QUIT") || msg.equals("quit"))
	    {
	        qs.send(msg);
        	System.exit(0);
 	    }
        qs.send(msg);
        System.out.println("ttt msg sent: "+i+"t "+msg);
        i++;
        System.out.println();
	}
	br.close();
     }

private static InitialContext getInitialContext(String url) throws NamingException
    {
	Hashtable<String,String> env = new Hashtable<String,String>();
	env.put(Context.INITIAL_CONTEXT_FACTORY, JNDI_FACTORY);
	env.put(Context.PROVIDER_URL, url);
	return new InitialContext(env);
    }
}

Step2). Now write the “ManageJMSQueue.java” program as following in order to list the messages present inside the JMS Queue “queue/DLQ” and if required delete them through the same code.

import javax.management.*;
import java.io.*;
import java.util.*;
import java.rmi.*;
import javax.naming.*;
import java.io.*;
public class ManageJMSQueue
   {
      private MBeanServerConnection server=null;
      public ManageJMSQueue()
      {
            try{
            Hashtable<String,String> ht=new Hashtable<String,String>();
            ht.put(Context.INITIAL_CONTEXT_FACTORY,"org.jboss.security.jndi.JndiLoginInitialContextFactory");
            ht.put(Context.PROVIDER_URL,"localhost:1099");
            ht.put(Context.SECURITY_PRINCIPAL,"admin");
            ht.put(Context.SECURITY_CREDENTIALS,"admin");
            System.out.println("nt 1- Gotting InitialContext...... ");
            Context ctx = new InitialContext(ht);
            System.out.println("nt 2- Got InitialContext: "+ctx);
            server = (MBeanServerConnection) ctx.lookup("jmx/invoker/RMIAdaptor");
            }
            catch(Exception e)
            {
                System.out.println("nnt Exception inside ManageJMSQueue..."+e);
            }
      }

      public void monitorJMS() throws Exception
      {
           ObjectName objectName=new ObjectName("jboss.messaging.destination:name=DLQ,service=Queue");
           System.out.println("nnServerPeer = "+ (javax.management.ObjectName)server.getAttribute(objectName, new String("ServerPeer")));
           System.out.println("QueueName = "+ (String)server.getAttribute(new ObjectName("jboss.messaging.destination:name=DLQ,service=Queue"), new String("Name")));
           System.out.println("JNDI Name = "+ (String)server.getAttribute(new ObjectName("jboss.messaging.destination:name=DLQ,service=Queue"), new String("JNDIName")));
           System.out.println("FullSize = "+ (Integer)server.getAttribute(new ObjectName("jboss.messaging.destination:name=DLQ,service=Queue"), new String("FullSize")));
      }

     public void listAllJMS_Messages() throws Exception
      {
           ObjectName objectName=new ObjectName("jboss.messaging.destination:name=DLQ,service=Queue");
           List<org.jboss.jms.message.JBossTextMessage> messages=(List<org.jboss.jms.message.JBossTextMessage>)server.invoke(objectName, "listAllMessages" , null, null);
           int count=0;
           for(org.jboss.jms.message.JBossTextMessage msg : messages)
                    System.out.println((++count)+"t"+msg.getText());
      }

     public void removeAllJMS_Messages() throws Exception
      {
           String queueName=(String)server.getAttribute(new ObjectName("jboss.messaging.destination:name=DLQ,service=Queue"), new String("Name"));
           System.out.println("nt Removing all JMS Messages from Queue: "+queueName);
           server.invoke(new ObjectName("jboss.messaging.destination:name=DLQ,service=Queue"), "removeAllMessages" , null, null);
           System.out.println("nt All the Messages are removed from JMS Queue: "+queueName);
      }

     public static void main(String ar[]) throws Exception
       {
            ManageJMSQueue ref=new ManageJMSQueue();
            ref.monitorJMS();
            System.out.println("nt Following Messages Are present inside the JMS Queue:");
            ref.listAllJMS_Messages();
            BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
            System.out.print("nn Please Specify (yes/no) to delete all the messages from JMS Queue ? ");
            String answer="";
            if((answer=br.readLine()).equals("yes"))
                             ref.removeAllJMS_Messages();
            br.close();
       }
  }

Step3). Compile and then run the “QueueSend.java” program as following and then send some messages to the JMS Queue:

javac QueueSend.java
java QueueSend localhost:1099
	Start Sending Messages (Enter QUIT to Stop):

<Msg_Sender> TestMessageOne
			 msg sent: 1	 TestMessageOne

<Msg_Sender> TestMessageTwo
			 msg sent: 2	 TestMessageTwo

<Msg_Sender> TestMessageThree
			 msg sent: 3	 TestMessageThree

<Msg_Sender> quit

Step4). After sending some Messages to the JMS Queue “queue/DLQ” Compile and then run the “ManageJMSQueue” program as following to list the messages present inside the JMS Queue:

javac ManageJMSQueue.java
java ManageJMSQueue localhost:1099

	 1- Gotting InitialContext......
	 2- Got InitialContext: javax.naming.InitialContext@74341960

ServerPeer = jboss.messaging:service=ServerPeer
QueueName = DLQ
JNDI Name = /queue/DLQ
FullSize = 200000

	 Following Messages Are present inside the JMS Queue:
1	TestMessageOne
2	TestMessageTwo
3	TestMessageThree
4	quit

 Please Specify (yes/no) toi delete all the messages from JMS Queue ? yes
	 Removing all JMS Messages from Queue: DLQ
	 All the Messages are removed from JMS Queue: DLQ

.
.
Thanks
Middleware Magic Team


  • Receive FREE Updates


    FREE Email updates of our new posts Enter your email address:



  • Magic Archives

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