Spring integrating with remote Topic

Hi,
I am going to demonstrate how to receive messages from a remote topic.

The remote Topic is placed in a Jboss application server.

1. Add topic implementation jars into spring lib class-path

2. We going to create jmsTemplate makes the java code pretty minimal and simple:

public class TgwMDB implements MessageListener
{

	@Override
	public void onMessage(Message msg)
	{
	}
}

3. Most of the configuration is at the applicationContextXml:

3.1 Declare jmsTemplate:

 	jnp://server.ip:1099
	org.jnp.interfaces.NamingContextFactory
	org.jboss.naming:org.jnp.interfaces

3.2 declare jndiTopicConnFactory.

	

3.3 declare ConnectionFactory:


3.4. declare DestinationResolver:

3.5 declare DefaultMessageListenerContainer which will act as a cached message listener

		 // this property pubSubDomain turns the listener from Queue to Topic.

 


You ready now to receive messages.

Idan.

[ad]

Related Articles:

(1801)

Ejb lookup from StandAlone/Tomcat to Jboss5+

Hi,

Lately I was trying to do EJB lookup from my Web Application (Tomcat 6) to my Jboss project(Jboss5.1)

That should be pretty simple but without the right jars it just wont work.

So:

1. Take all jars from the client dir of jboss (Jboss_home_dir/Client/) and put them under the Lib dir of your web project which deployed under tomcat.

2. The client code which does the EJB look up will look like that:


private void ejbCall() throws NamingException
	{

		Properties p = new Properties();
		p.put(Context.INITIAL_CONTEXT_FACTORY, "org.jnp.interfaces.NamingContextFactory");
		p.setProperty("java.naming.factory.url.pkgs", "org.jboss.naming");
		p.put(Context.PROVIDER_URL, "jnp://remote.server.ip:1099");
		InitialContext context = new InitialContext(p);
		String lookupStr = "jndi-remote-lookup-string";
		DispactherBeanRemote dispactherBean = (DispactherBeanRemote) context.lookup(lookupStr);
		MomDispatcherResponseMsgDTO momDispatcherResponseMsgDTO =  dispactherBean.dispatchMsg();
		System.out.println("dispactherBean ="+ momDispatcherResponseMsgDTO.toString());
	}

Again, dont forget to add all the jars from the jboss client. Else you will get lots of weird exceptions,

[ad]

Idan.

Related Articles:

(1801)

Define jboss logs in the application level.

Hi,
The next post will demonstrate how to define jboss logs for a specific application
in a way that it will write all it’s logs to an independent log file.

(tested on Jboss5.1 AS)

Under jboss-dir/conf we have file named: jboss-log4j.xml

1. let’s add new appender:

  
     
     
     
     
     

     
       
     
   

2. let’s add category:

   
     < priority value="debug" />
     < appender-ref ref="projectName" />
   

Now on each class we want to use the Logger(which is imported from org.apache.log4j.Logger) we need to use it this way:

public class Someclass

      private final static Logger logger = Logger.getLogger(Someclass.class);
      public dispatchMsg()
      {
         logger.debug("My first log msg");
      }
}

Idan.

[ad]

Related Articles:

(1801)

Creation and Use of Singleton under Jboss5.1 with EJB3.0 Annotations.

Hi,

I had a case where I needed to use the same variable shared between couple of stateless beans.

In a stand alone java program we would set it as Static.

But since we are under Server application container(this case Jboss) we know that the container has pool of EJB’S sessions which is being created for us.

A static variable in such environment might get duplicated(specially in Cluster mode) and therefor wont serve out target.

So for this purpose we will create Singleton class which will hold our “static” variables.
that Singleton class will have only one instance throughout our application deployment.

Some code:

First we create the Singleton interface:

import javax.ejb.Local;

@Local
public interface SingletonBeanLocal
{
	 int getAttribute();
	 void setAttribute(int x);

}

Now we will create Singleton Management class:

* Note: We must implement Management class in order to achieve Singelton MBean.

import org.jboss.ejb3.annotation.Management;

@Management
public interface SingletonBeanManager
{
	 int getAttribute();
	 void setAttribute(int x);
}

Now we are going to implement these Interfaces:

import javax.ejb.Local;
import org.jboss.ejb3.annotation.Service;

@Service(objectName = "jboss:custom=Singleton")
@Local(
{ SingletonBeanLocal.class })
public class SingletonBean implements SingletonBeanManager, SingletonBeanLocal
{
	private int xyz = 0;

	@Override
	public int getAttribute()
	{
		return xyz;
	}

	@Override
	public void setAttribute(int x)
	{
		xyz++;
	}
}

The @Service and @Management combined together will install a Singleton MBean which can also be controlled via JMX console.

Since this Mbean is registered as service it will be the only one installed and it’s “local” variables” could be use as “Static” in our terms.

Now all we need is to Lookup/Inject to the Singleton Mbean and retrieve/set our variables.

Hope you got it,
Idan.
[ad]

Related Articles:

(1801)

Accessing Jboss JMX programmatically

Hi,

The next example will explain how to retrieve attributes from the JMX console via java.

The reason why you want to access the JMX console would be the need of having values which you wont be able to retrieve via the common API.

For example if we want to get the current subscribers of a specific Topic/Queue resource for any purpose
we wont be able to get it via the common JMS API.

We need to access to the JMX(locally or remotely) and read the attribute we desire.

Some code:

An example of connecting to the JMX and accessing the current number of subscribers which listening to a Topic:


public static int getCurrentTopicSubscribers()
	{

		try
		{
		//use this code when you are connecting remotely(outside the jboss container).
			//------------------------------------
//			Hashtable ht = new Hashtable();
//			ht.put(Context.INITIAL_CONTEXT_FACTORY,
//					"org.jnp.interfaces.NamingContextFactory");
//			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);
			//---------------------------------

                       //(Connection within the jboss container)
		 MBeanServer server = (MBeanServer) MBeanServerFactory.findMBeanServer(null).get(0);
			server = (MBeanServerConnection) ctx.lookup("jmx/invoker/RMIAdaptor");
			if (server != null)
			{
				monitorJMS();
			}
			else
			{
				log.error("Couldnt connect to JMX server");
			}
		}
		catch (Exception e)
		{
			log.error("Couldnt connect to JMX server");
		}

After we have connection we can easily retrieve the attributes from the JMX:

public static void monitorJMS() throws Exception
	{
		ObjectName objectName = new ObjectName(
				"jboss.messaging.destination:name=DispatcherTopic,service=Topic");
		System.out.println("DurableMessageCount = "
				+ (Integer) server.getAttribute(objectName, new String("DurableMessageCount")));
		System.out.println("AllSubscriptionsCount = "
				+ (Integer) server
						.getAttribute(objectName, new String("AllSubscriptionsCount")));
	}

Idan.
[ad]

Related Articles:

(1801)

Sending Object to Restful Web service Straight forward.

Hi,

We all know that Restful services works with HTTP protocol. restful services support xml/jamson.

Problem: I have object and I want to send it “as is” to a restful service.

Solutions: 1. not straight forward: We need to convert that object manually to XML string and send it.
2. Straight forward:
2.a Annotate the object with those annotations:
Class annotations:
@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement
Fields annotations:
@XmlElement(name=”fieldName”)

example: (This has been tested on Jboss5.1.1 AS)

@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement
public class SomeObject implements Serializable
{
	@XmlElement(name="m")
	int m = 1;
	@XmlElement(name="g")
	int g = 2;
}

Now in order to send it we need to marshell our object using StringWriter and Marshaller.
Example:

Client side:

                SomeObject  myObject= new SomeObject();
		HttpURLConnection conn = null;
		StringWriter stringWriter = new StringWriter();

		try
		{
			Marshaller m = JAXBContext.newInstance(SomeObject.class).createMarshaller();
			m.marshal(myObject, stringWriter);

			URL url = new URL("http://localhost:8080/MYPROJECT_WEB/hello
                        /testObjects");
			conn = (HttpURLConnection) url.openConnection();
			conn.setDoOutput(true);
			conn.setRequestMethod("POST");
			conn.setRequestProperty("Content-Type", "application/xml");


			OutputStream os = conn.getOutputStream();
			os.write(stringWriter.toString().getBytes());
			os.flush();

			BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));

			String output;
			System.out.println("Output from Server .... n");
			while ((output = br.readLine()) != null)
			{
				System.out.println(output);
			}

		}
		catch (Exception e)
		{

			e.printStackTrace();

		}
		finally
		{
			conn.disconnect();

		}

Server side:

@POST
   @Path("testObjects")
    @Consumes("application/xml")
    @Produces("text/plain")
	public String testObjects(GrandSun sun)
	{
		System.out.println(sun.toString());
		return "Success";
	}

Idan.

Related Articles:

(1801)

Creating Restful Services using EasyRest for Jboss

Hi,
Here is how we creating simple GET method using EasyRest(Supported perfectly by Jboss).
The method expecting one input of type String and print out it’s value.

First of all if you using Enterprise Application project make sure you add the Rest methods to the Web project.

The class which holds the method logic named: “RestFacade”

import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;

@Path("hello")
public class RestFacade
{
	@GET
	@Path("sayHello")
	public void sayHello(@QueryParam("input") String input)
	{
		System.out.println(input);
	}
}

* With QueryParam we declaring our rest method to expect input parameter(in our example it’s String).
* with GET we declaring our method to work when GET being invoked.

Now we need to add the following code to WEB.XML:

< ?xml version="1.0" encoding="UTF-8"?>

	YOUR_PROJECT_NAME
	
		index.html

	
	
		resteasy.scan
		true
	

	
		org.jboss.resteasy.plugins.server.servlet.ResteasyBootstrap


	
		Resteasy
		org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher


	
		Resteasy
		/*



* make sure you add the right project name and don’t forget to add the listener as shown below.

This is the url in order to trigger the method:

http://localhost:8080/MY_PROJECTWeb/hello/sayHello?input=TestingMyMethod

and the output is: 14:24:01,296 INFO [STDOUT] TestingMyMethod

Idan.

Related Articles:

(1801)

Circular dependency bug at Jboss5.1.1 AS

Hi,  
I have been struggeling this for a week now. This is a seriouse bug at Jboss5.1 and EJB3.

Example for Circular dependence:

In CompanyCoreBean

  @EJB(name = "CompanyCoreBean")
  private CompanyCoreBeanLocal companyCoreBean;

CompanyCoreBean is injected to itself

leading to this jboss error:

DEPLOYMENTS MISSING DEPENDENCIES:
Deployment

“jboss.j2ee:ear=WMA_EXPLODED.ear,jar=

WMA_EXPLODEDEJB.jar,name=CompanyCoreBean,service=EJB3” is missing the following dependencies:
Dependency “<UNKNOWN jboss.j2ee:ear=WMA_EXPLODED.ear,jar=

WMA_EXPLODEDEJB.jar,name=CompanyCoreBean,service=EJB3>”

(should be in state “Installed”, but is actually in state “** UNRESOLVED Demands ‘jndi:WMA_EXPLODED/CompanyCoreBean/local-com.mirs.wma.core.sessionBeans.CompanyCoreBeanLocal’ **”)

Dependency “<UNKNOWN

 

There is an open Jira about the issue. but I had to overcome this one.

So the walk around is using the Annotation @IgnoreDependency. which will Ignore it’s own dependency on deployment.

@IgnoreDependency
@EJB(name = "CompanyCoreBean")
private CompanyCoreBeanLocal companyCoreBean;

Idan.

[ad]

Related Articles:

(1801)

Start Jboss on boot with openSuse

This is the way of getting a JBoss application server to start automatically when the OS loads.

 

1. Following steps must do as ROOT.

2. When installing Jboss the script jboss_init_suse.sh is auto generated at

/home/jboss/jboss-5.0.0.GA/bin

3. The script from section need to copy into /etc/init.d and name it “jboss”

run:  cp /home/jboss/jboss-5.0.0.GA/bin/jboss_init_suse.sh /etc/init.d/jboss

4. Give permissions to the file

run: chmod 755 jboss

5. Create Log dir. inside the log dir a log file will be created. here is the path:

/home/jboss/jboss-5.0.0.GA/log

6. Must update the initiate file with the right paths(see section 9)

7. Configure the system to autmaticly the script on boot with this command:

/sbin/insserv  /etc/init.d/jboss

(or use Yast:  Yast -> System -> System Services (Runlevel) ->jboss ->Enable -> ok)

8. In order to start/stop/restart the service we need to use the command:

service jboss start/stop/restart

9.Init file:(pay attention the “Bold” parts

#!/bin/sh
#
# JBoss Control Script
#
# To use this script
# run it as root - it will switch to the specified user
# It loses all console output - use the log.
#
# Here is a little (and extremely primitive)
# startup/shutdown script for SuSE systems. It assumes
# that JBoss lives in /usr/local/jboss, it's run by user
# 'jboss' and JDK binaries are in /usr/local/jdk/bin. All
# this can be changed in the script itself.
#
# Either amend this script for your requirements
# or just ensure that the following variables are set correctly
# before calling the script.
#
### BEGIN INIT INFO
# Provides: jboss
# Default-Start: 3 5
# Default-Stop: 0 1 2 6
# Description: Start the JBoss application server.
# Required-Start:
# Required-Stop:
### END INIT INFO

#define where jboss is - this is the directory containing directories log, bin, conf etc
JBOSS_HOME=${JBOSS_HOME:-"/home/jboss/jboss-5.0.0.GA"}

#make java is on your path
JAVAPTH=${JAVAPTH:-"/usr/java/jdk1.6.0_12/bin"}

#define the classpath for the shutdown class
JBOSSCP=${JBOSSCP:-"$JBOSS_HOME/bin/shutdown.jar"}

#define the script to use to start jboss
JBOSSSH=${JBOSSSH:-"$JBOSS_HOME/bin/startup.sh"}

# Shell functions sourced from /etc/rc.status:
#      rc_check         check and set local and overall rc status
#      rc_status        check and set local and overall rc status
#      rc_status -v     ditto but be verbose in local rc status
#      rc_status -v -r  ditto and clear the local rc status
#      rc_failed        set local and overall rc status to failed
#      rc_reset         clear local rc status (overall remains)
#      rc_exit          exit appropriate to overall rc status
. /etc/rc.status

# First reset status of this service
rc_reset

# Return values acc. to LSB for all commands but status:
# 0 - success
# 1 - misc error
# 2 - invalid or excess args
# 3 - unimplemented feature (e.g. reload)
# 4 - insufficient privilege
# 5 - program not installed
# 6 - program not configured
#
# Note that starting an already running service, stopping
# or restarting a not-running service as well as the restart
# with force-reload (in case signalling is not supported) are
# considered a success.

#define the user under which jboss will run, or use RUNASIS to run as the current user
JBOSSUS=${JBOSSUS:-"jboss"}

if [ "$JBOSSUS" = "RUNASIS" ]; then
  SUBIT=""
else
  SUBIT="su - $JBOSSUS -c "
fi

#define what will be done with the console log
JBOSS_CONSOLE=${JBOSS_CONSOLE:-"$JBOSS_HOME/log/jboss.log"}

if [ -n "$JBOSS_CONSOLE" -a ! -d "$JBOSS_CONSOLE" ]; then
  # ensure the file exists
  touch $JBOSS_CONSOLE
fi

if [ -n "$JBOSS_CONSOLE" -a ! -f "$JBOSS_CONSOLE" ]; then
  echo "WARNING: location for saving console log invalid: $JBOSS_CONSOLE"
  echo "WARNING: ignoring it and using /dev/null"
  JBOSS_CONSOLE="/dev/null"
fi

chown $JBOSSUS $JBOSS_CONSOLE

CMD_START="cd $JBOSS_HOME/bin; $JBOSSSH"
CMD_STOP="java -classpath $JBOSSCP org.jboss.Shutdown --shutdown"

if [ -z "`echo $PATH | grep $JAVAPTH`" ]; then
  export PATH=$PATH:$JAVAPTH
fi

if [ ! -d "$JBOSS_HOME" ]; then
  echo JBOSS_HOME does not exist as a valid directory : $JBOSS_HOME
  exit 1
fi

case "$1" in
start)
    echo -n "Starting JBoss application server: "
    cd $JBOSS_HOME/bin
    if [ -z "$SUBIT" ]; then
        eval $CMD_START >${JBOSS_CONSOLE} 2>&1 &
    else
        $SUBIT "$CMD_START >${JBOSS_CONSOLE} 2>&1 &"
    fi

    # Remember status and be verbose
    rc_status -v
    ;;
stop)
    echo -n "Shutting down JBoss application server: "
    if [ -z "$SUBIT" ]; then
        $CMD_STOP
    else
        $SUBIT "$CMD_STOP"
    fi

    # Remember status and be verbose
    rc_status -v
    ;;
restart)
    $0 stop
    $0 start

    # Remember status and be quiet
    rc_status
    ;;
*)
    echo "usage: $0 (start|stop|restart|help)"
esac
Credits for my colleague: Eli Cohen,
Idan.

 

 

Related Articles:

(1801)