How did I setup SSL with HTTPClient-4.1.2

I've been struggling to get this working for about 2 days now. I was able to POST a request directly from sockets, but it took me a while to see it working with HTTPClient-4.1.2. There are different variants out there in google for legacy HTTPClient and less than 4.1.x.
The key was to specify TrustManager and KeyManager while initializing SSLContext.

Step-1: First, you have to initialize SSLContext like this:

SSLContext ctx = SSLContext.getInstance("TLS");

Step-2: Getting TrustManager. Java look into its trust managers to check against authorized Certification Authorities(CA). Default trust store in Java is "jks". This is how you can get trust manager:
TrustManager[] getTrustManagers(String trustStoreType, InputStream trustStoreFile, String trustStorePassword) throws Exception {
KeyStore trustStore = KeyStore.getInstance(trustStoreType);
trustStore.load(trustStoreFile, trustStorePassword.toCharArray());
TrustManagerFactory tmfactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
tmfactory.init(trustStore);
return tmfactory.getTrustManagers();
}

It should be called as:
TrustManager[] trustManagers = getTrustManagers("jks", new FileInputStream(new File("/Library/Java/Home/lib/security/cacerts")), "changeit");

/Library/Java/Home/lib/security/cacerts is the default path to trust managers in Mac OSX

Step-3: Getting KeyManager: This is where your client certificates are stored. KeyManager in the code can be retrieved as :
KeyManager[] keyManagers = getKeyManagers("pkcs12", new FileInputStream(new File("clientCertificate.p12")), "password");

You have to get KeyManagers using KeyManagerFactory like this:

KeyManager[] getKeyManagers(String keyStoreType, InputStream keyStoreFile, String keyStorePassword) throws Exception {
KeyStore keyStore = KeyStore.getInstance(keyStoreType);
keyStore.load(keyStoreFile, keyStorePassword.toCharArray());
KeyManagerFactory kmfactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
kmfactory init(keyStore, keyStorePassword.toCharArray());
return kmfactory.getKeyManagers();
}

Step-4: Once you have TrustManager and KeyManager ready, pass them in SSLContext:
ctx.init(keyManagers, trustManagers, new SecureRandom());

Step-5: Now create a SSLSocketFactory object using SSLContext object:
SSLSocketFactory sf = new SSLSocketFactory(ctx, new StrictHostnameVerifier());

Step-6: Assign Scheme to the HttpClient:
DefaultHttpClient httpclient = new DefaultHttpClient();
ClientConnectionManager manager = httpclient.getConnectionManager();
manager.getSchemeRegistry().register(new Scheme("https", 443, sf));

Done !
Now use this httpclient in HttpPost, HttpGet ….

My take on setting up Jenkins for PHP project on Mac OSX

I've found many good articles on setting up Jenkins for PHP projects. But couldn't get one which is targeted to Mac OSX. Here is the one, I followed to setup Jenkins for myself. I took following steps to setup one on Mac OS:

1- Installing php5 and pear using mac-ports: sudo port install php5 +pear
Enable libphp5.so module in apache configuration file: /etc/apache2/httpd.conf

2- Installing/configuring xdebug using macports:
command: sudo ports install php5-xdebug
Macports automatically put xdebug.so in /opt/local/lib/php/extensions/no-debug-non-zts-20090626

Copy xdebug config in /etc/php.ini
[xdebug]
zend_extension="/opt/local/lib/php/extensions/no-debug-non-zts-20090626/xdebug.so"
xdebug.remote_enable=on
xdebug.remote_handler=dbgp
xdebug.remote_host=localhost
xdebug.remote_port=9000

Check debug installtion:
php -r 'var_dump(extension_loaded("xdebug"));'

3-Install ant using macports
sudo port install apache-ant
Macports installs ant in : /opt/local/bin/ant

4- Follow this tutorial for creating demo project and other steps:
http://edorian.posterous.com/setting-up-jenkins-for-php-projects

I had trouble in installing phpunit. I had to do install following packages as well in addition to the packages mentioned in above tutorial:
sudo pear install -f Net_URL2-0.3.1
sudo pear install HTTP_Request2-2.0.0RC1
and then
sudo pear install --alldeps phpunit/PHPUnit

5- Jenkins jobs folderis located at: /Users/Shared/Jenkins/Home/jobs/
6- Restart jenkins using : java -jar jenkins-cli.jar -s http://localhost:8080 safe-restart
7- Reloading jenkins configuration: java -jar jenkins-cli.jar -s http://localhost:8080 reload-configuration
8- Checkout php-template job from this tutorial and reload configuration
9- You are Done !
10- Play around the Jenkins :-)

Linux command to find file names for matching pattern

Here is command to get files which contains the given pattern. For example, if you are trying to find "Got my text" in current directory and its sub directories, then following command will give line numbers along with file names that contains that text:

grep "Got my text" -nr ./*

Installing git-svn on Mac

git-svn can be installed on Mac using macports. Just this will do:
sudo port install git-core +svn

[MySql] How to add/delete a column from commandline

Following command is used to delete a column from a table:

ALTER TABLE <table_name> DROP COLUMN <column_name>;



Following command is used to add a column in table:

ALTER TABLE <table_name> ADD <column_name> <datatype> ;


[MySql] How to export MySql database schema using command line

Following command dumps MySql database's schema into a file:


mysqldump -u<username>i -p<password> -h<host> --databases <database1> --no-data > dump.sql

Above command exports single or multiple databases into dump.sql. This only exports database schema without any table contents.


This exported schema can be restored using following command:


mysql -u<username>i -p<password> -h<host> <database_name> < dump.sql

Uploading files to Remote Server


There are different ways we can upload files to remote servers. Few command line tools are listed here"
1- Securely Copy files (scp):
scp -v -r -o IdentityFile=<cert.pem> <source folder> <user>@<remoteserverip>:/home/<user>/<destination folder>

Note: If a certificate is needed, then IdentityFile=<cert.pem> should be used.

2- rSync: 
rsync -vcrz --delete-after <source folder> <user>@<remoteserverip>:/home/<user>/<destination folder>

jQuery Chaining Interview question

Which one of the following will break the chain and Why?
A-

$(…)
.html('Breaks chain')
.addClass('chainbreaker')

B-

$(…)
.html()
.addClass('chainbreaker')

Solution:
In A, .html('Breaks chain') behaves like a setter and returns object, on which .addClass(…) adds the given class. But in B, .html() behaves like a getter and returns a string, on which .addClass(…) methods fails to perform and gives runtime error.

How to get File Extension in PHP ?

Very Simple! This command should do that:
$ext = pathinfo($filename, PATHINFO_EXTENSION);

Another GoogleDoc API Issue

After getting past of one issue. Here is another error log I got:
com.google.gdata.util.ResourceNotFoundException: Not Found <HTML> <HEAD> <TITLE>Not Found</TITLE> </HEAD> <BODY BGCOLOR="#FFFFFF" TEXT="#000000"> <H1>Not Found</H1> <H2>Error 404</H2> </BODY> </HTML>

Solution is simple ! Replace URL mentioned in Google documentation.
Replace this: URL documentListFeedUrl = new URL("http://docs.google.com/feeds/documents/private/full");
To: URL documentListFeedUrl = new URL("http://docs.google.com/feeds/default/private/full");

You will get your document listing :)

Started Using GoogleAPIs ?

I have recently tried out google apis and found this dazzling problem after importing all the jars documented in GoogleAPI documentation:

Exception in thread "main" java.lang.NoClassDefFoundError: com/google/common/collect/Maps
at com.google.gdata.wireformats.AltRegistry.(AltRegistry.java:118)
at com.google.gdata.wireformats.AltRegistry.
(AltRegistry.java:100)
at com.google.gdata.client.Service.
(Service.java:555)
at TestDocumentList.main(TestDocumentList.java:14)
Caused by: java.lang.ClassNotFoundException: com.google.common.collect.Maps
at java.net.URLClassLoader$1.run(URLClassLoader.java:202)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
at java.lang.ClassLoader.loadClass(ClassLoader.java:307)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
at java.lang.ClassLoader.loadClass(ClassLoader.java:248)
... 4 more


Actually, in documentation they forgot about importing google-collect-1.0-rc1.jar. You can find this jar in gdata/bin/deps/google-collect-1.0-rc1.jar. Don't forget to add this in your build path.

How to make MySQL working on Mac OS X

Installing and configuring MySql in Mac was such a pain for me. I have installed and run MySql on Windows and Linux systems at least for 20 times by now, without any trouble. I assumed it will be quite simple in Mac as well. Actually, I hoped for easy installation because Apple products are considered user-friendly....but not developer friendly :(

Anyhow, I got it working now :)
1- Download binary from Mysql downloads
2- Copy /usr/local/mysql/support-files/my-medium.cnf to /etc/my.cnf
3- Start MySql using : /usr/local/mysql/support-files/mysql.server start
4- Stop MySql using : /usr/local/mysql/support-files/mysql.server stop
5- Check MySql Status: ps xa | grep "/usr/local/mysql/bin/[m]ysqld"

You may get some errors in bin dir path. You may want to fix paths in /usr/local/mysql/support-files/mysql.server (at least I did)

I have installed Workbench GUI for administration purpose. Good enough to give a try !

How to disable Mysql at startup in Mac OS X

1- Open hostconfig file in vi editor : vi /etc/hostconfig
2- Change "MYSQLCOM=-YES-" to "MYSQLCOM=-NO-"
3- Save and exit

Apache error log in Mac OSX

Its located at: tail -f /private/var/log/apache2/error_log

GIT: Squash (Comitting multiple files to gerrit under one review)

I am showing here how to push multiple files under one gerrit review.

Pre-requisites: You need commit-msg hook configured in your local repository.
1- scp -p -P :hooks/commit-msg .git/hooks/
2- curl http:/:port/tools/hooks/commit-msg

Steps:
1- Work and commit usually in your local copy
2- git rebase -i HEAD~6 (6 is the numbers of version you want to squash together)
3- pick base version and replace "squash" for "pick" for the commits you want to squash together. All squashed commits will go together with the "pick" one into gerrit review.
3- Modify changeId in rebase process when asked (make sure changeId should be same as that of already created review process)
4- push to gerrit

Git Stash

Stashing your changes: It saves your local changes on stash stack and revert your working copy to HEAD
git stash save
bash-3.2$ git stash save
Saved working directory and index state WIP on testing: fb1f22c This is test commit commit-amended
HEAD is now at fb1f22c This is test commit



Viewing your stashed changes:

git stash list
bash-3.2$ git stash list
stash@{0}: WIP on testing: fb1f22c This is test commit commit-amended
stash@{1}: WIP on testing: fb1f22c This is test commit commit-amended


Applying your stash :
git stash apply stash@{0}

OR
This applies latest stashed copy of your changes
git stash pop


Deleting Stash
  • Delete Particular Stash:
    git stash drop stashId
    bash-3.2$ git stash drop stash@{0}
    Dropped stash@{0} (3b88e6278d1bb2bcf600ff9a5dde50116361a200)
  • Delete All Stashes:
    git stash clear

Installing Hudson on Mac OS X (Snow Leopard)

This is a 5 step process:
  1. Install hudson.war in your download directory : ~/Downloads
  2. Create a hudson directory in your home folder : mkdir -p ~/hudson
  3. Copy hudson.war from ~/Downloads/ to ~/hudson directory: cp ~/Downloads/hudson.war ~/hudson/hudson.war
  4. Run hudson at port of your choice: java -jar ~/.hudson/hudson.war --httpPort=8082
  5. Configure Hudson Jobs !

Creating Multi level directory in Linux

Linux doesn't create a directory at an unknown path. For example- If I want to create a directory firstLevel/secondLevel, firstLevel should already exists. Otherwise, give -p option with mkdir like this:

mkdir -p firstLevel/secondLevel

This will create firstLevel first, and then secondLevel under it.

Steps to create a Gerrit review

Git and Gerrit have been quite confusing together sometimes. Specially, in lack of good documentation. Doesn't seem like lot of people are using them efficiently.   
In this post, I am trying to explain that how to create a review in gerrit and modifying a file under one review multiple times.

Pre-requisites: You need commit-msg hook configured in your local repository.
1- scp -p -P <gerritserver>:hooks/commit-msg .git/hooks/
2- curl http:/<gerritserver>:port/tools/hooks/commit-msg

Step-1. Change a file
Step-2. Commit this file using: git commit -a -m "commit message"
Step-3. Push change to gerrit to create a new review. git push gerrit HEAD:refs/for/branchname
Step-4. Amend a file for the next change: git commit --amend <filename>
Step-5. Iterate Step-3,5

Using ImageMagick to Crop an Image

I was looking into ImageMagick to understand its crop option. Since, I don't have very good understanding of image components and its terms, I couldn't make much sense out of it. But looks promising. Now, I am hunting for some friendly examples for crop feature. I was referring to this link to understand it: crop_gravity

Scheduling Repeating Local Notifications using Alarm Manager

Learn about Scheduling Repeating Local Notifications using Alarm Manager in this post .