Friday, 22 April 2016

Tech Talk... Reverse UML generator in eclipse - ObjectAid

A reverse UML generator can be used to generate UML diagram from source code. Here, I am going to talk about a reverse UML generator that comes as a eclipse add on and that can be used to generate UML diagram from java code. ObjectAid is one such addon available for eclipse.
Here we see step by step how to add ObjectAid to eclipse and then use it to generate a UML diagram:

Step1: Install ObjectAid in eclipse:
  • Open Eclipse and go to Help > Install New Software
  • Click on add to add a new repository
  • Enter name ObjectAid UML Explorer
  • Enter Location http://www.objectaid.net/update

Step2: Select the objectaid class diagram plugin as it is free, and click 'next' . Sequence diagram one needs a license, so, you can skip it for now.



Step3: Click 'finish'. The installation should start now. Click 'ok' on the security warning that appears.

Step4: Once the installation finishes, eclipse would ask for a restart. Click ok and let eclipse restart.

Now, we are done with the ObjectAid installation and we are ready to create a class diagram.
Step5 : Create a folder anywhere to store the class diagrams.

Step6: To create a new ObjectAid UML diagram, launch the ObjectAid wizard by going to File->new->other.


Type Class Diagram  in the top textbox to filter this wizard out. Once you see the right wizard, select it and click 'next'.


Step7: A visual UML editor would appear in your eclipse. You can start dragging and dropping your classes or java files on to this editor. It will automatically start putting in the class diagrams, the relations between classes, methods etc.



Step8 : Once you are done, you can choose to save it as an image. for this, all you have to do is right click on the diagram and choose save as image followed by the specific image type you want to save it as (.jpeg or .gif etc.)



Friday, 4 March 2016

The dussehra ordeal

This time around dussehra we had hired a driver for my office journey. A few days before dussehra he asked whether we did vehicle pooja on the dussehra day. We said traditionally we north Indians do vehicle pooja on vishwakarma pooja day. The conversation ended here and we forgot about it. On the day of dussehra when we were relaxing at home, we got this call from the driver wherein he enquired if we were at home. Then he  announced that he was coming with sweets and other pooja materials and wanted to do a pooja of our vehicle. We were surprised as we had not perceived earlier that in this short span of time he had developed so much intimacy with our vehicle. So we obliged to his order of coming over and doing the pooja. He came over and did the pooja whole heartedly and gave us the prasad as well. We were half pleased and half suspicious at his gesture (the world is like that dear friends, nobody does anything selflessly, not even a pooja. If anyone puts up a selfless show it is bound to raise suspicions. )
The next day on our way to office the driver told me "you know madam yesterday this sir called me whom I used to work for earlier and he told that I and I only must come over to his place and do pooja for his vehicle. Since I was the best driver he eved had.i went over and did the pooja and just for that he gave me  bakshish (a token of reward given out of happiness) of half my monthly salary." I could very well see now where this conversation was headed.along with that the purpose of his great pooja at our place was also getting clear. Anyways to see his reaction and bring out his purpose more clearly I just replied "wow your sir must be filthy rich". He said "no madam it is a custom that everyone gives bakshish to drivers on dussehra". I was not interested in persuing this bargain of forced bakshish with him, so I simply told him to talk to my husband in the evening on the subject.  After reaching office I talked to my husband and informed him of the whole situation and the driver's expectations. In the evening my husband told him that we were not in a position to simply give away a huge amount in bakshish.also he had been providing his service to us for hardly fifteen days so the bonds were also not that strong yet and moreover he had already taken some advance money from us the second day of his service only and now he was forcing us to give him bakshish , that also not what we would give as per our comfort and will but as per his.  My husband told him the max amount that we were in position to give him and in reply he said "sir I can't come from tomorrow .pleass arrange for another driver." Wow. Isn't a bakshish supposed to be awarded out of happiness and isn't it upto us to decide on our capacity that how much bakshish we can give to someone. Well, not in this case. No wonder our culture is changing fast and instead of depending on people for various services we, in urban india atleast, are preferring to depend more and more on machines.
So this was our dussehra ordeal that left us wondering whether our decision of hiring a driver was out of our capacity or its that people are becoming more and more intolerant and greedy day by day.

Arpora flea market in Goa, India

This time around I happened to be in Goa around a weekend, with an equally enthusiastic (read shopaholic) friend. So, we decided to hit the infamous Arpora flea market.
This market was very near to calangute beach, on the calangute-anjuna road. It has a very good expanse and numerous stalls selling all different kind of products that would attract tourist attention, particularly foreign tourists wherein they would be looking for souvenirs or famous products from India to take back home. But apart from the buzzing shops, there was more to the market - something for even the non-shopaholics . There were artists and musicians, playing live and numerous people applauding. The environment was so charged up...my toddler couldn't help swing to the beats as we stopped by :) Then came the food stalls - again a number of them well organized in one section of the flea market offering everything from goan delicacies , to south indian delights to Italian pizzas and other subcontinental mouth watering food.
The market starts from 6:30 in the evening and goes on well into the night. The stalls are up and running till 3 or 4 am in the morning. But you must have a good bargaining skill to get a good deal here. However, what would be the definition of a "good deal" when there's no end to bargaining. Well, in my opinion, once you form a price of the product in your mind looking at its worth and you are able to get it into that price range - you can happily call it a great deal. So we did. Just to give you an idea, we liked a bag. The price quoted by the shopkeeper was INR 550 , we quoted INR 250 and finally the deal was done at INR 300 :)
Overall, I would say the market is a must visit at least once when you are in Goa. The whole street market shopping, including the bargaining, the food, the performances...everything there was an enticing experience.

Here's a glimpse of the colorful pictures you can see when you search for arpora flea market, to give you an idea of the vibrancy and liveliness of the atmosphere there :


Items that were on sale in the Arpora flea market:
  • Small wooden furnitures
  • Different kind of souvenirs - key chains, show pieces (wooden/shell/marble/metal), wall hangings
  • Jewelry (shell, stones, oxidized silver, wood, metal)
  • Woolen/Silk/Cotton stoles
  • T-shirts, beachwear and other garments suitable to Goan climate
  • Goan spices and dry fruits
  • Bags, purses, backpacks (leather, cotton, jute, synthetic leather)
  • Paintings
  • Flipflops and other foot wear
  • And many other things...please add if I am missing anything major

Useful links to get more information about the flea market:

Beleza Goa

Last week we went for a trip to Goa, but this time the aim was to just relax, eat and sleep(I know some of you would think...what a waste!! But believe me, to get a few nights at a stretch to sleep 8hrs per night and to get food without really cooking it is worth all the luxury for parents to little ones). 
After much research, we finalized on "Beleza...by the beach". I thought to dedicate a crisp blog to this property, which can help others in making their decision for staying here.

This property is located in south Goa, and has a direct access to the beach from within the property itself. The beach was kind of serene, clean and calm, in a complete contrast to calangute or baga which are overcrowded and thriving with activities, shops, eateries etc. Don't head to this beach with lots of activities and food on top of your priority list unless you want to be heavily disappointed. You would love it if your motive was to take a leisurely walk or a peaceful sunbath, have a relaxing time with your friends or family. 

In short, this resort+beach is well suited for families/groups that want leisurely and peaceful vacation and don't really care too much about the thriving night life and too much of water activities. Since the resort has 3 bedroom villas, it's particularly awesome for a group of 3 families or similar group of friends. What I meant is that if you could book one villa all to yourself, you would have an awesome time with great privacy. Over all there are only some 10 plus villas which means never having an overcrowding in the resort, even if its fully booked. In case you want to venture out and hit other parts of Goa, the resort does provide for vehicles at fixed rate, which, you might find a little overpriced, but of course,  there's always a trade off between price paid and the comfort received :)
To be precise, a half day trip to Panjim and rest of Goa would cost anywhere between 2000-3000 INR (Depending on the distance to be covered or the time involved)

Here's a brief list of pros and cons of the resort, as perceived by my family during our stay there:
Pros:
  1. Courteous staff. And I literally mean it. You would be greeted where ever you were spotted. Staff would be willing to go out of their way to help you out. A gardener left his work and strode along with us to show us the path to the beach. A waiter approached us and had a hearty chat while we were standing near the restaurant. Was it a necessity? No, it was courtesy. And the list goes on.
  2. Vast stretch of green lawn, decent swimming pool, on premises spa facilities, private access to beach, plus a children's play area that was big relief for me as my little one is used to it back home.
  3. Very good location and facilities to enjoy a leisurely vacation. We had leisurely walks across the beach, we could enjoy the sunset scenes on the beach sitting into the shack at nazare.
  4. The property is a collection of 3 bedroom villas, having 1 bedroom at ground floor along with kitchen and dining and 2 bedrooms on the first floor with a vast sitting area. The terrace had benches to sunbath and enjoy a glance on the stretches of the resort. The rooms were air conditioned, had a mini freeze tucked-in, a very easy to operate locker and a water heater kettle as well. Laundry service was available on the premises. In short, all basic amenities that you could ask for a comfortable stay were present.
  5. Free wifi but the strength was not that great in the rooms.

Cons:
  1. The biggest con was the food options available on the premises. Since the property is a little far from major markets, restaurants and other ready food options, until you are willing to venture out for long, you have to satisfy yourself with a limited menu. There are two restaurants - tentacao in the middle of the resort and nazare - the beach shack. Ambiance wise, both win. But food wise, both fail to satisfy. The breakfast option is decent, but for lunch, snacks and dinner there are very less varieties to choose from. Plus, we felt the food was overpriced for the amount of satisfaction it gave to the taste bud. Goan bun was way too chewy and we had a sundae which didn't have brownie!!! (essentially , it was two scoops of vanilla icecream with a  little chocolate sauce). 
  2. Little thoughtfulness was missing here and there : like no bucket in bathrooms!! (I had a hard time giving my little one a bath), no mosquito sprays (due to greenery there was a abundance of mosquitos but the provided repellants were not sufficient and they didn't have a spray available on the premises which we could use - again my baby came back home with quiet some gruesome mosquito byte marks), no refill/replacement of toiletries even when they got exhausted, no plane drinking water in site on the breakfast buffet spread etc. These are very little things that if not overlooked, can make the daily stay of a customer much more convenient and pleasurable. 
Coming to the cost, the rooms were rated somewhere around 5000-6000 INR per night. But we contacted the resort directly and got a better package deal from them that included breakfast, airport pickup and drop along with stay.

Finally comes the question, if given a chance I would again consider staying here. Perhaps no, until the food options get elaborated out. But, at the same time, I loved rest of the facilities and we had a nice peaceful family time along the coast , definitely enjoyed our stay.

[PS:pictures soon to follow, do come back to have a look]


Wednesday, 2 March 2016

The EPF taxation

The EPF taxation decision in budget 2016 has definitely made me think, and I am sure many others like me are thinking and wondering. Right now I am trying to figure out if there is anything that we use, apart from the air that we are breathing in, that is not taxed. After the current tax proposal, I would rather not be surprised if breathing in fresh air also gets taxed next. We salaried people should be rather prepared for anything if living in India. I am envisioning the future, where government would rather start giving a basic minimum living allowance to the salaried people and take away rest all as taxes. The salary will be cut from the taxes, rather than the taxes being cut from the salary.

I have heard the "ant and grasshopper" story, however I still thought it can't be that bad.
But now, I am sure, anything can happen...the possibilities of the impossible are unlimited. I am thinking hard whether to brace this reality or step in the shoes of the ant and move on..and away.

“But there are people who'll try to hurt you through the good they see in you--knowing that it's the good, needing it and punishing you for it. Don't let it break you when you discover that.” 




Friday, 19 February 2016

To you my child...and to all the parents out there

I never thought I was ready for motherhood before I got you. Now I know I would have never felt ready while I was as ready as ever all the time. Since the time I started nurturing you inside me to the moment you arrived ...to date...a lot has been constantly and rapidly changing into life and its all for the good, it all feels good like never before.
For the first time in life, I am having the full responsibility of nurturing and shaping a human being..a responsibility bigger than anything else, a pressure greater than any other pressure..but in the process of helping you grow, I am seeing myself grow. I was never so passionate and patient at the same time, I was never so loving as this. I had never experienced this saying "when you love someone truly you see them everywhere". I literally see you in every child I look at, I feel my heart filled with a new level of compassion and care. Had you not come into my life, I would have never felt this unconditional love inside me.

Tech Talk...Apache 403 forbidden error

I have worked with apache a lot during my career and I am never able to remember all the configurations required there for various apache behavior tuning at different levels but one thing that has surely helped me in solving the 403 errors time and again, particularly with the home page loading after the first time apache is configured on the fresh environment is this:

<Directory />
    Order allow,deny
    Allow from all
    Require all granted
</Directory>


Make sure the right permissions are provided at the root directory level and you should be good to go.
(With the assumption that you can safely allow all the incoming requests to pass through). Hereafter you can do VirtualHost specific configurations for allowing or denying certain requests as per your project requirement.

Monday, 15 February 2016

A fresh start with venturing into the unknown

it's always so refreshing to make a new start on a fresh slate. It's not so easy to do it every time, in all the situations, but when it happens, it makes you feel a new surge of energy inside you. There's no peer pressure, no fear of failure and no sky rocketing expectations when things are being started on a clean slate. Every baby step that one takes brings a feeling of achievement, no matter how small or big. There's a new boost of confidence and a new force inside you to scale the new heights. Yet people often fear starting on a clean slate because it comes at the price of leaving behind the known, getting out of one's comfort zone and venturing in the unknown. Those who are able to muster the courage to step into that unknown , they get rewarded with the benefits of starting fresh and the pleasure of exploring the unknowns, learning and creating while life goes on :-)

Life has come a long way since those days way back in the past that I can think of. Things might or might not have been more comfortable had I not made that decision to step out of the comfort of my home to study in an unknown college ,in an unknown city, between unknown people, or, when I made a job switch just when I got comfortably set into the previous job or numerous other such situations in my personal life. But one thing that I know for sure is that life must not have been as enriching had I not done all that I mentioned above. In fact it would have got so monotonous that it might have been difficult to keep going. Every change was uncomforting to start with, but unknowingly refreshing at the same time, and helped me grow in some way. And the journey continues.....

Sunday, 13 September 2015

A nighmare:Stupid Intertwined complicated threads that my subconscious weaves!!

It started with me trying to catch my bus post my office, like I do everyday. There were many buses lined one after the other...the AC volvos, the red ones that I board. I was looking for the right number but not finding one.Then I climb into one of them and go till the end where I expect a passage leading to the next one, just like train coaches.But why am I expecting it to be a train. Don't know, and while I prude over it, it starts off and to my distress, it turns out to be really a train. 

By the time I reach the next station, I know I am in the wrong one and I must get down. Or, should I continue? No no, that would be too much of risk. God knows where its bound to. So, as soon as it comes to a halt, I get down and to my dismay I find myself in a very remote kind of train station. To make matter worse, its on the edge of a cliff and I am supposed to walk on that edge to cross the station and reach over to the town. Nevertheless there is no other option so I try it out. (I am very bad with my balance even if its a 2 ft high road divider bar that I have to walk on to...and this one is ridiculously high for me. Its an impossible feet). At times I consider to slip down the slope of the edge and reach the bottom and then walk. But of course its too high to even give me the slightest hope to survival.

I don't remember how exactly I managed to cross it but then there I am , somehow on the other side. And to my relief there is an exhibition going on here.Wait a minute, it looks like the exhibition that the ladies in my apartment were planning to put up for Ganesha Festival. How could they possibly decide to hold it here in this remote village town instead of the premises of the apartment? Never mind, now that I am strangled here with nothing else to do, let me go visit there.I may find a company back home at least.

So, here I am, inside the exhibition. And here comes my neighbor. But wait a minute, isn't she coming along with my old friend who never calls me now and never visits me when I invite,who has been basically putting me off for ages. Now I see how she is extending her influence over my new found neighbor-friend-soulmate. I will not let it happen. I approach my neighbor and tell her in a complaining & hurt voice (which, I don't have to effort out after the way my evening has turned so far) why she didn't inform me the exhibition was planned here and she was to come here, we could have planned it together. But she makes a face and bitterly replies back "Neha! stop being an emotional fool yaar! Everyone knew it was here and everyone was supposed to come here. So I came with another friend. what's the big deal!" 

Obviously, it is already becoming too much to take. First the bus got misinterpreted as a train, then I landed in the unknown world, then the scary cliffy train station and now the feeling of being cheated by the true friends!! I must find myself a secluded corner and rest by myself for a while, all alone. O look....this place is actually on a sea beach, waves are crashing to the sand...how couldn't I spot it earlier. To hell with all the cheater friends. I decide to take a plunge in the sea (of course on the shore) and wash off all my worries. So, I get to the beach, knee down in water. But I should have realized by now that the time is not in my favor. A big wave comes and plunges me completely in water.Now I am not sure if I will be able to fight it off. I don't even feel like calling for help.Is it any use calling for help to the friends who never call you, never answer your call, never meet and call you an emotional fool!

Oh..I am on the beach again..wet but safe..somehow I came out of the web of the nasty waves. Good for me. Now I am too tired to do anything else. I want to return back home. There seems to be taxis lined up and people who had come for the exhibition are hopping into them and returning home. Maybe I should also hop into one, but wouldn't there be just sufficient place for those who came here, i am the extra one. I didn't come here using a taxi. will they let me in...let me try. And here I go get into one, along with 5-6 other ladies, and no one seems to notice. there are 3-4 left behind now, I hear them say they will just wait for another taxi or something. I happily waive off to them although I know deep within its not the best thing to do, wait here when its getting so dark. Anyways, its their decision. In the best of my interests, I have to keep mum as I have just found a safe and cozy corner in a crowded taxi to get back to home.

Now we are driving off...wide cemented winding roads..that never seem to end. But all of a sudden, we see those 4 ladies panting and running for their lives..asking our taxi to slow down so that they can hop in. What's wrong!!! From their grumbled words all I can make is that they are being followed by some goons. I open the taxi door for them to get in but they are not being able to. And the more the taxi slows down, the more the chances of the goons catching up. What a tense situation I landed into again! Now, I can't even close the door, its swung open and hanging in the air and I am not being able to do anything about it, I am clinging to the seat...managing to hold on to the taxi....

Don't know how much time passed. But looks like somehow the taxi door shut and we are out of the reach of the goons. time to relax. On one winding of the road, I decide to get off. I will phone someone from home to pick me up. I get down and so does another lady. I don't seem to recognize her but seems she knows me since ages. Without any prior warning, she blurts out "your best friend got blessed with a baby, but of course you must be knowing". But of course!! The friend who didn't confine to me the last time she was having a good news and I have still not forgiven her for that..and the same one who promised me if there is a next time she will let me know as soon as she herself comes to know about it...ditcher...I should have expected it. What has happened to the world !!!!

I can't take it anymore. So, I pop open my eyes to the bright sunshine coming in from my window and feel relieved to realize that it was after all only a dream...a nightmare and a really exhausting one (It must have gone on for half an hr or one hr and I already feel completely drained both physically and emotionally) . But its over now, and most of it was not true and unreal and is never going to be. My day will be nice and beautiful and so will be my life.
However on the back of my mind a tiny voice says ... there's a stronger reasoning behind every thread in the dream that your mind weaves..better pay attention to it!!

Friday, 21 August 2015

What is happening !!

I was born and brought up in a small town, with friends and relatives in every lane. Parties always happened at home, we didn't have culture to go to restaurants for food. Life was too simple. Infrastructure and medical facilities were very minimal. Family income was also limited. There was only one park in the town. When water logged on streets during rainy season, we used to make paper boats and sail them in the water. Once, the high school boys and some of our neighbors even took a boat into the paddy fields in our water logged farms and they enjoyed sailing there, as if in a massive river. When strikes happened, we were happy about the unexpected school vacation. Once, there was no electricity for almost a month in our colony because the transformer had burnt down, can't even imagine how we survived, but can't recall any uncomfort as well - that we might have experienced in that period. We ate fresh fruits and vegetables straight from the market, power cut was a frequent routine and in sweaty summer days, we used to head to our roofs where we would camp out at night in the cool breeze, and compete in counting the stars with a dozen cousins - and have a nice peaceful sleep gazing at them. 

Life has come a long way. I live in a big city now and earn much more than what my entire family managed to ,put together. We have power backup, continuous water supply, and all other material comforts that count in life. But at times, I feel more stressed and unhappy than ever before. I don't get to see the starts - because I don't have time to , the sky is full of dust and there is no roof to lie down on. The lanes are not water logged, but they are traffic clogged. There is no fresh air, fresh fruits and fresh vegetables right from the backyard garden. Many relatives are there - but there is no time to meet. Parties happen at restaurants and its more of a showoff of money than real pleasure. People who counted in life got scattered - some left behind, some moved ahead, some are near and some far - but the dynamics have changed so much.

Sometimes I get to seriously wonder if this is the life we had all carved for. If we had remained in that small town for the better, if we had changed it for the better, if we could have harmonized the natural surrounding of our birth place with better modern facilities that we all carve for - it would have been what we all imagine as 'heaven'. Will I get that heaven in this lifetime? Sounds ironical - don't we have to die to be in heaven? But is this life in any form better than being dead...... and we live on!!! :)

Sunday, 2 August 2015

Served with a baee ultimatum

I don't even need to mention how important a role kaam wali baee or a maid servant plays in the life of an Indian woman. Its easy to manage without the husband for few days but without a baee...even a single day is impossible! Life comes to a standstill without her. Nevertheless, even madame baee very well understands her importance in our lives and when people with little minds and big arrogance feel they are important for some reason, the arrogance reaches cloud 9. The same has happened off late with my baee.

I still remember the 'one fine day' when we moved into this apartment. While i was still settling down & unpacking things, bang on the door she was! GOD knows how she sniffed the new comers in the new flat and came looking for the job. But I was more than happy to have got a maid without getting to hunt for one. Another 5 minutes with her and I realized that if this lady was going to work for me, I had to put up with few things like her constant meaningless chatter , her arrogance and I had to bear in mind that she was going to be the boss. Still,overwhelmed with the feeling of getting a baee so easily, i put her on my payroll and happily closed the chapter with a 'feeling blessed' status for rest of the day.

Comes the next day and she says, "itne paise me itta nahi hoga didi. bagal ke ghar me to double offer kar rahe hain(i can't do all that you want in this much money, the flat next door is offering me double the amount)". All my dreams seemed to be shattered in a moment. But through all the harshness of my capricornian life, one thing that I have resolved for is not to give up easily. I told her she could leave because I was offering her the best I could, and right upfront I announced to her that even in case I was not going to get another maid, i will do all the work myself, as i knew very well that the next thing she would do was to scare me off with the threatening to not allow any other maid to enter my premises (although I only know how scared i was inside!!!). To my relief, she decided to continue.That was followed by a series of crockery shattering, broom breaking etc. which I don't want to cover here (I just realized i actually have enough material for a novel!)

Now an year has passed, and things have been moving smoothly, of course on the cost of few adjustments, like, she comes on her own time and leaves on her own time - we dare not ask any questions about that. She rarely comes on sundays, if she really feels to shower us with her blessings, she will show up on some sundays. we are not supposed to mention it as its her unofficial holiday. she demands a new broom and floor cleaner every month, and a new soap bar every third day - no questions to be asked. If a guest arrives - she asks us a million questions like how many, for how long, etc. etc. and we comply. She can be on leave of absence anytime and anyday without prior notice and the number of days are not fixed. We dare not cut her pay or ask her harshly about it. Then there are days when the boss doesn't seem to be in such a good mood when she arrives at work - ofcourse her domestic life is also full of the general domestic problems that each one of us faces and that grows at times out of proportion - so she can't be blamed for the bad mood, and then who else will she get to unleash her frustration on than us the poor beings, and our utensils. God, you should see the beating she gives to the utensils the day her mood is bad!! At times, in my imagination, she is like that wicked witch with a broom who can curse us to hell anytime she decides to board her broom and fly out of the window while we watch helplessly.

But then yesterday my mom voilated one of the treaties. I can't completely blame her, afterall she is also human and most of the days she is the one dealing with the boss and facing the heat.

So it all started with the maid showing up early that day, when mom asked her why her timings were so irregular. Ofcourse madame baee was offended. She said (with this hidden warning) that there were timing conflicts happening and she had to quit from one or the other house work by the end of the month. Now it was mom's turn to get offended and the war of words started. I was happily working in office , unaware of the great turmoil at home. As soon as I came back and stepped in, mom unleashed her dissatisfaction about the maid. Now, it was my turn to take sides, control the situation, and discuss with mom on what to do.This is not the first time such a situation had arrived, but the irony of the situation struck me fully yesterday. 

After a 1 hour discussion with mom finally the conclusion was to continue with her as the pain of getting a new maid and ensuring she was as good as the current one, seemed to overshadow the pain of dealing with the current one!!! What if the other maid that comes takes even more leaves, she is not honest and steals things, she asks for advance money now and then. At least the current one doesn't do all this! Obviously, We are the human race who is always afraid of changes and to explore the unknown, and on top of that we are middle class service oriented private servants ourselves, so, we are used to these nagging from bosses. So, finally we also shed our frustration by talking and discussing things for couple of hours and then got back to our normal lives! The day crisis strikes and boss quits, I will muster some courage, take control of my sinking domestic life ship and hire another commander for it..till then I should perhaps just chill!!!!

Tech Talk... Java fork/join pool

What is Java fork/join pool?
There are situations when there are multiple processors that an application can leverage on to increase its computational efficiency. How the application can do this, is generally, by breaking a big chunk of work that it might be serially doing, into subtasks which can then be divided among the different processors available, which can do the processing in parallel. The java fork/join pool provides a framework to achieve exactly the same. It wraps the complexity of thread creation, pool management and getting the work done in parallel, leaving to the user the only responsibility of his core computation logic and splitting the work when desired.
How to use Java fork/pool?
Simple, need to extend a ForkJoinTask (or its subclass RecursiveAction) and then assign it to a ForkJoinPool which will get it executed. The pool executes the task and on completion, returns back the control to the invoker thread.
The Fork/Join concept it recursion based, so, the ForkJoinTask invokes its instances recursively until the work is broken into the desired level of chunks and then is executed. The invocation through invokeAll method insures that all the tasks will be completed in parallel and then the control will be returned back to the caller, so, it would appear to the caller as if the tasks were done in a blocking fashion.
Sample program
Below is a sample program that shows the use of fork/join. The execution that the program needs to do is simple - print elements of an array list, along with the name of thread that is printing it. But, the elements need not be printed in order, whenever the size of the array list is greater than a threshold, subparts of this array list are recursively handed over to further instances of the ForkJoinTask which get it executed in parallel. The parallel execution can be observed by running the task multiple times and seeing that the sub-array-lists are executed in alternate orders at time and the order keeps changing every time the program is executed.
So, below are the steps for writing a program to use the fork/join framework:
Step1: Subclass the ForkJoinTask class and have your implementation inside it:
public class ForkJoinExample extends RecursiveAction {
       //An array list that would hold the numbers to be printed
private ArrayList<Integer> events;
       //if the number of elements in the array list is > this threshold, divide the task
private int computationThreshold;
       //name of the class, when printed, can help identify how the parallel execution is happening
private String name;
       //counter for appending to the name of the class
private static int count=0;

public ForkJoinExample(ArrayList<Integer> events, int computationThreshold,
String name) {
this.events = events;
this.computationThreshold = computationThreshold;
this.name = name;
}

//this method is supposed to be invoked for direct computation once the work has been broken down to the desired extent
private void computeDirect(){
for(int i=0;i<events.size();i++){
System.out.println("Printing from :" + name + ":  " +events.get(i));
}
}

//this is the method that would be invoked by the ForkJoinPool
//Inside this method, the work can be further subdivided recursively
@Override
protected void compute() {
//if the threshold value is not reached, direct computing can be done
if(events.size() <= computationThreshold){
computeDirect();
return;
}else{
//break the task among threads and let each one do the computation of its own
int split = events.size()/2;
ArrayList<Integer>firstHalf = new ArrayList<Integer>();
ArrayList<Integer>secondHalf = new ArrayList<Integer>();
for(int i : events){
if(i>split){
secondHalf.add(i);
}else{
firstHalf.add(i);
}
}
invokeAll(new ForkJoinExample(firstHalf, computationThreshold, this.name+(++count)),
new ForkJoinExample(secondHalf, computationThreshold, this.name+(++count)));
}
}
}
Step 2: Create a ForkJoinPool and let it invoke the ForkJoinTask:
ForkJoinExample forkJoinExample = new ForkJoinExample(
new ArrayList<Integer>(Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8)), 4, "Thread");
ForkJoinPool pool = new ForkJoinPool();
pool.invoke(forkJoinExample);

Sample outputs on running this program:

Output Sample 1:
Printing from :Thread1:  1
Printing from :Thread1:  2
Printing from :Thread1:  3
Printing from :Thread1:  4
Printing from :Thread2:  5
Printing from :Thread2:  6
Printing from :Thread2:  7
Printing from :Thread2:  8

Output Sample 2:
Printing from :Thread1:  1
Printing from :Thread2:  5

Printing from :Thread1:  2
Printing from :Thread2:  6
Printing from :Thread1:  3
Printing from :Thread2:  7
Printing from :Thread1:  4
Printing from :Thread2:  8

Tuesday, 23 June 2015

The first strand of gray hair

For ages, I took pride in not having a single grey hair. It was a trophy of my winning against all the junk food, the roller coaster metro lifestyle , pollution,  stress and everything else branded as "not good for health". Add to it the fact that all my friends, juniors, my dear husband...everyone around me has heads full with gray and white hair. Not having a gray hair really made me feel so special as well as strong and confident (Afterall, inspite of all the odds I was able to keep away the white strand). I remember confidently replying to hubby's "Oh! see the comb has a gray strand of hair" as " definitely not mine!".

And then one fine morning, I wake up with my first gray hair. I am getting ready for office as usual..combing my hair in front of the mirror and all of a sudden...that gray strand of hair glares at me...right in front of my head. I concentrate...I blink my eyes several times..I move closer to the mirror, basically I look out for any sign that would defy the horrifying observation I just made..but to my disappointment and horror...its true !!!

Anyways, I had to gather my strength and carry on with rest of my chores for rest of the day. With thousands of trains of thought unleashed concurrently and running uncontrolled in my mind, I somehow went through the steps of getting ready, finishing my breakfast and packing my bag for office. But of course, the distress couldn't remain hidden from loved ones for long. They empathized, and tried comforting me. Mom said "lets talk over it once you are back from office!"


On my way to office, through the long and juggling drive, with my mobile internet, speed as bumpy as the roads I travel on, I tried to look for causes of premature white hair, prevention and cures. Unfortunately, it didn't give me much respite, only worsened my fear. It seemed, to prevent grey hair, or to keep hair healthy, I needed to do yoga and exercise which would mean waking up at 5 in the morning and cutting my sleeping hours by half an hr or so, where I am already getting 7 hrs of sleep. But to have a healthy body and healthy hair I need to have a good sound sleep of 8 hrs! I need to eat more fruits and vegetables but then the loads of pesticides in those fruits and vegetables might play with the Ph and acidity levels in my body and lead to more hair fall. The solution is to go organic. organic edibles can cost anywhere between two to three times of the normal ones and to being the whole family of 5 members on organic products would mean double or triple the grocery bill...well I will have to take up a new job or promotion or work harder for that extra cash. that would bring in more stress and less sleeping hours again!!!! My mind started forming pictures of me with bigger patches of white and gray hair, slowly outgrowing all my black hair and dominating my head!!


After juggling through all this for the day, slowly my subconscious realized that the best and most convenient way out is to accept the gray strand of hair as a part and parcel of life and adjust with it instead of stressing myself out to the level of turning all the rest of my hair gray within a month! 
Well, I am trying to harbor a positive attitude, I have decided to move on with the believe that one day the karnataka state pollution control board will wake up and check the pollution levels of the city, the world will go organic and the organic products will be more accessible at reasonable prices, my baby will grow and I will get long sound sleep again, I will say no to junk food and get a nice cook who will cook nice healthy food for me without making a mess about it. Life will be beautiful again. I am waiting for that fine day...till then, I will do a patch-up job applying heena to my hair!

Thursday, 30 April 2015

Tech talk... hashcode and equals method overriding in java

I always used to messup the concept that which one must be overridden if the other one is overridden.

Should we override equals() if we are overriding hashcode():
we can, but even if we don't it will not have side effects

Should we override hashcode() if we intend to override equals():
yes we should, otherwise it might lead to side effects.

How?
hashcode() method generates a unique integer for each object. No matter what the fields value of the object, this integer is always the same for the object. And equals() uses hashcode by default to compare if two objects are equal or not.

Suppose now I override equals() to say two person objects are equal for me if their "name" are same.
But I don't override the hashcode(). I have all person objects stored in a HashMap against their address.

I say the following:

Person john = new person("john");
mymap.put(john, addrOfJohn);


Now, i want to retrieve the address of john. Since my equals() method is overridden,I assume if i create a object again with name "john" and use it to retrieve the address of john, that should work.

So i say:

mymap.get(new Person("john");

what do i get? null !!
why?
because storage of keys in hashmap is based on their hashcode and the above two Person objects that i created, had the same name but different hash value as i had not overridden the hashcode method.
so, while the address is stored against a key that hashes to a different bucket, after creating a new person, I might be looking at it in a different bucket. this leads to an undesirable effect.

That is why when equals() is overridden, hascode() should as well be overridden.

Tech Talk... How hash map works in java

This is a very common question asked by interviewers for java.
Rather than explaining it here, I would like to compile some links that helped me immensely in understanding the internal working of hash map:

This one provides a very elaborate theoratical insite into how things work internally with hash map
http://javahungry.blogspot.com/2013/08/hashing-how-hash-map-works-in-java-or.html


This one explains the same, but rather centering the explanation around a practical example:
http://www.javacodegeeks.com/2014/03/how-hashmap-works-in-java.html

I liked both the approaches and benifitted from both these links...hoping the same will help the readers coming to this website as well.

Wednesday, 26 November 2014

Https client and server

Post the cryptograhy session (generation of asymmetric keys), I had to use my keys to communicate between a simple https client and its corresponding server. Here's how they look like:

A simple https server:

public class MyHttpsServer {
int httpsPort = 443;
String httpsPath = "/certificate";
final EventLoopGroup parentGroup = new NioEventLoopGroup();
final EventLoopGroup childGroup = new NioEventLoopGroup();
protected final LinkedBlockingQueue<ByteBuf> incomingMsgQueue = new LinkedBlockingQueue<>();
private Channel channel;

public static void main(String[] args) throws InterruptedException {
MyHttpsServer mhs = new MyHttpsServer();
mhs.createASimpleHttpsServer();
}

public void createASimpleHttpsServer(){
try {
// setup the socket address
InetSocketAddress address = new InetSocketAddress(
InetAddress.getLocalHost(), 443);

// initialise the HTTPS server
HttpServer httpsServer = HttpsServer.create(address, 0);
SSLContext sslContext = SSLContext.getInstance("SSL");

// initialise the keystore
char[] password = "dummypassword".toCharArray();
KeyStore ks = KeyStore.getInstance("JKS");
FileInputStream fis = new FileInputStream("keysdir/my_keystore.jks");
ks.load(fis, password);

// setup the key manager factory
KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
kmf.init(ks, password);

// setup the trust manager factory
TrustManagerFactory tmf = TrustManagerFactory
.getInstance("SunX509");
tmf.init(ks);

// setup the HTTPS context and parameters
sslContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
((HttpsServer) httpsServer).setHttpsConfigurator(new HttpsConfigurator(sslContext) {
public void configure(HttpsParameters params) {
try {
// initialise the SSL context
SSLContext c = SSLContext.getDefault();
SSLEngine engine = c.createSSLEngine();
params.setNeedClientAuth(false);
params.setCipherSuites(engine.getEnabledCipherSuites());
params.setProtocols(engine.getEnabledProtocols());
} catch (Exception ex) {
ex.printStackTrace();
}
}
});


httpsServer.start();
MyHttpsHandler myHttpsHandler = new MyHttpsHandler();
httpsServer.createContext(httpsPath, myHttpsHandler);
httpsServer.createContext("/key", myHttpsHandler);


System.out.println("https server is listening on " + httpsServer.getAddress());
} catch (Exception ex) {
ex.printStackTrace();
}
      }
}


Https handler (helper class):

public class MyHttpsHandler implements HttpHandler {
@Override
public void handle(HttpExchange exchange) throws IOException {
try {
if (exchange.getRequestMethod().equals("GET")) {
System.out.println("Processing the incoming GET request...." + exchange.getRequestURI().getPath());
byte[] response;
try {
response = getResponse();
exchange.sendResponseHeaders(200, response.length);
exchange.getResponseBody().write(response);
exchange.getResponseBody().close();

} catch (KeyStoreException | NoSuchAlgorithmException
| CertificateException e) {
e.printStackTrace();
} catch (UnrecoverableEntryException e) {
e.printStackTrace();
}
System.out.println("Sent response sucessfully");
} else {
System.out.println("Requested http method not supported");
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}

private byte[] getResponse() throws FileNotFoundException, IOException,
KeyStoreException, NoSuchAlgorithmException, CertificateException, UnrecoverableEntryException {
File privateKeyFile = new File("keysdir/my_keystore.jks");
FileInputStream fIn = new FileInputStream(privateKeyFile);
KeyStore keyStore = KeyStore.getInstance("JKS");
keyStore.load(fIn, "dummypassword".toCharArray());
System.out.println("Successfully loaded the keystore");

Enumeration<String> aliases;
aliases = keyStore.aliases();
String alias = aliases.nextElement();
KeyStore.PrivateKeyEntry keyEnt = (KeyStore.PrivateKeyEntry) keyStore
.getEntry(
alias,
new KeyStore.PasswordProtection("dummypassword"
.toCharArray()));
PrivateKey privateKey = keyEnt.getPrivateKey();
byte[] response = privateKey.getEncoded();
return new Base64().encode(response);
}
}

Tuesday, 1 July 2014

Tech talk...Cryptography or Encryption [Using keys]

Previous post covered how to generate keys and keystores.
This post shows how to load the private key from keystore, public key from truststore and then use them for data decryption/encryption respectively:

Load keystore: (keystorePass = password of the keystore)

KeyStore keyStore= KeyStore.getInstance("JKS");
FileInputStream fin1 = new FileInputStream("D:\\MySecurityKeys\MyKeyStore.jks");
keyStore.load(fin1, keystorePass.toCharArray());

Load the truststore: (truststorePass = password of the truststore)

KeyStore trustStore= KeyStore.getInstance("JKS");
FileInputStream fin2= new FileInputStream("D:\\MySecurityKeys\MyTrustStore.jks");
trustStore.load(fin2, truststorePass.toCharArray());

Load private key from the keystore:

Enumeration<String> aliases = keyStore.aliases();
String alias = aliases.nextElement();
KeyStore.PrivateKeyEntry keyEnt = (KeyStore.PrivateKeyEntry) keyStore.getEntry(alias,
                    new KeyStore.PasswordProtection(keystorePass.toCharArray()));
PrivateKey privateKey = keyEnt.getPrivateKey();

Load public key from the truststore:

aliases = trustStore.aliases();
alias = aliases.nextElement();
KeyStore.TrustedCertificateEntry keyEnt = (KeyStore.TrustedCertificateEntry) trustStore.getEntry(alias, null);
PublicKey publicKey = keyEnt.getTrustedCertificate().getPublicKey();

Initializing ciphers:

//the public and private keys use encryption and decryption ciphers respectively for encrypting //and decrypting the data. So, first, the ciphers need to be initiatized:
//Initializing the encryption cipher:
Cipher encryptionCipher = Cipher.getInstance("RSA");
                        encryptionCipher.init(Cipher.ENCRYPT_MODE, publicKey);/Initializing the decryption cipher:
Cipher  decryptionCipher = Cipher.getInstance("RSA");
                        decryptionCipher.init(Cipher.ENCRYPT_MODE, privateKey);

Encryption of data:


    public byte[] encryptData(byte[] input)                throws IllegalBlockSizeException,BadPaddingException   {
        byte[] encryptedData = null;
        encryptedData = encryptionCipher.doFinal(input);
        return new Base64().encode(encryptedData);
    }

Decryption of data:


    public byte[] decryptData(byte[] inputData) throws IllegalBlockSizeException , BadPaddingException {
        byte[] decryptedData = null;
        byte[] inputBytes = new Base64().decode(inputData);
        decryptedData = decryptionCipher.doFinal(inputBytes);
        return decryptedData;
    }

Note:The Base64 encoding decoding is done to preserve the context of data when data is converted from byte to string and string to byte and encryption/decryption is done over the data. For example, if a String "Hello" were to be encrypted using the above method, the caller would say String encryptedData = new String( encryptData("Hello".getBytes()) and when decrypting back the data, he would say String decrytedData = new String(decryptData(encryptedData.getBytes()). Here, encryptedData and decryptedData are two new Strings, the final value expected on decrypting the data is "Hello". This might not be the case if proper encoding is not used. So, to preserve the value of actual data through this process, a base 64 encoding has been used here along with the encryption.

Tech talk...Cryptography or Encryption [Generating keys]

The following code snippets in java show how to generate a private and public key pair for asymmetric cryptography and how to add them to the keystore and truststore respectively:

An enum to help differentiate public and private keys:

public enum KEY_TYPE {
PUBLIC, PRIVATE
}


 Code snippet to generate the public and private keys:


  KeyPairGenerator keyPairGenerator = KeyPairGenerator
.getInstance("RSA");
  KeyPair keyPair = keyPairGenerator.generateKeyPair();
  KeyManager keyGenerator = new KeyManager();

  // generate a public-private key pair
  PublicKey publicKey = (PublicKey) keyGenerator.generateAndStoreKey(
"MyPublicKey", KEY_TYPE.PUBLIC, keyPair);
  PrivateKey privateKey = (PrivateKey) keyGenerator.generateAndStoreKey(
"MyPrivateKey", KEY_TYPE.PRIVATE, keyPair);


Storing the keys into files:

function generateAndStoreKey:
This function would store the keys into files:

private Key generateAndStoreKey(String keyName, KEY_TYPE keyType,
KeyPair keyPair) throws IOException {
Key key = null;
switch (keyType) {
case PUBLIC:
key = keyPair.getPublic();
break;
case PRIVATE:
key = keyPair.getPrivate();
break;
}
byte[] keyBytes = key.getEncoded();
File keyFile = new File("D:\\MySecurityKeys\" + keyName);
FileOutputStream fos = new FileOutputStream(keyFile);
fos.write(keyBytes);
fos.flush();
fos.close();

return key;
}


Adding private key to keystore:

A private key, once generated, can be added to the keystore. For this, first the keystore needs to be loaded into memory. Below is the code snippet for loading a keystore file, given its location:


FileInputStream fIn = new FileInputStream("D:\\MySecurityKeys\MyKeyStore.jks");
KeyStore keystore = KeyStore.getInstance("JKS");
keystore.load(fIn, KEYSTORE_PASSWORD.toCharArray());

Once the keystore is loaded, the private key can be added into it as follows:


//Convert the private key to byte array, if the key is stored in the form of file, then 
//read the file and convert it to byte array (as is the case from our private key generation code //above). If it is available in any other format, like a string, then also, the string should be //converted to byte array.
File privateKeyFile = new File("D:\\MySecurityKeys\MyPrivtekey");
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(
privateKeyFile));
byte[] privKeyBytes = new byte[(int) privateKeyFile.length()];
bis.read(privKeyBytes);
bis.close();

KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PrivateKey privateKey = keyFactory
.generatePrivate(new PKCS8EncodedKeySpec(privKeyBytes));

                //generate a certificate chain out of the private key  
File certFile = new File("D:\\MySecurityKeys\MyCertificateFile");
FileInputStream fin = new FileInputStream(certFile);
CertificateFactory factory = CertificateFactory.getInstance(CERTIFICATE_TYPE);
Certificate generateCertificate = factory.generateCertificate(fin);
Certificate[] chain = new Certificate[1];
chain[0] = generateCertificate;
                
                //add the entry to the keystore
keyStore.setKeyEntry("MyPrivateKey", privateKey,
PRIVATE_KEY_PASSWORD.toCharArray(), chain);
                //store the new keystore to the file system
keyStore.store(new FileOutputStream(new File("D:\\MySecurityKeys\MyKeyStore.jks")), KEYSTORE_PASSWORD.toCharArray());
System.out.println("Added private key to keystore");
}

Adding public key to truststore:

A public key can be added to the truststore as follows:
A public key needs to be embedded inside a certificate to be stored in truststore. Following code snippet shows how to do it:

Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());

X509Certificate[] serverChain = new X509Certificate[1];
X509V3CertificateGenerator serverCertGen = new X509V3CertificateGenerator();
X500Principal serverSubjectName = new X500Principal("CN=neha verma");
                String RANDOM = "123456789";
serverCertGen.setSerialNumber(new BigInteger(RANDOM));

serverCertGen.setIssuerDN(serverSubjectName);
serverCertGen.setNotBefore(new Date());
serverCertGen.setNotAfter(new Date());
serverCertGen.setSubjectDN(serverSubjectName);
serverCertGen.setPublicKey(publicKey);
                String CERTIFICATE_SIGNATURE_ALGO = "MD5WithRSA";
serverCertGen.setSignatureAlgorithm(CERTIFICATE_SIGNATURE_ALGO);
serverCertGen.addExtension(X509Extensions.SubjectKeyIdentifier, false,
new SubjectKeyIdentifierStructure(publicKey));
serverChain[0] = serverCertGen
.generateX509Certificate(privateKey, "BC"); // note: private key
// of CA
byte[] encodedCert = serverChain[0].getEncoded();
File certFile = new File("D:\\MySecurityKeys\MyCertificate.cert");
FileOutputStream out = new FileOutputStream(certFile);
out.write(encodedCert);
out.flush();
out.close();
}

The certificate file can be added to the truststore from command line as follows:
C:\ProgramFiles\Java\jdk1.7.0_40\bin>keytool -import -file D:\\MySecurityKeys\MyCertificate.cert -alias MyCertificate
  -keystore MyTrustStore

To see how to load and use the public key and private key generated above, you can refer to next post.

Tech talk...Cryptography or Encryption [Generating & Using Keystore/Truststore]

Keystore is used to hold the private keys.
In java, keystore can be generated from the command prompt.
This is the oracle documentation for doing the same:
http://docs.oracle.com/cd/E19509-01/820-3503/ggfen/index.html

You need to go to the jre bin folder . Inside that the executable 'keytool' should be present. this is used to generate the keystore.
Here's the command to generate the keystore

keytool -keystore <keystore name> -genkey -alias <keystore-alias>

example:

keytool -keystore MyKeyStore -genkey -alias MyKeyStore

Once you enter the above command, you would be prompted for certain inputs, keep providing the inputs and finally the keystore file would be generated with a .jks extension in the bin folder.
From here, you can copy the keystore file anywhere.

An example of what all would be entered once the above command is entered:


Enter keystore password: javacaps
What is your first and last name?
[Unknown]: neha neha
What is the name of your organizational unit?
[Unknown]: Development
what is the name of your organization?
[Unknown]: self
What is the name of your City or Locality?
[Unknown]: Bangalore
What is the name of your State or Province?
[Unknown]: Karnataka
What is the two-letter country code for this unit?
[Unknown]: India
Is<CN=development.self.com, OU=Development, O=self, L=Bangalore, ST=Karnataka, 
C=India> correct?
[no]: yes

Enter key password for <MyKeyStore>
    (RETURN if same as keystore password):

Once the keystore is generated, either keys can be added to it using command prompt or using java program.To add keys using command prompt, you can further refer to the oracle documentation here: http://docs.oracle.com/cd/E19509-01/820-3503/ggfen/index.html I used java program to generate and add private keys to the keystore. Refer to the next post for seeing example of how to generate Asymmetric key pairs and add them to the keystore/truststore using java.


The key store that holds the public key is generally called a truststore. A truststore can be generated in the same way as demonstrated above. For example:

keytool -keystore MyTrustStore -genkey -alias MyTrustStore