WSO2Con 2013 CFP Banner
WSO2Con 2013

Axis2 Session Management: Part 2

Deepal Jayasinghe, Tech Lead at WSO2, presents a two-part article series on session management within Axis2.  In Part 1, Web service session management concepts were introduced.  Part 2 builds on this introduction and provides more detailed descriptions of the four specific types of sessions within Axis2.

Date: Sun, 4th Jan, 2009
Level: Intermediate
Reads: 14064
Discuss this article on Stack Overflow
Deepal Jayasingha

WSO2 Inc.

Request Session Scope

Request session scope is the default session scope in Axis2. When we deploy a service without knowing anything about session management, then our service will be deployed in request session scope; this is much like using no session management at all. The lifetime of this session is limited to method invocation lifetime, or the request processing time.

Once we deploy a service in request session scope, for each individual invocation a new service implementation class will be created. Let's say we have deployed a service called "Foo" in request scope. If a client invokes the service 10 times, there will be 10 instances of the service implementation class.

If we want to specify the scope explicitly, we can still do that by adding scope attribute to service element in services.xml as follows:

 <service name="Foo"  scope="request">  </service>  

To get a better understanding of request scope, create a service using the following service class, deploy it and invoke:

 public class MyService implements Lifecycle {      public void init(ServiceContext context) throws AxisFault {         System.out.println("I'm inside init method ");     }      public void destroy(ServiceContext context) {         System.out.println("I'm inside destroy method");     }      public String foo(String foo) {         return foo;     } } 

Note: To invoke the service, we simply type the following in the browser:

http://localhost:8080/axis2/services/MyService/foo?foo=foo

Then we will see the following in the server console:

I'm inside init method

If we continue to do so, we will see this statement printed every time we invoke the service.

It should be noted here that even if we deploy a service in a request scope, there are many ways of keeping our service as a state full service. One approach is to store the state in Axis2 global run time (ConfigurationContext) and retrieve whenever necessary.

SOAP Session Scope

The purpose of SOAP session is to have a transport-independent way of managing sessions between two SOAP nodes, the client and the server. Here Axis2 uses SOAP headers in order to manage the session. SOAP session scope has a slightly longer lifetime than request session scope; deploying a service in SOAP session is required to change services.xml as well. Managing SOAP session requires both the client and service to be aware of the sessions. This means that the client has to send the session-related data if he wants to access the same session, while the service has to validate the user using session-related data.

In order to manage SOAP session, a client has to send additional reference parameters in the SOAP header, which is named serviceGroupId (this will be sent to the client when he invokes a service that deploys in SOAP session for the first time). In the meantime, SOAP session provides a way to manage sessions across single service invocations, as well as for multiple services within a service group. As long as we are in the same SOAP session, we can manage service-related data in ServiceContext; if we want to share data across other services in the group, we can use ServiceGroupContext to store the session-related data.

When a client tries to access a service that we have deployed in SOAP session for the first time, Axis2 will generate serviceGroupId and send that to the client as a reference parameter in wsa:ReplyTo, as shown below. However, it should be mentioned that the server has to have WS-addressing support for SOAP session support to be available to both the client and the server.

 <wsa:ReplyTo>        <wsa:Address>http://www.w3.org/2005/08/addressing/anonymous</wsa:Address>             <wsa:ReferenceParameters> <axis2:ServiceGroupId xmlns:axis2="http://ws.apache.org/namespaces/axis2">urn:uuid:65E9C56F702A398A8B11513011677354</axis2:ServiceGroupId>             </wsa:ReferenceParameters>  </wsa:ReplyTo> 

If a client wants to live in the same session, then he has to copy that reference parameter and send it back to the server when he invokes the service in the second instance. As long as a client sends the valid serviceGroupId, he can use the same session and the service can maintain the session-related data. Unlike request session, SOAP session has a default timeout period; if the client does not touch the service for a period of 30 seconds, the session will expire. In this situation, a client that sends the old serviceGroupId will get an AxisFault. We can change the default timeout period by changing the server's axis2.xml as follows:

 <parameter name="ConfigContextTimeoutInterval">30000</parameter>

By changing the parameter value, we can obtain the desired timeout interval.

As mentioned earlier, deploying a service in SOAP session requires us to change services.xml as follows:

 <service name="MyService"  scope="soapsession"> </service>  

It should be noted here that, although we are required to copy the references parameter, once we use the Axis2 client we can configure it to copy the parameter automatically.

To get an idea about SOAP session management, let's write the following service class and deploy it. The service class adds the current passed value to the previous value and sends the result, so we should see the incremental values changing. First, write the service and deploy it in SOAP session, completing the necessary changes to services.xml

 public class MyService {     public int add(int value) {         MessageContext messageContext = MessageContext.getCurrentMessageContext();         ServiceContext sc = messageContext.getServiceContext();         Object previousValue = sc.getProperty("VALUE");         int previousIntValue = 0;         if (previousValue != null) {            previousIntValue = Integer.parseInt((String)previousValue);         }         int currentValue = previousIntValue + value;         sc.setProperty("VALUE","" + currentValue);         return currentValue;     } } 

Now let's use the following code to invoke the service. As you can see, we have engaged the addressing module, but we have not done anything to manage the sessions.

         ServiceClient sc = new ServiceClient();         sc.engageModule("addressing");         Options opts = new Options();         opts.setTo(new EndpointReference(                 "http://127.0.0.1:8080/axis2/services/MyService"));         opts.setAction("urn:add");         sc.setOptions(opts);         OMElement ele = sc.sendReceive(createPayLoad(10));         System.out.println(ele.getFirstElement().getText());         ele = sc.sendReceive(createPayLoad(10));         System.out.println(ele.getFirstElement().getText());  

createPayLoad method is shown below:

 public static OMElement createPayLoad(int intValue) {         OMFactory fac = OMAbstractFactory.getOMFactory();         OMNamespace omNs = fac.createOMNamespace(                 "http://ws.apache.org/axis2", "ns1");         OMElement method = fac.createOMElement("add", omNs);         OMElement value = fac.createOMElement("args", omNs);         value.setText("" + intValue);         method.addChild(value);         return method;  }  

Once we run the code, we will see the following output in the client side:

10
10

That means that although we have invoked the service twice, we have gotten the same output. Now let's change our client code a bit and see what results we get. Just add the following line of code and run the client again.

   opts.setManageSession(true);   sc.setOptions(opts); 

Now you should see the following output in the client side.

10
20

So that simply tells us that we have invoked the service in a session-aware manner.

It should be mentioned that you will need to engage the addressing module in both the client side and the server side in order to get SOAP session working.

Transport Session Scope

In the case of Transport session, Axis2 uses transport-related session management techniques to manage sessions. For example, in the case of HTTP, HTTP cookies are used to manage session. The lifetime of the session is controlled by the transport, not by Axis2; Axis2 simply stores service context and ServiceGroupContext in the transport session object so that service can access those contexts as long as session lives.

One of the key advantages of Transport session over other sessions is that we can talk to multiple service groups within one transport session. In SOAP session, we don’t have a way to communicate between two service groups, but with the transport session we have that capability. In this case, the number of service instances created depends on the number of transport sessions created.

Deploying a service in transport session requires us to change services.xml as follows:

 <service name="MyService"  scope="transportsession">  </service>  

Now, let's change our previous sample to have the scope as transport and redeploy the service. Let's also try to invoke the service in the following ways:

Option 1 : Using the browser.

http://localhost:8000/axis2/services/MyService/add?value=10

If we keep on typing that, then we will get the output as 10 , 20 , 30 etc.

Option 2 : Using the service client. To use the service client, we must first set the session management flag to true so that it will send back the transport cookie. So if we run the following code, we will see this outcome:

         ServiceClient sc = new ServiceClient();         Options opts = new Options();         opts.setTo(new EndpointReference(                 "http://127.0.0.1:8000/axis2/services/MyService"));         opts.setAction("urn:add");         opts.setManageSession(true);         sc.setOptions(opts);         OMElement ele = sc.sendReceive(createPayLoad(10));         System.out.println(ele.getFirstElement().getText());         ele = sc.sendReceive(createPayLoad(10));         System.out.println(ele.getFirstElement().getText()); 
10
20

This simply tells us that we have invoked the service deployed in the transport session in a session-aware manner. In this case we do not need to have addressing module.

Application scope

Application scope has the longest lifetime compared to others; the lifetime of the application session is equal to the lifetime of the system. If we deploy a service in application scope there will be only one instance of that service, and there will be only one service context for that service. In the Axis2 world, if we consider the memory footprint and if we do not want to manage session, then a good option is to deploy the service in application scope.

When we deploy a service in application scope, a client does not need to send any additional data to use the same session.

To deploy a service in application scope we need to change axis2.xml as shown below:

 <service name="foo"  scope="application">  </service>  

Managing Sessions Using ServiceClient

As we know by now, managing sessions in the client side involves bit of a work. In both SOAP session and Transport session, a client has to send the session-related data if he wants to live in the same session. He might be able to do this for SOAP session by copying the required reference parameters. However, with Transport session, a user cannot obtain access to transport to copy and send cookies.

To make the user experience easier, Axis2 has the built-in capability of managing sessions within the client session by just setting a flag (which we have used already). Then, depending on the service side session, it will send the corresponding data as long as we use the same service client.

If we want to live in the same session then we can create a service client as shown below, then reuse the created service client object to invoke the service.

 	  Options options = new Options(); 	  options.setManageSession(true); 	  ServiceClient sender = new ServiceClient(); 	  sender.setOptions(options); 

Once we create ServiceCient as shown above, if the service is deployed in SOAP session it will copy the serviceGroupId and send that from the second invocation onwards. If the server sends the session id, such as http cookies, it will copy that to ServiceContext (in the client side) and send it back to server when the client invokes the service for the second time.

Conclusion

Stateless nature is one of the main characteristics of Web services, but that is a limitation for advanced web services developers. Developing an enterprise level application using Web services is not easy unless we have a session management layer. Axis2 has four levels of sessions to address enterprise Web service development issues.

References

Author

[Deepal Jayasinghe, Tech lead, WSO2, deepal +AT+ wso2 +dot+ com]

lxhuaa.foxmail.com's picture

Christian Louboutin Shoes Nike Air Griffey Max GD II Black Green

ennis shoes have gone from being footwear for kids to become one of the most popular types of shoes worn today. The people who design this fancy footwear have become in demand stars in their own right. With fans from every avenue of popular culture, from Hip Hop music to extreme sports. Everyone wears sneakers from moms to gamers to busy corporate executives. The first sports footwear Nike Air Diamond Turf White Grey Basketball Sports Shoes were actually called croquet footwear because they were worn by the wealthy of the late 1800s to play the popular lawn game they got their name from. The first croquet footwear were much too expensive for the average person to afford. As technology and sports advanced so did athletic footwear. The manufacturers of today no longer make shoes for playing sports as an offshoot of their primary business. The sneakers are the primary business. Billions are made each year from sneaker sales. The more mainstream designs come from teams of college educated fashion designers, researchers and engineers who spend hundreds of man hours testing and tweaking their products. Air Griffey Max Fury 2011 All Black Retro Running Shoes Sneaker design is big business. And big money for the designer or team of designers that creates a great new product. Todays sports footwear wearers are business leaders, politicians, artists, entertainers, educators and religious leaders. Walk into any grade school, high school, college, university or trade school and you will see the majority of the students wearing sneakers. It is not uncommon to see doctors and nurses walking the halls of hospitals wearing scrubs and sneakers purely for the comfort factor. Tennis shoes were once relatively inexpensive and many still are. But having become very popular they can cost a great deal of money. The research that goes into the higher end pairs can be extensive. The athletic shoe industry employs scientists, doctors, podiatrist, athletes and many others to continually improve their products. The competition is fierce but the rewards are great. The ease of use and comfort sneakers provide the wearer make them popular with every generation. The young, old and everyone in between wear tennis shoes. The rubber soles do not slip on wet sidewalks and the soft durable uppers help ease foot pain. Each year sneaker companies introduce new styles in a myriad looks, colors, textures, weights and heights. Sales are not waning, but increasing. In some cases endorsement deals for athletes are more lucrative than actually playing their sport. A big chunk of this revenue comes from doing sneaker commercials. Satisfied consumers have made tennis shoes a worldwide staple. Another key is public tastes. Once a particular pair becomes popular among the masses, sales increase. Word of mouth, better known as street credibility is a vital part of the Women Air Max Jr 2011 Black Pink Trainning Sports Shoes athletic shoe phenomenon. Marketers understand how to manipulate the cool factor. Not all footwear are created equal and no amount of marketing can guarantee the success of an inferior product. The manufacturers of tennis shoes have elevated the success of their products through the intelligent use of science and marketing. Nike Air Diamond Turf White Black Basketball Sports Shoes
lxhuaa.foxmail.com's picture

Christian Louboutin Shoes Mens Air Jordan Fusion 22 Urban Series

Women of all ages love the look of heels, but that doesn't mean that they still don't love how flat shoes make them feel. Flat shoes are perfect for a woman when she wants to look good, but wants to keep her feet a little closer to the ground. While there are many different kinds of flats that are perfect for a woman's casual style, there are also a lot of fun patterns that a lady can wear to really amp up her look. Many of us only think of Teva as casual sandals, but you can also find a lot of other great styles as well, including some fantastic flats! The Women's Kiru Ballet T is ultra radiant in the waterproof leather and poly webbing detail. When you are looking for flats that will really keep you warm, soft and fashionable, these are just the ones for you. The faux fur lining will really keep your toes toasty and the rubber outsole will always keep you on your toes. The MICHAEL Michael Kors Townsend Flat are what every fashion forward woman needs in her closet. When you are looking for some classy shoes that will really keep your feet comfortable without losing any of your style, these strappy flats are superb! This multi-strap design with metallic decoration and block heel offers just the right amount of sophistication in a flat. The leather lining, lightly padded insole and rubber sole help keep your feet comfy with good traction. The Rocket Dog Capucine Flat is super flattering with the ruched pointed toe. These soft fabric shoes with rubber soles are easy to walk in, even if you need to wear them all day long at the office. Some women prefer the look of a smooth, round toe, while other ladies really love the look and feel of a pointy toe shoe, and these are just the ones to be worn. Are you looking for the perfect office shoe? The Liz Claiborne Hartley is a very smooth leather loafer that adds just the right amount of comfort and style. The rubber soles help keep your feet from feeling tired when worn all day at work and the detail stitching really adds a lot of professionalism to this shoe. Forget about trying to wear pumps all day long while you are running around the office and wear a pair of shoes that will keep you happy the entire time they are on your feet! The Edie Flat is just right for a woman who does not want to wear just any old plain shoe on her feet! These round toe flats have gold hardware that offer a really stylish look to a normally plain shoe. If you love the look of flats, but want to have a dressier pair to wear when you need to get all primped up, these are just right for your classy toes! Flat shoes are perfect for so many women because they are so cute and fashionable, but they really keep your feet comfortable. You do not have to always wear shoes that hurt your feet in order to look good! Instead wear a pair of hot flats to keep your style sizzling! For wildly good fashion, flats are always the way to go when you want to keep your feet happy. View more Women's Shoes from Like.com Mens Air Jordan 9 Commemorative Edition White Black Red ID:9051Author:jackrlandryTitle:Customizing Your Treadmill WorkoutArticle:Working out in a gym can either be distracting or very dull. With all of the activity going on around you, it may be hard to focus on the task at hand. Running for extended periods of time on a treadmill can be less than thrilling. There are many ways for you to get the most out of your cardiovascular workout and look forward to it every day. One great way to pump up the excitement factor in your workout is to create a great playlist of your favorite music. Be sure to choose tunes that will inspire you to increase your heart rate. There are a number of different websites and blogs devoted to helping you choose a great list of songs to run to. Try researching these, along with articles related to fitness. They may have some ideas on bands, songs, and styles of music that will make you feel more energized while listening to them. You can also consult iTunes or other music centered programs. Programs like this will be able to suggest different styles of music for you or give you the names of other bands and musicians that are related to your favorites. Spend a little extra time creating a great playlist for your iPod or mp3 player, and you will have more energy and determination while you jog on the treadmill. Another great way to inspire yourself to exercise on workout equipment is by having a great pair of shoes to carry you through your workout. The right pair of running shoes will support your feet and make your cardiovascular exercise easier. Make sure to purchase some that have arch and heel support. They should also be light and assist you in proper foot placement when running. Visit your local sporting goods store or, even better, a store that specializes in athletic shoes. If the option is available, schedule a running consultation. For this consultation, the experts at the place of business will most likely ask you to run on a treadmill for a certain amount of time and observe you while doing so. After taking notes regarding your running technique and stamina, they will be able to provide a few different brands and types of shoes for you to choose from. Try on each pair, and be sure to get a practice walk or run in them, so you can really make the best decision about which feet and feel best. Once you have made your decision, be sure to start using them a little at a time, to break them in. After a few weeks of alternating between your new and old running shoes, you should be able to run every day in them without causing foot pain or blisters. Another way to customize your workout is to utilize the different adjustable functions on the treadmill. It is possible for you to change the incline, speed, and program that you are running to. Many types of workout equipment offer different programs meant to mimic outdoor terrain and environments. You can use certain trails, decide if you would like to run at a steady speed or in intervals, and most machines even have a fat blasting option meant to rapidly increase your heart rate and burn calories. Choose the program that fits your style and your abilities best. Choose a few different types, so that you can alternate between days of the week. This way, you will not fall into a pattern and get bored, and you can trick your body into working harder than it may want to. You can also personalize your daily routine by finding things to keep you entertained. At most gyms, exercise machines are in view of televisions. Though you must be respectful of the other patrons, as well, turn the television to your favorite channel or program. You will be able to get your exercise and catch some of your favorite shows at the same time! However, do not let yourself get distracted by this kind of stimuli. Make sure that you keep your heart rate up, and you should always keep focused on your workout. The more you customize your run to your liking, the more likely you are to make it a habit and do it once a day, every day. Try making exercise fun, and you will look forward to breaking a sweat! About the author of this article: jack r. landry has been writing about the exercise and health industry for years. he recommends using spinning bikes to stay healthy and fit. contact info: jack r. landry jackrlandry@gmail.com http://www.workoutwarehouse.comCategory: Mens Air Jordan Retro 10 Black Red Date:September 04, 2010 08:03:01 AM  Mens Air Jordan Fusion 12 XII Retro Basketball Shoes Black White Yellow
freak000.web.de's picture

Soapsession

hi, i treid the soapsession example, it dont works, i got this message: Unable to engage module : addressing if i do: ConfigurationContext configurationContext = ConfigurationContextFactory .createConfigurationContextFromFileSystem( "/webapps/axis2/repository", "/webapps/axis2/WEB-INF/conf/axis2.xml"); LifeCycleStub stub = new LifeCycleStub(configurationContext, "http://localhost:7777/axis2/services/LifeCycle"); stub._getServiceClient().engageModule(Constants.MODULE_ADDRESSING); stub._getServiceClient().getOptions().setManageSession(true); // the paths are correct, i modify it for posting. i got: org.apache.axis2.transport.tcp.TCPTransportSender but the second way is not useful. anyone can help? would be cool ;)
latex.mattress.yahoo.com's picture

Programming language is make

Programming language is make me confused. Maybe later I will learn about programming, but not now. free ads |part time jobs|latex mattress
mannylim's picture

Lifecycle for request scoped service

When and where does the destroy(ServiceContext) method get called for a service in request scope?
hkcsseo.hkcs.gmail.com's picture

When we deploy a service

When we deploy a service without knowing anything about session management, then our service will be deployed .like using no session management life time is limited for each individual invocation a new service implementation class will be created. If a client invokes the service 10 times, there will be 10 instances of the service implementation class. came to know how could we overcome this Jobs Weiden