Popular Posts

Monday, October 13, 2008

Reading a property of Axis2 services.xml from service Implementation class

There have been questions raised in Axis2 user list about reading some properties defined in services.xml from service implementation class.
An easy way of doing that is as follows.

1. Suppose your services.xml is as follows and it has a parameter named, TestProperty.

<service name="ParameterService">
<messageReceivers>
<messageReceiver mep="http://www.w3.org/2004/08/wsdl/in-only"
class="org.apache.axis2.rpc.receivers.RPCInOnlyMessageReceiver"/>
<messageReceiver mep="http://www.w3.org/2004/08/wsdl/in-out"
class="org.apache.axis2.rpc.receivers.RPCMessageReceiver"/>
</messageReceivers>
<parameter name="ServiceClass">org.test.MyParameterService</parameter>
<parameter name="TestProperty">This is a test property</parameter>

</service>

2. We need to read the value of "TestProperty" parameter from service implementation class.
It can be done using MessageContext as follows.

import org.apache.axis2.context.MessageContext;

public class MyParameterService {
public void readProperty(){
MessageContext mc = MessageContext.getCurrentMessageContext();
String prop = mc.getCurrentMessageContext().getAxisService().getParameter("TestProperty").getParameterElement().getText();
System.out.println(prop);
}

}

Now you can create a service archive with this class and copy it to AXIS2_HOME/repository/services directory. Then start axis2server.bat and go to http://localhost:8080
You will notice that the service will be deployed there. Then invoke the service by sending HTTP GET request as follows
http://localhost:8070/axis2/services/ParameterService/readProperty

Look at the Axis2server console. You will see "This is a test property" message is printed there.

4 comments:

Amila Suriarachchi said...

hi Charitha,

Normally we read parameters from services.xml and axis2.xml. Properties are read from the options object. i.e.

MessageContext.getCurrentMessageContext().getOptions().getProperty("TestProperty");

Typically users set properties at the Client level (i.e. at ServiceClient )

thanks,
Amila.

Ranjan said...

Hi,
Thanks for writing "Reading a property of Axis2 services.xml from service Implementation class".
Can you tell me how to get the properties in lower levels of the service.
For example I want properties related to database in dao layer, but I dont want to declare dao layer as a service class.
I get null pointer exception on trying it this way.

Ranjan said...

I put the properties file besides the service accessible files (unlike log4j.xml which is still in util package) and it worked fine.
This was my mistake.
Thank you.

s2_zat said...

Retrieving the property value can be done

mc.getCurrentMessageContext().getAxisService().getParameter("TestProperty").getValue().toString();