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

Monday, 30 June 2014

Tech Talk.....Cryptography or Encryption [Introduction]

Recently, I was working on securing the communication between different components of my product using cryptography or encryption (as it was called in the old world), I explored and learnt various concepts related to cryptography which proved to be very helpful. However, they were scattered around a lot and I had to filter out lots of stuff from here and there. I would like to summarize the learning that I gathered, over a series of small posts here, that would help someone like me in the future save time and effort and keep the learning crisp and fast.

Cryptography is a way to secure communication between two parties from any third party. In the world of computers, there are two different kind of cryptography techniques that are mostly popular : Public key cryptography (also known as Asymmetric cryptography) and Symmetric cryptography.

Public key cryptography:
This cryptography or encryption technique uses a pair of keys for encryption - decryption, one being a private key and another being a public key.Private key is used for decryption of data and public key is used for encryption of data. This mode of encryption is famous in the client - server world where the server generates a pair of keys - a public key and a private key. The private key is retained with the server , while the public key is made available to any client that wants to communicate to the server. The client encrypts its data with the public key before sending it over to the server, when the server gets the data from client, it uses the private key to decrypt the data. If any third party gets hold of the encrypted data, it can't decrypt the data because it won't have the private key with it.

In the next post, I will show how to generate a public-private key pair, how to store it and how to use it.(In java)


Friday, 27 June 2014

Innocence

There are certain incidents of purity, innocence and selflessness that leave their imprints on our heart forever. Here I am narrating one such incidence that had touched me deep down and made its imprint on my heart forever.
I had these little cousins - an elder sister and a younger btrother - just an years difference between the two.  I had a piece of sweet with me which I had to offer them but unfortunately when I broke it the two pieces came out to be unequal. The two of them came rushing to me for sweet and I couldn't think of any fairer way to distribute the pieces than to spread my palm in front of them and let them make the decision of who wanted which piece. The sister reached out in a swift movement to grab the larger piece. The brother was just watching, the expression on his face clearly showing his disappointment of loosing the chance of grabbing the larger piece. When the sister was about to take the larger piece, she halted for a moment, saw her brother's face and then to my surprise she silently went ahead and grabbed the smaller piece, her eyes fixed on the disappointed face of her brother! I was so touched by the purity and selflessness of her gesture.

Thursday, 27 March 2014

Wonder woman

There was this girl in college, with backlog papers in final year, obviously her career aspects didn't look very bright. On top of that she was in a relationship which both their parents disapproved. Anyways, we all graduated, joined our jobs, got busy in our lives and life moved on. Until one day when i was surprised to see her in the basement of our apartment and even more surprised to learn that she had been living here for quiet sometime. She invited me over to her place and in a few days time I arranged to visit her. Little did I know how many more surprises were there for me in store as i would come to learn more about the happenings in her life. As a starter I was impressed to learn that she had married the love of her life, and that too with the blessings of both their families in spite of all the obstacles, oppositions and tension they hadn't given up and finally got together. Then I learnt that she was working in a reputed iT firm, and I could sense the effort she would have put to reach here in her career given the weak academics. And unlike many other girls around me who had good academic records and degrees but were still not interested in pursuing a career, this woman seemed pretty serious and sincere about her job. Double imprsssed!! Next I couldn't stop gazing around her house, sorry, home. It was so nicely decorated and managed, so cute, warm, charming and inviting with the love and spirit of its owners reflecting in it. I couldn't stop wondering how many so called successful women around me would have scored more than her in this aspect - hardly any.
Needless to say, my opinion about her personality, her strength and weaknesses,  completely changed. I was impressed by the way she had pulled things up and managed to balance together all aspects of life. 
Today she is the mother of a small baby, still smartly striking the balance between her home, job and the infant with the help of her husband and just one domestic helper. I wish her success in whatever she does in life.
When I feel the work life pressure, when I feel lazy in keeping my commitments towards my home, then I think of her and it energises me.
Hats off toyou girl.

Sunday, 23 March 2014

Grandmaa.....

Imagine you do a schooling only till class 2 . Then you get married at a mere age of 16 and have a child the very next year. You then become a mother every couple of years for the next 12-14 years, some of your children survive, some are still-born and a couple of others are consumed by epidemics. Your husband has hardly sufficient money to meet the monthly expenses, yet you have to manage the upbringing of  all your children to the best you can, and then you get them married one by one and have grandchildren, and you take care of each one of them, at times even better than their moms can! As if your life has just one purpose - to serve your children and grandchildren. But, things don't end here. There are these clashes and fictions of joint family that happen, the children you raised with your sweat and blood separate from one another, the grandchildren grow up and go their own ways, you grow older and older, enduring all this, taking into your lap whatever life has to offer, without complaining, without leaving the zeal to live and to make the life of people around you better through your care and love….how does it feel imagining yourself in this kind of a situation? Melodramatic? Out of the world? It does feel like that to me. If I had such a life, either I would have abandoned it or  I would have gone insane.

Sadly, its not something over-dramatic or imagined or exaggerated. It’s the life bestowed upon a Grandma, it’s the life she lead for the past 80+ years. But I am not writing it out here so that you have pity for her, I am writing It out to justify why she is one of the greatest inspirations in my life, why she deserves a salutation from all the women out there, I am writing this to bring to fore the beauty of her great personality and that of numerous other Grannies like her.

A life which me and you can't even think of, which we would loath, which would drive us mad and crazy, to lead such a life, and not just lead, to maintain your integrity throughout your life - is something more than commendable. That's what this grandma did. Never once I remember her loosing her integrity through all the ups and downs of life, never did I see her compromise on her values, however hard it was for her.

If she had a single penny with her, she would make sure to spend it equally among her children, if she had a single piece of bread, she would divide it equally for them. She had no grudge against any of them, even if they ignored her needs at times. She would feed the whole family and eat at last. Every time any one of her children needed her support or for the matter of fact, anyone's support, she would be there standing besides them, even without they asking for it explicitly. I remember when her daughter-in-law was ill and they had to take her to another city for treatment, none of the brothers or sisters had come forth to go with them, but grandma was there for her son and daughter in law. When a grandchild was alone at home, she would be there to take care of him or her. When they went to study far from home, the day they would come home, where ever she would be,even when old and unable to walk so much, still she would come over to meet them. When all her sons were settled except the youngest, she lived with him, taking care of him- saying to other children - "my youngest son needs me the most, you all are settled, until  he is settled, my prime duty is to take care of him". She used to do all the household work and then attend all the society events as well.

When a cat had abandoned its kitten , a newborn just a few days old, in the backyard and the children were trying to feed it in vein, she came with a box filled with cotton, placed the kitten into it and then fed it through a cotton ball, squeezing milk into its mouth. The kitten survived and 3 days later its mother took it with her.

I had seen silent tears rolling down her cheek the day her joint family had broken, but she had not uttered a word. The very next day she was her usual self , going through her daily chores, she had accepted the big blow in her life with such calm. 

If I continue writing about such incidences where her composed personality, her love her compassion for her family touched me deep down..its going to be the longest blog ever written. So, I don't want to squeeze in all the details here...let some reside in the core of my heart … :) 

When I face little problems in life, when the loved ones around me fail to meet my expectations on petty matters, I feel frustrated, sometimes furious. Then at times I think about this Grandma, and it gives me so much strength. I don’t need to look forward to any special Saint or holy person to get the inspiration on spiritual aspects of life, on selflessness and true love, when I have her to look up to. If she can do it, she can be so loving, caring, composed and giving all through the hardships that life endured upon her, each one of us can be … and the world would be so much more beautiful if each one of us could learn something from a personality like her.

Monday, 17 March 2014

Tech Talk... Creating a temporary file using java

Template:

File tempFile = File.createTempFile(<temp-file-name>, <temp-file-extension>);

Using the above template would create a file with name <temp-file-name> and extension <temp-file-extension>.

Code sample:

File tempFile = File.createTempFile("mytempfile", ".txt");

Where such code gets useful:

Mostly, I find it very useful when writing unit test cases in java which require to test scenarios where a file creation is required, because, this way, I don't have have to worry about which OS I am on, what location should I choose to create a temporary file etc. In the setup method in my unit test, I can create the file and in the teardown method i can call delete() on this file to ensure that the file gets created before I run my testcase and gets deleted after the testcase is complete. 

Monday, 10 March 2014

Inspirations - cheers to all the women around me…

I truly feel blessed to have so many women around me - friends, relatives, elders and youngsters, colleagues - whom I look up to and seek inspiration from. Then there are distant acquaintances and sometimes even some strangers whom I got to meet in hotels, in lift, on the roads, in the shops, on bus-stops, in the buses  and everywhere else -  for very brief span of time, yet in that small span of time they left their imprints on my mind in one way or the other - so that I remember them till today. I want to dedicate some of my posts to all those women in and around...who inspire me in everyday life in various ways.  I would like to say to those women - you are all so filled with qualities, you all have something or the other that every other person can learn from you… kudos to you for being you :). God bless you all….

I would love to dedicate some of the posts that follow to some of the shining, inspiring, guiding examples from women around me. A recollection of these always gives me strength to keep moving in tough times and fills me with positive energy in daily life....

Coming back soon with the inspirational stories....

Friday, 28 February 2014

Tech talk...creating a symlink

Almost everyone knows that a symlink is a symbolic link (in simplistic words, a shortcut link) to a file or a directory and most of you would be knowing how to create a symlink on one of those linux systems. So, the question arises, why am I writing a post here on how to create a symlink, well, for some people as basic (i wont like to call naive) as me, who went through so many sites to achieve the same..somehow it was a simple line and a simple command on all those sites but yet there were contradictions due to which after 4-5 trials I was able to get the first link created properly. So, I was compelled to put it out to the world, to make a simple symlink creation even simpler. Here you go...

Create a symlink:

Command format:


ln -s [folder-or-file-for-which-symlink-is-to-be-created] [symlink-name]

Command example:


ln -s rootFolder/childFolder/folderWhoseSymlinkIsRequired symlinkToFolder
In the above case, the symlink will be created in the current directory, where the rootFolder lies.

Wednesday, 22 January 2014

Tech Talk...Byte array and String conversions in Java

How to convert a byte array to a String in Java:
To convert a byte array to a string, create a new String using the byte array as an input argument to the String constructor. Something like this:

byte[] bytes = initializeByteArray();
String str = new String(bytes);


To convert a string to a byte array, you can use the String API getBytes() :

String str = "Hello"
byte[] bytes = str.getBytes();

Monday, 30 December 2013

Tech Talk...JavaScript execution from within JVM

This tutorial describes how to execute JavaScript from within java using the Rhino provided JavaScript execution Engine.

About Rhino:

What is Rhino JavaScript Engine
Maven Repository for Rhino Jar

How to invoke a JavaScript from within java using Rhino:


public class JavaScriptInvoker {
    String myfn = ""
            + "function sayHello(inputStr, outputStr){"
            + " outputStr =  \"Hello\"+inputStr;"
            + "}";
    Function function;
    Context ctx;
    ScriptableObject scriptable;

   public void initJs(){
        ctx = Context.enter();
        ctx.setOptimizationLevel(9);
        scriptable = ctx.initStandardObjects();
        function = ctx.compileFunction(scriptable, myfn, "sayHello", 0, null);
   }

   public void invokeJs(){
      String outputStr;
      Object[] args = {"Neha", outputStr};
      function.call(ctx, scriptable, function, args);
      System.out.println(outputStr);
   }

    public static void main(String[] args) throws Exception{
       JavaScriptInvoker jsInvoker = new JavaScriptInvoker();
       jsInvoker.initJs();
       jsInvoker.invokeJs();
    }
}


Understanding different parts of the program:

1. Initializing the JavaScript engine.
The Rhino JavaScript engine needs to be initialized before it can be used to invoke a java script. This initialization involves initializing the internal objects used by the JavaScript Engine (being done using the line  scriptable = ctx.initStandardObjects(); ) .This single line would be sufficient for you in most of the cases( unless you need to do some sophisticated initializations on your own.).
Also, an optimization level can be set on the context of the engine, which ensures how performant the invocation of JavaScript from within java will be (see the line:ctx.setOptimizationLevel(9);) Optimization levels are integers, 9 being the highest.
Finally, the javascript which has to be invoked, needs to be initialized. This is being done in the line:
 function = ctx.compileFunction(_scriptable, myfn, "sayHello", 0, null);

2. Invoking the JavaScript from within java at runtime.
Once the javascript engine is initialized, it can be invoked at runtime multiple times to invoke the function compiled above, that is happening in the code :
 function.call(ctx, scriptable, function, args);
The first two arguments to the call method are context object and scriptable object of the JavaScriptEngine to let it know of the initialization parameters.
The next parameter is the compiled function that needs to be called.
The final parameter is an Object array consisting of parameters being passed to the function being invoked.

3. Parameter passing / Object sharing between JavaScript and Java.
As seen in the code above, I am passing two parameters to the method sayHello : one input string and one output string. Both these are Java String Object types. They are successfully binded and passed to the function sayHello, which appends "Hello" to the input string and then assigns the result to output string and returns the output string back. On obtaining the output string, the java runtime can successfully use it for further operation.

4. Java method invocation from within javascript engine
From within the javascript function, any of the Java methods can be invoked, even objects can be passed from the java code to the javascript as initialization parameters or arguments and then they can be used by the javascript in any way possible.

Thursday, 5 December 2013

What am I writing after all


So, What am I writing after all....

So...many of the readers might be wondering what am I writing here...some technical topics, some management stuff, some general stuff - difficult to categorize. Well, most might as well be wondering, am I really writing because it has been a really long gap after which this post is coming up. Well, there have been things that I was held back with and even now there are things, but it gives me pleasure to see that I am still writing..or rather blurting whatever is coming to my mind. And that is what I do with every post. That is why there is a mix of stuff out there.

 To be honest, when I started blogging, I had no definite plans as to what I would write on. So, as and when things have been popping up, I have been jolting them down (That sounds nice..isn't it ? :) , of-course there is one more underlying 'strong' reason for the mix of topics you see here, that being, I am more of a jack of all trades...and of-course master of none :D ) So, I am assembling here different kind of posts with the hope that everyone finds something here that interests them (I know not every topic will be of interest to everyone ) and I know that the readers are intelligent enough to dig down and get what interests them :) . Thus, i can go for stunt of writing diverse things under the roof of a single blog when i am blessed with such an intelligent set of readers. So, I am listening to the instincts for now that says - just go for it :)

Jokes apart, now a few posts down the line I have started reflecting on the aspects of blogging which I had not even thought of initially when I started on. For instance, it would be a pleasure to look back and see what all I had got to share, as the posts grow old (and you and me too :) ). Also, it gives such a nice space to not only share your thoughts, little observations from life (like hope), but to vent out your feelings wrapped in a nice coat of sugary words (like the post Who is a development manager ). You get to connect with like minded people and when the topics are diverse, then you get to connect to many like minded people who share your thoughts on the different topics...
So, thanks for bearing with the different posts so far,and do hang on, i will be writing soon again :) . Lots of stuff is piling up, need to slowly jolt them down and present forth, which I would do soon.
If you like my writing, you can award me an excellence medal :P i really like the one below :) :)