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 :) :)

Sunday, 8 September 2013

Best of Ayn Rand quotes

"The question isn't who is going to let me; it's who is going to stop me."
“Learn to value yourself, which means: fight for your happiness.”

“A creative man is motivated by the desire to achieve, not by the desire to beat others.”

 “If you don't know, the thing to do is not to get scared, but to learn.”  
  - Atlas Shrugged

 “I started my life with a single absolute: that the world was mine to shape in the image of my highest values and never to be given up to a lesser standard, no matter how long or hard the struggle.”

“You can avoid reality, but you cannot avoid the consequences of avoiding reality.”

“Never think of pain or danger or enemies a moment longer than is necessary to fight them.” 

- Atlas Shrugged

“A government is the most dangerous threat to man's rights: it holds a legal monopoly on the use of physical force against legally disarmed victims.” 

“I worship individuals for their highest possibilities as individuals and I loathe humanity for its failure to live up to these possibilities.”

“She did not know the nature of her loneliness. The only words that named it were: This is not the world I expected.”

“What greater wealth is there than to own your life and to spend it on growing? Every living thing must grow. It can't stand still. It must grow or perish.”

-  Atlas Shrugged

“Live and act within the limit of your knowledge and keep expanding it to the limit of your life.” 
-  Atlas Shrugged

“There's no way to rule innocent men. The only power any government has is the power to crack down on criminals. Well, when there aren't enough criminals, one makes them. One declares so many things to be a crime that it becomes impossible for men to live without breaking laws.” 
-  Atlas Shrugged

“Men who reject the responsibility of thought and reason can only exist as parasites on the thinking of others.” 
- The Virtue of selfishness

“Self-sacrifice? But it is precisely the self that cannot and must not be sacrificed.”
- The Fountainhead

“Ask yourself whether the dream of heaven and greatness should be left waiting for us in our graves-or whether it should be ours here and now and on this earth.”
-  Atlas Shrugged

“It is not advisable to venture unsolicited opinions. You should spare yourself the embarrassing discovery of their exact value to your listener.” 
-  Atlas Shrugged

“Power-lust is a weed that grows only in the vacant lots of an abandoned mind. ”
-  Atlas Shrugged

“A rational man never distorts or corrupts his own standards and judgment in order to appeal to the irrationality, stupidity, or dishonesty of others.”  
- Atlas Shrugged

“In a free society, one does not have to deal with those who are irrational. One is free to avoid them.”  
- The Virtue of selfishness

“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.” 
-  Atlas Shrugged









 

Monday, 2 September 2013

hope..

The other day when I was taking my mom from hospital back to home, in this auto-rickshaw, mid noon, I had a really rough time with the auto driver. I had been already going though a rough patch in life - having been recently met with an accident and most of the family members ailing.I was dealing with the downs of life, waiting patiently for the bad time to pass on, but, when the auto rickshaw driver started blabbing complaints and demanding more money because we were living in a street and not on the main road, the limits to my patience burst and I ended up in this heated argument with him which left me feeling bitter about the infrastructure around us, the law-and-order and the kind of people that we have to deal with.
Days later, when me and hubby were headed for a place somewhere in Vijayanagar, Bangalore for
image source : LINK
some work, we ended up in this small street that was heading straight to the cattle barn, with no side streets and reversing the car looked like a nightmare because half of the population from the houses - children and old alike - was on the street itself (thanks to the Google map and some people who would confidently guide you even if they themselves have no idea what you are looking for). We were not sure what to do next. Gathering courage, we started reversing the vehicle at a very very small pace, doing our best not to hurt anyone in the process. Slowly, the residents started helping us out, they started managing their children and gathering other stuffs like the drying spices and water buckets that they had laid out on the road while going through their daily chore. They also started guiding us to help make the reversing process smoother. There was this one really great guy who looked like a cab driver residing there, who took extra efforts to help us out of the nightmarish ordeal in that street. The incidence, although draining and tiring, filled my heart with hope and happiness - on finding so much friendliness and supportive attitude in the people out there. So, the good things do still exist :)
When I started writing this post, I just felt like putting the two incidences together, maybe to remind myself that there are both sides to life, that there are things that are good here and there are things that are bad. I hope we slowly improve upon things that are bad, and the experience of our next generation would be better than what it has been so far for us...


Image source : LINK


Wednesday, 28 August 2013

Biscuit Corn Sev Poori

We had this quick and super easy biscuit corn sev poori recipe made this weekend for snacks when we were super hungry :). Just some ready-made and some already available ingredients made to work together , giving a sweet-sour-tangy taste to satisfy the taste buds :)

Ingredients:

  1. 10 salty biscuit - I used the parley monaco biscuits, you can use any you like, even the regular cream crackers
  2. fine sev or any potato mixture  like the haldiram aaloo bhujiya or the lahar aloo bhujiya - 1/2 cup
  3. finely chopped corianders - 1/4 cup
  4. finely chopped onion - 1/2 cup
  5. finely chopped tomato - 1/2 cup
  6. one large potato - boiled and finely mashed
  7. one cup boiled corn or sweet corn kennels
  8. 1 tsp roasted cumin powder
  9. 1 tsp roasted coriander powder
  10. 1 tsp black salt powder
  11. 2-3 tsp green chutney
  12. 2-3 tsp sweet chutney - can be tamarind or tomato or mango - whatever you prefer
  13. 2-3 tsp diluted tamarind paste
  14. salt to taste
  15. green chilli -1 - finely chopped

Method:

Spread the biscuits on a plate. Mix the mashed potatoes, corn, coriander leaves, coriander powder,  cumin powder, onion, tomato, black salt, salt and green chilli together and add equal portions of this mixture on top of each biscuit. Top each one of these with equal portions of green chutney, sweet chutney and diluted tamarind paste. Spread sev equally over each one of these and serve immediately.
Below is a snap of how mine looked after preparing, could have been a better snap. I will post more when again make this dish a second time. But believe me, it turned out to be so mouth watering tasty, I am sure I will make another one soon.

 Diluted tamarind paste:You can make it by mixing 1/4 tsp readymade tamarind paste with 2-3 tbsp water and properly dissolve the tamarind paste in water, or you can also make it by dissolving one ripe tamarind ball in 2-3 tbsp water, ofcourse after de-seeding it.
Green chutney: You can use a standard green coriander chutney, or a coriander+garlic chutney or a mint coriander chutney for the same. Here are some great links on how you can make it:
(I will post my own blog on how to prepare each one of these, as soon as possible, please bear with me till then)
Sweet chutney: You can use a sweet tamarind chutney or a sweet mango chutney. I will soon write to you how I prepare them, till then, you can use these links for reference :

Thursday, 22 August 2013

This is going to hurt just a little bit...

My mom got a bad tooth ache last night and once again it reminded me the infamous lines from Odgen Nash "Because some tortures are physical and some are mental, But the one that is both is dental", true to the core. All those who have had to go through either this dental torture at some point of time in their life, or those who didn't have to because they pay regular visit to their dentists and willingly take-up the pain in small installments to avoid the big hit, would nevertheless agree with me, Odgen Nash so very well summarizes all their feelings into his amazing words in this poem - dedicating this post to his poem "This is going to hurt just a little bit...." and to all the victims of dental torture.

"One thing I like less than most things is
sitting in a dentist chair with my mouth wide open.
And that I will never have to do it again
is a hope that I am against hope hopen.

Because some tortures are physical and some are mental,
But the one that is both is dental.

It is hard to be self-possessed
With your jaw digging into your chest.
So hard to retain your calm
When your fingernails are making serious alterations in your life line
or love line or some other important line in your palm;

So hard to give your usual effect of cheery benignity
When you know your position is one of the two or three in life most lacking in dignity.

And your mouth is like a section of road that is being worked on.
And it is all cluttered up with stone crushers and concrete mixers
and drills and steam rollers
and there isn’t a nerve in your head that you aren’t being irked on.

Oh, some people are unfortunate enough to be strung up by thumbs.
And others have things done to their gums,
And your teeth are supposed to be being polished,
But you have reason to believe they are being demolished.

And the circumstance that adds most to your terror
Is that it’s all done with a mirror,
Because the dentist may be a bear, or as the Romans used to say,
only they were referring to a feminine bear when they said it, an ursa,

But all the same how can you be sure when he takes his crowbar in one hand and mirror in the other
he won’t get mixed up, the way you do when you try to tie a bow tie with the aid of a mirror,
and forget that left is right and vice versa?

And then at last he says That will be all;
but it isn’t because he then coats your mouth from cellar to roof
With something that I suspect is generally used to put a shine on a horse’s hoof.

And you totter to your feet and think.
Well it’s all over now and afterall it was only this once.
And he says come back in three monce.

And this, O Fate, is I think the most vicious circle that thou ever sentest,
That Man has to go continually to the dentist to keep his teeth in good condition
when the chief reason he wants his teeth in good condition
is so that he won’t have to go to the dentist."
 
 

Monday, 19 August 2013

Ma's Aaloo Parathas

Difficulty Level : Medium

Time Required : 1 Hour +


Well, I need not stretch on the authenticity and the taste of this delicacy. It's directly from Mom, she made it yesterday morning for breakfast. It was one of those rare occasions when she kept taking out the hot parathas right from the pan and we ate, without keeping a track, could eat no more. So, here goes the recipe for mom's aaloo paratha (The recipe below would serve 4) :

Ingredients:

For the filling:

  • Potatoes , medium - 4  , boiled and peeled
  • Onion - 1 medium
  • Garlic - 6-7 cloves
  • Ginger - 1" piece
  • Salt to taste
  • Turmeric powder - 1/2 tsp
  • Coriander powder - 1/2 tsp
  • Cumin powder - 1/2 tsp
  • Garam masala powder - 1/4 tsp
  • Green chillis - 2 to 3
  • Red chilli powder - 1/8 tsp (almost 2 pinches)
  • 1 tbsp vegetable oil for frying the filling material.
  • 1 tsp ghee or refine oil or butter for each of the parathas.
  • 1 tbsp finely chopped coriander leaves

For the Dough: 

  • 2 cups whole wheat flour  
  • Enough water to kneed a soft dough

Method:

For preparing the filling, cut onion into small pieces. Mince the ginger and garlic . In a heavy bottom frying pan or wok, heat 1 tbsp vegetable oil. When hot, add the onion, ginger and garlic to it. Saute till the onion turns translucent. Then add the spices and green chilli (cut into fine pieces) to it. Cook for another 2-3 minutes, or, until the spices give a cooked aroma. Mash the boiled and peeled potatoes and add to the pan. Mix well with rest of the spices etc. Sprinkle salt as per taste and then mix everything well. Smooth out the filling mixture so that there are no lumps left into it. (If there are lumps left, when you will fill it in your parathas, they may split while rolling). Now, add the finely chopped coriander leaves to the filling mixture and mix well. Set it aside to cool while you work on the dough. For the dough, take the wheat flour and gradually add water to it, making a soft dough. Divide this dough into 12 equal portions. Take each portion between your palms and then roll it into a smooth ball (like you do to make any other chapati or flat Indian bread). Now, make a dip inside one  ball with your finger, add a teaspoon of the filling mixture inside it and then seal its mouth (like you do for any stuffed paratha). Dust with dry flour and roll out paratha using an Indian rolling pin. Now , heat a pan and put the paratha into it. Apply 1/2 tsp oil/ghee to both sides of the paratha and let it cook on the pan till its cooked (it would turn dusky in color with golden brown patches on it :) )
Make the rest of the parathas the same way. Serve them hot. 

Serving the potato stuffed parathas:

Potato stuffed parathas can be served with a verity of side dishes like curd, raita, kheer (rice pudding), sewai (vermicelli pudding), or chutneys like tomato chutney, green chutney, coriander chutney, pudina chutney,sweet mango or tamarind chutney, anchar (pickles), or any gravy reach vegetables like masala gobhi (cauliflower curry) or chole (chikpeas curry). Slowly I will add the recipes for these as well ,to the blog :)

Invariantions while roasting the parathas:

You can roast the potato stuffed parathas in more than one ways. You can either choose the way I described above, or, you can roast it dry , take it out of tawa/pan and then apply butter or ghee on top of it. Its a delight to see the butter melting on your hot paratha. This option of applying the ghee or butter on the parathas post preparing them makes them softer while with the previous procedure of applying oil to them while they are on the pan, you can make them crunchier if you want.

Finally, a snap of my mother's yummy aaloo parathas:

Friday, 16 August 2013

Oh!! These Dreams....

Do you remember that dream sequence from "Kung fu Panda 2" where the Panda dreams of his parents deserting him? He runs after them and they say something like 'we have replaced you with this radish which is better than you and does a better kung fu' and post that the radish actually starts doing the kung fu and takes the panda completely off - guard. And finally, it wins over and then gets transformed into a symbol that is haunting the panda. Parent replacing their child with a radish and then the radish performing kung fu and then suddenly converting into a symbol. Sounds bizarre!! Right?

Do you as well remember Inception - levels of dreams and so much technicalities involved!!Where , it rains in one level of dream and it floods in the other. Able to correlate to these? I am, absolutely. As, I am one of those individuals that get lots of dreams - all kinds of dreams - and even dreams within dreams. I don't remember a night when I had such a sound sleep that I didn't get a single dream. Well, they don't let me have a sound sleep, but I still love them. They are bizarre, sometimes sweet, sometimes scary, sometimes adventurous and sometimes very depressing - but one thing is sure, they bring me nearer to my subconscious self , which is overpowered by my conscious mind all through the day, involved into the day to day activities of mere or no significance.And, they provide me these boundless and countless opportunities of achieving the impossibles.
Some interesting factors that I have observed about my dreams:
Achieve the impossible : I dream of friends and relatives whom I desire to meet but haven't been able to, since long, and they stop after I get to meet them. I have para glided, conquered mountains and sailed through the 7 seas in my dreams. And I have died a thousand deaths - falling from the mountain peaks and being chased by enemies, fighting all kind of odds and what not. The most wonderful thing is how some dreams span across days in episodes , and how at times they are so symbolic and rhythmic. Sometimes they even helped me make a decision, which I possibly couldn't have with my conscious mind which keeps pondering over all the aspects of the situation.
Stitch - in the outside environment: Once I was having this dream and in the dream it started raining, I tried to escape the rain, but didn't help, I took a shelter, still no protection from the rain. Then finally I woke up, and then I saw it was actually raining outside and the rain water was coming inside from the open window - the reason I couldn't escape the rain in my dream :)
All emotions, including sarcasm: You won't really believe how once my mind could spin a dream which was so sarcastic. I had this manager who was so used to "explaining" and "expanding" every talk. You reach out to him with one simple question that could have been answered in 1 sentence and yet he would weave a whole big one-hour lecture on the subject, there won't be any escape.Sometimes, he would even lecture just like that. So, one fine day, I dream of him, at my native place. He was giving bath to my late doggie and at the same time lecturing about how to give bath to a dog in the best possible way!!!! I was amazed by the sarcasm of my own subconscious, having this dream.
Communication between the subconscious and conscious mind:  Sometimes, it feels like the mind knows that its a dream going on. If its a sweet and charming dream - the mind says - keep sleeping, have more of it. While, when its a fearful, tragic or painful dream, the mind jolts us out of it, when we are no longer able to take it.
There are countless amazing facts about dreams. Newborns who hardly know what to do and how to do when they are awake, are able to dream. Animals, who so much lack the intellect that human race boasts of, even they are as capable of dreaming as us. Some of you must have had dreams of future forecasts as well - like the exact number on your mark-sheet in  that maths paper etc.  But "why do we dream" is still a mystery. If you come to know something interesting about these dreams, do share across.

Here's a resourceful article on dreams: http://www.psychologytoday.com/blog/the-literary-mind/200911/why-do-we-dream.
More reference materials:
http://psychology.about.com/od/statesofconsciousness/p/dream-theories.htm
http://news.nationalgeographic.co.in/news/2011/11/111129-sleep-dreaming-rem-brain-emotions-science-health/

If interested to find more, just Google for "why do we dream" and you would get numerous links around the same.


Wednesday, 14 August 2013

Paneer Malai Kofta

Difficulty Level : Medium 

Time Required : 1 Hour +


This recipe is not really tough, just takes a bit more time to prepare - anywhere between 30-45 minutes. But once done, you won't at all regret the time spent, and in fact, you would like to spend time on it as much as possible :)
Here goes the recipe, I prepared it yesterday and my whole family liked it a lot. This recipe would serve 4-5 people.
Ingredients:
  • Potatoes - medium - 3 , boiled and peeled
  • Paneer or cottage cheese - 200 gm
  • Raisins - 1 tbsp
  • Cashewnuts - 3 tbsp
  • Fresh cream - 1/2 cup (if not available , replace by 1/2 cup thickened milk)
  • Coriander powder - 1 and 1/2 tsp
  • Garam masala powder - 1/2 tsp (I substituted it with kitchen kind masala)
  • salt - as per taste
  • Corn flour - 3 tbsp
  • Refined oil - 1 cup - for deep frying the koftas
  • Vegetable oil or mustard oil - 3 tbsp for preparing the curry
  • Onion - 1 large
  • Tomatoes - 2 large
  • Green chilli - 1
  • Khara garam masala - 2 cardamom, 2 cloves and 1medium  piece of cinnamon
Method:
For the Koftas:
Mash the potatoes. Grate the paneer and add to the mashed potatoes. Add corn flour, salt to taste , 1/2 tsp coriander powder, 1/4 tsp garam masala powder, all the raisins and 1 tbsp cashew nuts to it. Mix everything together. Take small amounts of this mixture into your hand and roll into a round ball. 
Try making all the balls of the same size, for this, you can pre-divide the mixture into equal portions. You can make small, medium or large balls depending on your choice. Put a heavy bottom pan on the stove and pour the refined oil into it. Let the oil heat up to frying temperature. One by one drop the balls in the the oil and let them fry till golden brown. Turn them once or twice so that they are equally fried from all sides. Take them out. Below are some snaps of the balls (koftas) that I prepared:
One side of the plate are the koftas which are fried (golden brown ones) and the other side are the one to be fried.


All koftas fried :)
For the curry or gravy:
Peel and cut the onion into 2 halves. Cut the tomatoes in 2 halves as well. Add them to a pan with water and let them boil on medium heat for 7-10 minutes. Once done, put off the flame, take them out and let them cool. Add 2 tbsp cashew nuts to water and leave them soaked for 10 minutes. After 10 minutes, grind them to a fine cashew paste and set aside. Once the onion and tomato pieces are cold enough to grind in a mixie, add them to the mixer along with the chilli and grind to a smooth paste. Put a wok on the flame and add the mustard oil to it. When hot, add the onion and tomato paste and then fry it till the raw smell of tomatoes is gone (takes nearly 10 minutes) . Then add to it 1 tsp coriander powder, 1/4 tsp garam masala powder, salt to taste and fry for 2-3 more minutes. Now add the cashew paste and fry for one more minute. Add the khara garam masalas to it. Now add the whipped cream and mix everything so that the gravy has a smooth texture. Add 4-5 cups water and let it boil to a smooth consistency. After 2-3 minutes, turn off the flame and drop the kofta balls into the gravy. Your paneer malai kofta is ready, let it sit for 10-15 minutes before serving, the kofta will absorb the gravy and thus, the gravy will become thick in consistency.
After that you can serve it with naan, or tandoori roti or freshly made rice or any rice preparation like pulav or jeera rice.
Decoration :
You can decorate your yummy paneer malai kofta with some grated panner, some red chilli powder, corainder leaves and top it with fresh cream. Below is a snap of how mine looked like:
Paneer malai Kofta, just after putting off the flame.

Paneer Malai Kofta, after it absorbed the gravy and was decorated with grated paneer.