Thursday, December 23, 2010

Back to India Voyage - If it's not Fire, it is Water

Prologue

Dont know where to start on this one, as we have had an event less couple of weeks, where everything settled to normalcy. My work schedule has gotton into a nice little routine, and Kids have found themselves friends in the complex and Diwali was a grand success, with kids and adults alike having a blast. Geetha's parents and Sister/BIL were also in town and that made it even more memorable as I had the opportunity to meet Sri Samavedam Shanmukha Sarma Garu because of Madhavi's acqauintance with him. Perks of moving to India, I would say.

If it aint broke - you are not working hard enough

Anything can be repaired in India, including broken iPhones. I finally got someone to fix my broken iPhone screen and gave that to Geetha (Not so romantic, I agree, but she didn't want me to spend more on her phone) during Dasara. She was really enjoying it, and even had an exchange offer from her BIL with a very good Nokia model. One thing of note is that because of the small number of iPhones, the popular e-commerce and e-mall apps are not available on iPhones in India. There are some really great apps like ngPay etc which will let you purchase anything from rail/movie/bus tickets, banking/commerce apps, but they are limited to other smart and not so smart phones. This is a clear case of Discrimination against iPhones and I want to propose to the Congress that they should create a special reservation category for us "e-commerce app Deprived iPhone Users". That's a nice little de-tour, but lets get back to the main topic, shall we?


Geetha's mother left for Kasi along with my parents and I have decided to do Nattalu (fasting everyday for the entire month of Karthika masam) and really getting into it. It had been a week or so into the month of Karthika Masam. My routine is to perform the Puja in the morning and leave for work, come back in the evening, take shower and do puja in the evening and then have my meal of the day. I do not know if it is the fasting or Geetha has gotten even better at cooking, but every meal was so sumptuous that I used to over-eat everyday, and follow that up by a solid sleep till the morning.

Wake up call - sort of

One of those days, Geetha's dad came upstairs around 3 AM in the morning, complaining that the first floor got flooded. I was not sure if I was having a nightmare or it is really happening. Then again, my doubts have been washed off as I walked downstairs along with Geetha to see that the entire ground floor (kitche, hall, bedroom, dining room) is flooded with water. Not much, but about less than an inch of water in the whole house. We saw water dropping of the ceiling in the Kitchen and my throat went dry (amidst all the water around). We soon noticed a jet of water splashing in the sink and my first thought is that there is a broken pipeline somewhere.

So I picked up the phone and was calling the building maintenance. I was talking to them, about the leak and asking them to come over as this comes close to the definition of Emergency (at least in my dictionary) and Geetha asked me to cut the call and come take a look. She discovered the source, and it is not a broken line, and I had to cut call with the maintenance saying "Never mind.." and turned my attention to Geetha.

At this point, Her father is a little confused, perturbed and worried to say the least. Dont' know if it is the way we are, or we got toughened by the events that culminated to date, neither Geetha nor I did flinch and behaved as if it were a regular event during the course of the day. It did not matter that, it was in the middle of the night or wee hours of the morning, or that there is water all over the house.

Where the rubber meets the road

The problem turned out to be a water inlet for our Water filter in the kitchen. Somehow, the inlet pipe came loose and water started gushing out (it is only a 5 mm pipe, but the pressure is high, with us being in the ground floor) into the sink. There was a plate covering the sink drain, so the water was splashing upwards giving us the impression that there was a leak in the ceiling. Now we were in much worse shape, as the problem was not someone else's but just our doing.

For starters, we shut down the inlet valve to avoid further amplification of the problem, then surveyed the scenario a little. There is water all over and we have two outlets one in to the balcony (closer to the source) and another into the bathroom attached to the bedroom (farthest from the problem source). With water being everywhere, Geetha and I decided to roll-up our sleeves and get to work. Thank the Mighty british empire for endowing us with the greatest of strategies, we decided to "Divide and Conquer". Geetha chose the balcony outlet and I chose the bathroom outlet, and armed with sponge mops we started sweeping the water away.

Nick-nacks and few other toys and sundry kept aside, Geetha and I were busy brushing/pushing the water out of the house into the outlets. Water under the beds, under the sofas, and water in the kitchen. Slowly but steadily Getha made her way out of the kitchen in to the hall and I met her my clearing my way out of the bedroom. We are breathing a sigh of relief when we saw ......

Fighting Spirit - not ours

Back to the point I mentioned earlier, regarding the iPhone, there it is, totally drenched in the water on the kitchen counter. It was so strategically placed on the kitchen counter that all the water splashing (instead of over-pouring) was landing on or near the phone and I read somewhere that electronic equipment and water do not mix well. There is truth to that piece of wisdom and now I could see the iPhone trying to do its best. One could clearly see the struggle its going through as the screen is flashing, flinching and even made attempts to make and answer phone calls. I attribute it to the brave soul that Steve jobs had designed, that despite its agonizingly pathetic physical condition, it was making feeble attempts to assure us that "all izz well". But we know in our heart of hearts that that poor soul is destined to be silenced and we would not see his bright face anymore.

We said a few little prayers for the brave soul and marched on the task in hand. Sure enough, in about an hour we were able to clear the house of the water, and we looked at each other, and heaved a sigh of relief. It was in the middle of the night, and we were sweating from the exhaustive physical work and said good night to Geetha's dad and went back to sleep as if nothing had happened.

A Matter of Faith

What befuddled us and put us in a state of sheer amazement was the fact that, there is not a drop of water in the Pooja Room which is adjacent to the Kitchen, hall and dining room. I dont claim it to be a divine intervention or a miracle, but a key aspect of our Vasthu system or Engineering which made that part of the house slightly inclined and the basi characteristic of water to follow the downward slope. If you see this an omen to renew your faith, I would be a happier person for it.


When we woke up the next morning, the only remnants of the last night's event were the wet floor mats and the dying iPhone. If not for these hard evidences, I would have chalked out this as a decent nightmare and slept if off..

Back to India Voyage - Pranavi's mis-adventure

There is an age old Chinese proverb that translates to 'May you live in interesting times'. Often this is referred to as Chinese curse. My life in India has been nothing short of making that come true in every sense of the word. I have not had time to jot down some of the incidents of the recent past, but this one begs to be told, and I would not do proper justice to the gravity of the incident if I wait any longer.

Perfect Start (or lack there of)

This incident happened on 18th December 2010 (a Saturday for those looking to find patterns or omens). I was getting ready to go to work in the morning, and the driver reported that the car would not start, not due to a dead battery, but some other hitherto unknown reason. This being India and inside a large residential complex, I asked my driver to call his driver brethren, and all of them gave me a jolly ride in and around the complex, while I tried in vain to jump start the engine. Very soon I realized that we are into unchartered waters, and asked the driver to call in the mechanic and get it towed and looked up, while I waited in the house. An hour later, they could not find out exactly what went wrong, and I called the Ford service technician as a last resort. He gave an appointment and after hearing the problem description over the phone, diagnosed the problem and gave my driver a quick remedy. Lone behold, the car starts, and it is an air leak in the fuel system and needs repaired, but as a stop-gap solution, we can pump out the air in the system and the car would work fine, and it only happens if we leave it idle overnight.

Now, both Geetha and I have decided to go ahead with our initial scheduled plan of visiting her friend's place (we should have learnt our lesson based on how the day started for us.. No, we didn't). So, we grabbed our little ones and headed for their house. Theirs is a duplex apartment, converted by internally linking 2 apartments one over the other in 3rd and 4th floors with a spiral stair case. Pranavi's favorite spot to throw a fit is that spiral stair case, her so called 'Alaka Griham'. They have a son Nikhil (9th grader) who loves to play with Dhruva and Pranavi and vice versa. That is another reason why we decided to march ahead with our plans despite the small hiccup with the car (coming to think about it, the car kinda has a hiccup and we have to clear the air pocket...). So, we are all having fun. Kids are playing with Nikhil, Geetha chatting with Narmada and I am discussing which amplifier to purchase for Murthy's new entertainment system (this guy has a separate entertainment room that you all would be proud/jealous of depending on the take). Pranavi said she was tired and wants to sleep and went into a room.

Room Alone

A little while later, I hear Pranavi crying, and since we were in the higher floor and voice being very feeble, assumed that she was downstairs and Geetha assumed that Pranavi was upstairs. Fact of the matter is that, she went into a room (upstairs) and the door closed behind her and got locked up. She could not reach for the lights and it is dark inside. However feisty little gal she is, she is still afraid of dark (partly/mostly because we use it as a weapon to feed her) and is crying scared inside.

When we realized that she was inside, they were panicked and started looking for the keys. Guess what, we tried over a dozen keys, but not able to open the door. Pranavi's cries have gone louder and she started coughing heavily, which could only lead to one thing -- she is going to vomit. Murthy and Narmada are getting anxious and trying to call in lock-smith and I even tried my Credit-card swipe technique. It did yield favorable results. Meanwhile, Pranavi went silent. This bothered all of us, and we are not sure what she is up to. Geetha kept calling her and tried to calm her down.

A true testament to our re-adaptation to the mother land, neither Geetha nor I were panicked. We were simply assessing the situation and looking at ways to solve the problem. It is heartening and comforting to see ourselves so composed in a situation like this.

"Kshana Kshanam".. (Sridevi and Venkatesh trying to sneak out of her apartment)

It is Nikhi's room that Pranavi got locked in, and he is in real panic. He told me that the window ( a large sliding French window) of his room is open and I went in to check from the other balcony. It sure is open. I have gauzed the situation and I can walk out of the balcony of the hall and cross over (about 4-5 feet) and reach the AC Unit outside the room and get past it and then slide into the room through the window. It is only fourth floor and it is dark outside, so I cant even see how high up I was. So, while there is a small contingent of people attending to Pranavi, I walked out of the balcony and reached the other room. A small detail worthy of mention is that there is no balcony in the room that Pranavi is in, as they converted even the balcony into the room to make it bigger. So, here I was hanging on to a rod 4 floors above ground trying to get past an AC unit attached to wall so I can get inside the room. Can anyone say "Kshana Kshanam"..

The hosts just realized what I was doing and they got panicked even further for both of us. Slowly and steadily I made past the AC unit, and grabbed the window and slide it open. I pulled myself up and slowly into the room. I was behind the computer desk and made my way through the opening to the front and there is Pranavi crying her lungs out and hugging Geetha dearly. Did I miss something here? I guess so...

While I was doing my own adventures, Geetha asked Pranavi to hold her hand (which she slid under the door) to appease Pranavi. In doing so, little miss Pranavi somehow managed to turn the knob and open the door. Poor kid was traumatized severely and was in a sorry state. She held on to Geetha like she wouldn't want to leave her at any cost, and in uncontrollable state. She is only 3 years old, but this is the first time I have seen her soft.

In the end, I was very pleased that she managed to open the door by herself, but it was kind of anti-climactic.. Don't you think...

So, I'm left with admiration for Murphy for his universal law... "If anything can go wrong, it will.."

Sunday, July 25, 2010

Back to India Voyage - Blackness of Smoke

This is another one of those incidents that happen to the chosen few, which would unsettle and unnerve most frail hearted.


We are slowly getting into a rhythm, and it is one of those beautiful Hyderabad evenings, when I came home. Geetha and Kids have gone out, and having not taken the key, I was walking outside and enjoying the cool breeze. I found out that, Geetha went to take Dhruva for his chess class. We have someone in the complex giving chess classes and wanted to take advantage of that (I liberally use the word We here, but Geetha is the one who found it out and took Dhruva there. Give credit where it is due I say). Dhruva is also getting enrolled into a Tai-Kwondo class and I am beginning to believe that there is a sense of belonging here in this complex.


Walking outside the walking rail (I don't know if I mentioned this, but there is a 1 KM walking trail round the perimeter of the buildings in the complex, which I should say is very nicely maintained and pleasant) for the first time, I was catching up on my phone calls. Around 7:30 I realized that Geetha has reached home, I stopped my walk and entered the house. Nothing out of the norm.


Preparing the kids for dinner, we asked Dhruva to go upstairs and get dressed in his pajamas. He goes up and in a flash comes running down saying "There is smoke and fire upstairs". I did not believe him and went along with him. That is when it struck me. The entire upstairs is pitch dark, could not see a thing with lights on, and as I walk I could see my steps in white on the floor. I came down stairs and see my legs, clothes already beginning to turn black. Pranavi starts yelling out "call the fire people".


We called the building maintenance right away and told them that it is an emergency and they have to rush. To their credit, they showed up in less than 5, and went upstairs. They were literally choking whilst trying to find the problem area. I myself went and looked at potential problem areas ( clothing iron, electric geyser etc) and could not find any. But, the professionals quickly found it out and told us that it was the electric geyser in the common bath room that got burnt beyond belief and shut down that part of the electric circuit and told us to stay away from upstairs and left.


This is when I went upstairs to assess the situation. Off late, I am coming across more situations that are truly ineffable. One has to see the room to understand the gravity of the problem. I could go on an on explaining how we felt or what we saw, but, it would surely fall short of reality, but, that does not mean that I am going to give up. I feel that a little (I mean very little) detail would help put things in perspective. So here it goes.


When we rented this apartment, we did it in a rush. We liked more features in this apartment and complex, but were some nagging issues that are still making us regret our hastiness. This apartment had 3 bathrooms and all of them fitted with electric geysers, of which we were using 2 regularly. The one in the common bathroom upstairs, was disconnected. So, we had it checked by electrician who simply connected the wires and said it is working now. When it was turned on, there was some issue with plumbing and it started leaking steam like a cooker with a blown safety valve. So, we called the plumber and he turned the water connection off. What we did not realize in this process is that we had a left a hot plate with nothing to cool it, had some one switched the geyser on.


Dhruva was asked to clean himself up that evening, and quite unusual for him, he used the common bath room and in trying to turn the light on, he turned the geyser on, but did not turn it off. The unit was on for 2 hours without any water to heat. Perfect recipe for disaster. Now lets get back to the situation at hand.


What once was a geyser is now a black cylinder (red hot) and all the plastic surrounding it is completely vaporized into soot. I am looking at a 2-3 mm layer of black soot on the ground, on the bed, and what I saw earlier as my foot prints in white are the clearing of the soot my my feet. The walls over 3 feet from ground are all black including the false ceiling. There was a 1mm of black coating in the closets (housing our clothes) that were locked shut. Few tiles in the bath room were cracked due to heat. The false ceiling in the bath room is charred and had to be replaced. The said Geyser is now a carcass waiting to be dumped.


The thing that made the situation complex was our mosquito nets on the windows which contained all the smoke and soot indoors as opposed to letting it out. We opened all windows and took out the nets thinking even the mosquitoes have some code of ethics and would not encroach an environment so inhospitable (little did we know their tenacity and hunger for human blood).


We were in panic mode, and I decided to take control of the situation as opposed to the contrary. We called for the cleaning crew and this being almost 9 PM at night, they said they could only come in the morning. Being a veteran of cleaning jobs owing to my janitorial training and work experience in school, I decided to take a first crack at it. I slowly but surely collected my wits and along with it cleaned up the soot on the ground. Being so light weight, it flew off into air when I tried to speed up the process. On this occasion my mind was wandering if the choice of marble for the floor should be white or black. If it is black we would not notice much of a difference, but on the other hand, we would not even know how big the problem was. After about half an hour of this clean up, I dared call Geetha upstairs to take a look. Now that both kids are asleep, We could not leave it in that shape and decided to give our best shot to the floor at least.


Good old bucket of soap water and a cleaning rag was the call of the day. So, we started that way. A clean bucket of water is pitch dark by the time we finished one block of marble (2ft X 2ft), and realized that we could not work in that manner if we have any plans of finishing before dawn. So, we went the professional way, dumping the water on the floor and cleaning with a huge mop and it took both of us 4 back breaking hours to at least see the spots of white marble under the black coating.


By the time we were done, we both resembled the coal workers of South Africa. We decided to call it quits as that point, as we were exhausted physically, mentally and emotionally. Even after showering for an hour the blackness did not go away.


We hired professional cleaners next morning and they were scared to start the work. Halfway through, they gave up and said they would only continue after painting the walls and ceiling. I kept thinking, how would they have reacted had they seen the house the day before.


We had the house repainted, and it took a complete scratching of the surface with emery paper, a coat of primer and in some areas up to 5 coats of paint to cover the blackness underneath. All in all after 3 days of that painting job, the cleaning crew gained courage and started to clean the floors and the bathroom which is marked "Enter at your own risk". Another 2 days of that, and now we could hardly imagine how the house was. The painting crew and the cleaning crew have done a superb job turning a disaster area almost back to its normalcy. Every now and then I see a small forgotten spot, a switch with a smoke mark, an overlooked corner of a tile etc that reminds me of the fact, but otherwise, we are back to normal (or whatever you want to call it).


What is surprising to me to this day is through all this, we did not have even the faintest of idea or the stench of something burning downstairs.


On hind sight, it is one of those things, one would think, "It could have been worse" and leave it at that.

Wednesday, July 14, 2010

Back to India Voyage - Rats and BSNL

Let me warn you, first off all, I am not referring to the employees of BSNL, lest I offend the rats. Here is another episode that can only happen to the select few and I fortunately or unfortunately fall in to that group.

Since my landing in the mother land, I have called numerous telecom providers asking for internet connectivity. In the land of IT, I got apology mails from the likes of Airtel, Tata etc saying they would not be able to provide service in my building. Then I found the brave soul BSNL, who took it to heart and promised me a service.

Encouraged by this new found enthusiasm, I have applied for a land line and broad band connection (a guarantee of 2 MBPS) online. Waited an eon and then, saw another advertisement from BSNL and sent them SMS requesting the same service. For good measure I followed it up with phone calls a week later.

Really on the wits end, last week I went to BSNL office and inquired about the status of my application. Not much surprise there, I was greeted with a friendly (wink) face who asked "What Application". I repeated my story. With a very understanding smile, she said, "Oh! you are from US. Generally, when you file an online application, you have to come to office and file a paper application." Little did I know about this highly advanced technological advancement. Having been in India for over a month now, I duly complied and filled in an application form for a land line and broad band connection and filled in the fees. Along the process I gave my proof of address, identity proof, a photograph, my current bill, a pint of blood, appendix and pancreas (who needs these organs anyway).

Now comes the twist. She gave me the application and asks me to go to another office (behind this office) and get permission from Mr. Nagaraja Rao. Like a stupid I ask "Why". She said, she can only take the application if he approves. Frankly I got confused (to my knowledge this does not happen very often), but what other option do I have. So, I went to the other office and saw the mentioned Nagaraja Rao, who looked at me and said, "File the application in the front office". I told him, that I was sent from the front office to see him. He said "you fulfilled the formality. so, now I'm telling you to go and file the application". I tried to assess the situation, but thought better of it and filed the application.

The CS rep, then took my application and after 15 minutes, told me that their systems are slow, and she would fill in the form later, but meanwhile, she gave a hand-writeen receipt that I applied for the said services and duly signed and put a rubber stamp and gave me the receipt. Methinks, "If their systems are slow to enter/process my application, how could provide me a 2MBPS service".

I am a patient man (a virtue I acquired recently and have been using and abusing it) and waited 4 days. Nothing happened, and I went to the BSNL office once again to inquire about my application (Paper application this time). They took my name, and the unequivocal paper receipt, and then told me that there is a problem with my application. I asked them what it was. It just so happens that India is booming with people looking for cell phones, and they ran out of 9 series and 8 series. When my turn came, I got a 7 series number and BSNL system does not like this (as it thinks this is a bogus number). My feelings exactly ("Are you kidding me"). Some how, I managed to convince them that they can call that number, which they did and fixed that issue. Now another problem with the application is that I chose a 2 MBPS package which is the highest they offered, and it is on the paper application form, but not yet in their system. I asked them why they could not have told me that on the day I filed the application. They answer promptly was "You did not wait till the application was filed. So, we could not have envisioned what all problems the system gives without entering the data".

I asked them to give me any plan they can enter in the system. I was asked to call back in the afternoon to get an Order #, then call Mr. Nagaraja Rao to expedite the order. Do you See the pattern here? By now a seasoned citizen, I called in the afternoon and got the order number and called Mr. Nagaraja Rao. He tells me, he is not in a position to promise anything. This is when I lost it. I blasted him and talked to few others and finally someone up or down the chain promised to expedite the order.

Real shocker, an hour later, Geetha calls to tell me that BSNL people are home installing the land line. I was surprised, shocked, and beginning to think, I should have blasted these people a month ago and I would have been in Gigabit land. Lesson learned, and mission accomplished.

It would not be a Krishna Story if it ends at this point. So, the story continues..

Geetha calls again, and says the BSNL people can not install as there is some problem. We call the building maintenance people and between them and BSNL folks, identified the problem. RATS. Yup, you read it right, Rats chewed the cable running from BSNL end point in the building to where it joins in my (or the one I rented) apartment. It is not the responsibility of BSNL. RATS.. that's all I can say. So, now I am in the hunt to find whose responsibility is it, and get the wiring installed.

BSNL people promptly left saying "Let us know when you install that cable and we'll install the land line". Now, I can not even blast them, as they can say "Talk to them rats in your building", which could mean so many different things...

Rats.. rats.. rats...

So, in conclusion, "Have you seen rats lately?"


Krishna

Tuesday, August 4, 2009

Adobe Flex & Struts 2.0 Integration

Flex presentation layer has been gaining popularity over the years, mostly because Adobe made the Flex SKD open source. The SDK focussed mostly on the presentation layer and leaves the door open for integrating with various server side technologies. With a vast majority of applications developed in J2EE platform utilizing struts, it becomes the obvious choice for providing the server side functionality.

In this article, I am going to explain how to integrate Flex presentation layer with Struts (2.0) server side. To make the process of creating new projects using this methodology, I have created a Maven archetype, that when installed, would create a sample project with the example explained in this article.

This article assumes understanding of Struts and Flex programming and not going into the details of the corresponding frameworks.

Submitting Flex Form Data to Struts Form



In this section we are going to discuss the submission of Flex form data to a struts action. The form data consists of product details, which when sent to the struts action, would be converted to java object and saved in the action.

Step 1

Create a Flex Form that contains the data fields 'productName', 'productDescription', 'productPrice', and 'productQuantity'.


<mx:Form id="addProductsForm" label="Add Product Form" width="100%" height="60%" >
<mx:FormHeading label="Add Product Form">
</mx:FormHeading>

<mx:FormItem label="Product Name:">
<mx:TextInput id="productName">
</mx:TextInput>
</mx:FormItem>
<mx:FormItem label="Product Description">
<mx:TextInput id="productDescription">
</mx:TextInput>
</mx:FormItem>
<mx:FormItem label="Product Price">
<mx:TextInput id="productPrice">
</mx:TextInput>
</mx:FormItem>
<mx:FormItem label="Quantity in Stock">
<mx:TextInput id="productQuantity">
</mx:TextInput>
</mx:FormItem>
<mx:FormItem>
<mx:Button label="Add" click="addProduct()"/>
</mx:FormItem>
</mx:Form>

Step 2

Create the service that invokes a Struts action. This service defines the methods to be invoked for the successful response and on failure.



<mx:HTTPService id="addProductService" showBusyCursor="true" useProxy="false"
url="addProduct.action" resultFormat="e4x" method="POST"
result="addProductResult(event)" fault="addProductFault(event)"/>


Step 3

Create the method that gets called when the button was clicked. This method creates a dynamic object with the attributes of the form data and submits the 'addProduct Service'.



public function addProduct():void {
var params:Object = { 'product.name': productName.text,
'product.description': productDescription.text,
'product.price':parseFloat(productPrice.text),
'product.quantity':parseInt(productQuantity.text)
};
this.addProductService.send(params);
}



Step 4

Process the response from the server. In case of error, display the error message. In this example, we have not applied any filters on the output result of the action. So, a complete XML representation of the action class would be sent back to the Flex as a response. Look for the 'status' variable and see if it is true and if so, the product was added successfully, else the details of the errors are stored in the 'actionErrros' variable of the Struts action object.



private function addProductResult(event:ResultEvent):void {
var xml:XML=XML(event.result);
var status:String = xml..status;
if (status != null && status.toString() == "true") {
mx.controls.Alert.show("Product was added Successfully!");
var messages:XMLList = xml..actionMessages.item;
actionMessages.text = messages.toString();
}
else {
var messages:XMLList = xml..actionErrors.item;
actionMessages.text = messages.toString();
mx.controls.Alert.show("Product was NOT added. See messages below");
}
}


The complete Flex application can be seen here.


Step 5

Create Struts configuration file, and define the action mapping with the result type as XSLT. This configuration would marshall the complete action class into XML stream and send it to the requester, in this case the Flex application.

<action name="addProduct" method="addProduct" class="com.company.flex.action.ProductAction">
<result type="xslt"></result>
</action>



Step 6

Define the POJO for the Product. And Create the Action class that extends the action support. The 'addProduct' method checks for the validity of input, and if validated, adds the product to the static product list and sets the status as true, else sets teh status as false.


public String addProduct() {
this.status = true;
if (this.getProduct() != null) {
Product p = this.getProduct();
if ( p.getName() == null p.getName().equals( "" ) ) {
addActionError ("Product Name can not be blank" );
this.status = false;
}
if ( p.getPrice() <= 0 ) {
addActionError( "Product Price has to be a positive number" );
this.status = false;
}

if ( p.getQuantity() <= 0) {
addActionError( "Product Quantity has to be a positive number" );
this.status = false;
}

if (status) {
getProducts().add( getProduct() );
addActionMessage( "Product " + p.getName() + "[" + p.getPrice() + ", " + p.getQuantity() + "] was added" );
System.out.println( "Product " + p.getName() + "[" + p.getPrice() + ", " + p.getQuantity() + "] was added" );
}

} else {
System.out.println ( "Product Object was not set for the action" );
addActionError( "Product Object was not set for the action" );
this.status = false;
}

return SUCCESS;

}



A complete example project can be downloaded here. This project is a maven project and you need maven version 2.2.0 to execute this project. I am using the maven flex-mojos for compiling and building the mxml and actionscript files, so you need to update your corresponding settings.xml file in your home directory.


Fetching Data from Struts Action



In this section we are going to discuss how to fetch data from a Struts action and display it in Flex application. For keeping this article simple, we are going to fetch the static data from the action class, but this could be easily extended to fetch the data from a server side file or database. This involves using the "xslt" result type of struts action (available in 2.0).

Step 1

Define a Flex form that has a button (We are not sending any data to server, however that change can easily be made) and a display grid for displaying the results.


<mx:Form id="detailsForm" label="Get Details Form" width="100%" height="100">
<mx:FormItem>
<mx:Button label="Get Product Details" click="getProductDetails()"/>
</mx:FormItem>
</mx:Form>

<mx:DataGrid id="dg" color="0x323232" width="100%" height="90%" rowCount="3" dataProvider="{products}">
<mx:columns>
<mx:DataGridColumn dataField="name" headerText="Product Name"/>
<mx:DataGridColumn dataField="description" headerText="Description"/>
<mx:DataGridColumn dataField="price" headerText="Price"/>
<mx:DataGridColumn dataField="quantity" headerText="Quantity in Stock"/>
</mx:columns>
</mx:DataGrid>



Step 2

Create the service that invokes a Struts action. This service defines the methods to be invoked for the successful response and on failure.


<mx:HTTPService id="getDetailsService" showBusyCursor="true" useProxy="false" url="getProductDetails.action" resultFormat="e4x" method="POST" result="getDetailsResult(event)" fault="getDetailsFault(event)"/>


Step 3

Create the method to submit the form and get the results from the struts action. In this case, this is a dummy action method and we are fetching the data from the action itself.


public function getProductDetails():void {
var params:Object = {};
this.getDetailsService.send(params);
}


Step 4

Define the Struts configuration for this action in struts.xml file


<action name="getProductDetails" method="dummy" class="com.company.flex.action.ProductAction">
<result type="xslt"> <param name="exposedValue">products</param></result>
</action>


Step 5

Define the action method and a property 'products' in the action class.


public ArrayList<Product> getProducts() {
if ( products == null ) {
products = new ArrayList<Product>();
Product prod1 = new Product();
prod1.setName( "Canon Rebel Xi" );
prod1.setDescription( "Digital SLR Camera from Canon." );
prod1.setPrice( 456.50f );
prod1.setQuantity( 2 );
products.add( prod1 );
Product prod2 = new Product();
prod2.setName( "IPhone 3G" );
prod2.setDescription( "3rd Generation Smart Phone from Apple" );
prod2.setPrice( 199.99f );
prod2.setQuantity( 10 );
products.add( prod2 );
}
return products;
}

public String dummy() {
return SUCCESS;
}


For complete application example, please see the resources section below.

Maven Archetype for Flex-Struts Project Creation



To make the creation of Flex Struts projects easier, I have created a Maven Archetype (using other open source components available on-line like flex-mojos etc).

Step 1

Download the maven archetype zip file from the resources below.

Step 2

Extract the contents into a folder, and run maven install command. This would install the archetype into your local repository


mvn clean install


Step 3

Now you can create a new project from the archetype specifying the local catalog. All the local archetypes are listed, and selecte the FlexStruts-archetype option. Then the installer would ask input for the parameters like 'groupId', 'artifactId', 'version' and package. Provide the requested information and a new project would be created for you.

mvn archetype:generate -DarchetypeCatalog=local


See the following screen-shot for how the output looks.



Step 4

Go to the newly created project and run Maven install command and a War file would be created in the target folder for the web module of the project. Deploy this war in an application server and you can test the Flex Struts in action.


Resources



  1. Example Project FlexStruts.zip
  2. Maven User settings.xml
  3. Maven Archetype Project.