Monday, December 12, 2011

How to comment code in VI or VIM

Mark the area which is to be commented using the *blockwise* visual mode (CTRL-V, in Windows this is CTRL-Q).

Press I (capital i) and write the text you want to prepend to each line of the selected block, e.g. #####.

Then press ESC and the text will be inserted to the left of each line of the selected block.

getResouce and Files in java. I just hate having to search for this every time.

To get a file inside a jar, you have to do the following:

URI resourceURI = this.class.getResource("/path/to/file/in/jar/config.txt").toURI();

To open the file using a file you can do:

File theFile = new File(resourceURI);

To read the contents of the file:

List<String> lines = Files.readLines(theFile, Charsets.UTF_8);

To read the files in a directory:

// Load the directory as a resource
URL dir_url = ClassLoader.getSystemResource(dir_path);
// Turn the resource into a File object
File dir = new File(dir_url.toURI());
// List the directory
String files = dir.list()

Monday, October 31, 2011

"Run On Server" not showing up in Eclipse with m2eclipse?

Okay, I went through this problem in Eclipse Indigo for J2EE Developers release that m2eclipse wont show me the Run On Server selection in the Run menu when I import a maven project with war packaging (ie. the maven-archetype-webapp).

Here is how to fix it:
1. Uninstall the current m2eclipse plugin you have in eclipse:
  (a) Go to "Help > Install New Software"
  (b) Click on the "What is already installed?" link
  (c) Select "m2e - Maven Eclipse Integration" and click on the "Uninstall" button
  (d) Restart eclipse when prompted

2. Next, you have to install the m2eclipse:
  (a) Go to "Help > Eclipse Market Place"
  (b) Search for the word m2eclipse
  (c) Select "Maven integration for eclipse"
  (d) Click the "Install" button

3. Install the "Maven Integration for Eclipse WTP"

  (a) Go to "Help > Eclipse Market Place"
  (b) Search for the word m2eclipse
  (c) Select "Maven integration for eclipse WTP
  (d) Click the "Install" button

Restart when prompted.

Now, importing a maven project with war packaging will work out of the box. Enjoy.

Sunday, October 23, 2011

Configuring Eclipse to run with a specific JDK or JRE

1. Open the file eclipse.ini for editing

2. Add the two lines to specify the virtual machine to use (the bolded lines):


C:\Program Files\Java\jdk1.6.0_29\bin\javaw.exe


3. Now start eclipse.

Wednesday, October 19, 2011

Wonderful Iphone Icon Generator Online

Give your divs a simplistic nice shadow with css

I loved the middle box shadow in the website, and therefore decided to dig it up. The CSS used for it is:

-moz-box-shadow: 0px 0px 15px rgba(0,0,0,0.1);
-webkit-box-shadow: 0px 0px 15px rgba(0,0,0,0.1);
box-shadow: 0px 0px 15px rgba(0,0,0,0.5);

Monday, October 17, 2011

Using mod_jk with Apache 2.2 How to setup a reverse proxy

Advice on mod_jk versus mod_proxy and mod_proxy_ajp
Do not use mod_proxy and mod_proxy_ajp on Apache 2.2 since they are not stable and have caused me some problems. Use mod_jk instead.

Prerequisites & Assumptions Before you continue
I assume you have:
- You already have Apache Webserver 2.2 installed
- You already have Tomcat installed
- You already have a web application on Tomcat with context "jobsapp"
- You are using Redhat Enterprise or CentOS and therefore have yum on your system.

How to get the mod_jk binary for Apache 2.2 on Linux
You wont find it anywhere, you have to compile it, now stop being lazy and start working.

The following steps detail the process:

// Create a temporary source directory, I use /opt/src
mkdir /opt/src
cd /opt/src 

// Get the source package

// Install packages needed to compile the binary
yum install httpd-devel
yum install gcc-c++

// Extract the tar.gz file
tar -zxvf /opt/src/tomcat-connectors-1.2.32-src.tar.gz

// Configure, make, make install
./configure --with-apxs=/usr/sbin/apxs
su -c 'make install'

How to configure Apache Webserver with Mod JK

1. Edit the file httpd.conf
vim /etc/httpd/conf/

2. Add this line to load the module:
LoadModule jk_module modules/

3. Add also the following lines:

JkWorkersFile   conf/
JkLogFile       /var/log/httpd/mod_jk.log
JkLogLevel      debug
JkRequestLogFormat      "%w %U %T"
JkOptions +ForwardURIEscaped +ForwardURICompatUnparsed

After finishing, change JkLogLevel from debug to "error" or "info" so that the log file doesn't grow too much in size.

4. Now create a file names inside /etc/httpd/conf/ and add the following lines to it:
vim /etc/httpd/conf/

# Worker Properties file for mod_jk

4.5. Make sure to read the mod_jk attributes in this link:

5. Now open the httpd.conf or your virtual host configuration file and add the following lines:

JkMount     /jobsapp tomcat
JkMount     /jobsapp/* tomcat

6. Also open the ssl httpd conf file which has the following line at the top,
and add the same two lines inside them:

<VirtualHost _default_:443>
JkMount     /jobsapp tomcat
JkMount     /jobsapp/* tomcat

7. Now restart apache

/etc/init.d/httpd restart

Tuesday, October 11, 2011

Adding deleted files in git

When you type:

git commit -a

Git will add the new, modified and deleted files automatically and commit them

However, there are cases when you want to 'git add' deleted files (that got deleted in your working directory).

I tried:

git add *

But this didn't workout. It only added the modified and created files.

I wanted a way to add the deleted files, I thought of issuing a 'git rm' command:

git rm *


So, what is the solution.

The solution is to use:

git add -u

The -u (show for --update) tells git to compare to the tracked files in git rather than the working directory.

According to the GIT manual:
'git add' man page says about the -u option...
Only match <filepattern> against already tracked files in the index rather than the working tree. That means that it will never stage new files, but that it will stage modified new contents of tracked files and that it will remove files from the index if the corresponding files in the working tree have been removed.
If no <filepattern> is given, default to "."; in other words, update all tracked files in the current directory and its subdirectories.

Sunday, October 09, 2011

Making a bash script know its current directory location

I use the following variables at the beginning of my Bash script to get such information:

THIS_SCRIPT_DIR=$(cd $(dirname "$0"); pwd)

#Do different tasks here


vim color tuning

A great way to tune color automatically in vim is by calling:

set background=dark

Since the default on linux is "backgroun=light"

I have also placed this inside the /etc/vimrc to have a global effect

Bash Tips

To check if a file exists (The exclamation ! means "not") :
if [ ! -f ${TOMCAT_DIR}/conf/jobsapp.conf ]
  echo "Do something"

To check if a script should be run by a specific user:
if [ "$(id -u -n)" != "root" ]; then
   echo "This script must be run as root user" 1>&2
   exit 1

To prompt a user for an action:

read -p "Deploy on Tomcat (y/n)?" CONT
if [ "$CONT" == "y" ]; then
  echo "Deploying on tomcat...";
  echo "Finished deploying on tomcat.";
  echo "Copied files, but didn't deploy on tomcat.";

.gitignore by example

A git ignore is a file named ".gitignore" that gets placed in the top level directory of your git workspace.

It informs git to ignore files when adding and committing files.

# Exclude files with an extension

# Do not exclude required.jar

# ignore the file TODO at the top level directory only
# thus /TODO will be ignored, but src/TODO will not be ignore.

# To indicate a directory for ignoring it should end with a "/"

# This line ignores all directories and subdirectories named log/

# This line only ignores the top level directory named build

# This ignores all files ending with txt inside doc/ directory, but not inside doc/example/

Important notes:
1. Files starting with / (slash) mean that you should start from the top level directory
2. The * (star) in doc/*.txt does not mean it will match any directories inside. It will only match top level files inside the doc directory ending with *.txt. Thus doc/example/test.txt will not be matched.

Tracking an /etc directory using GIT version control while preserving file permissions

.. while preserving permissions on the linux file system.

Here's how to do it:
1. Download the post hook file setgitperms from here or directly from here

2. Place the script inside your .git/hooks directory. You have two options here:

(Option A) To apply this for all git repositories newly created
Copy the file setgitperms.perl inside the directory:

mv setgitperms.perl /usr/share/git-core/templates/hooks/.

(Option B) To apply this hook for a specific directory only
Copy the file setgitperms.perl inside the directory:
mv setgitperms.perl <Your Project Directory>/.git/hooks/.

3. Although git new releases handles this, just to be safe, make sure to add execute permissions for the hook:
chmod +x setgitperms.perl

4. Inside the hooks directory, create a file named "pre-commit" and place in it the following lines:

SUBDIRECTORY_OK=1 . git-sh-setup
$GIT_DIR/hooks/setgitperms.perl -r

5. Create file named post-merge and post-checkout and place the following content inside each:

SUBDIRECTORY_OK=1 . git-sh-setup
$GIT_DIR/hooks/setgitperms.perl -w

6. Save the files and make sure they are executable using chmod +x:
chmod +x post-merge
chmod +x post-checkout
chmod +x pre-commit

7. Thats it.


Saturday, October 08, 2011

Installing Tomcat 6 on Redhat Enterprise

List of commands that took place:

cd /opt
ln -s /opt/apache-tomcat-6.0.33 tomcat
yum install java-1.6.0-sun
alternatives --config java

There are 3 programs which provide 'java'.

Selection    Command
1           /usr/lib/jvm/jre-1.4.2-gcj/bin/java
*+ 2           /usr/lib/jvm/jre-1.6.0-sun.x86_64/bin/java
3           /usr/lib/jvm/jre-1.6.0-sun/bin/java

Enter to keep the current selection[+], or type selection number: (Press 2 Then Enter)
vim /etc/init.d/tomcat

While in vim type the following in command mode to avoid extra spaces which pasting:
:set paste

Copy the following text and paste it:

#!/bin/bash # # Init file for SixSigns Tomcat server # # chkconfig: 2345 55 25 # description: SixSigns Tomcat server # # Source function library. . /etc/init.d/functions RUN_AS_USER=tomcat # Adjust run user here CATALINA_HOME=/opt/tomcat start() { echo "Starting Razuna Tomcat: " if [ "x$USER" != "x$RUN_AS_USER" ]; then su - $RUN_AS_USER -c "$CATALINA_HOME/bin/" else $CATALINA_HOME/bin/ fi echo "done." } stop() { echo "Shutting down Razuna Tomcat: " if [ "x$USER" != "x$RUN_AS_USER" ]; then su - $RUN_AS_USER -c "$CATALINA_HOME/bin/" else $CATALINA_HOME/bin/ fi echo "done." } case "$1" in start) start  ;; stop) stop  ;; restart) stop sleep 10 #echo "Hard killing any remaining threads.." #kill -9 `cat $CATALINA_HOME/work/` start  ;; *) echo "Usage: $0 {start|stop|restart}" esac exit 0

Then write and quit in vim:

Make sure the file doesn't contain microsoft new lines:
dos2unix /etc/init.d/tomcat

Now change to executable:
chmod +x /etc/init.d/tomcat

Next create a tomcat user:
groupadd tomcat
useradd -g tomcat -d /opt/tomcat tomcat
passwd tomcat
password: tomcat
retype password: tomcat

Reassign permissions to directories:
chown -R tomcat:tomcat /opt/tomcat
chown -R tomcat:tomcat /opt/apache-tomcat-6.0.33
cd /opt/tomcat/bin
chown +x *.sh

Add tomcat to services:
chkconfig --add tomcat
chkconfig --level 345 tomcat on

Start tomcat:
/etc/init.d/tomcat start

Finding ports and processes running on linux port 80

The command:

# To find processes running on port 80
lsof -i :80

A Wonderful CSS Tricks Website

Installing Tomcat 6 on Redhat Linux Enterprise or CentOS


Install Tomcat

With CentOS/RedHat you could install Tomcat from the YUM repositories, but they only hold the older 5.5.x version. Of course, if you want to have Version 5.5.x installed then you only have to issue a;
yum install tomcat*
But I do recommend that you install Tomcat 6.0.18 (the current version of this writing), since it features better memory handling and some other improvements. The official Tomcat page is your friend in this regard Luckily, installing Tomcat is straight forward.
  1. Download Tomcat 6.0.18
    1. Browse to and download the Binary Distribution or click on the direct link here Wget is your friend.
  2. I recommend to install Tomcat in the "/opt" directory. Thus copy the downloaded file into "/opt".
  3. Extract it with
tar xzvf apache-tomcat-6.0.18.tar.gz
  1. For better handling I always create a symbolic link for "tomcat" with
ln -s /opt/apache-tomcat-6.0.18 tomcat
  1. Test Tomcat
    1. Start Tomcat with:
    1. Hit http://localhost:8080. If all is fine you should see the Tomcat homepage.
All should be fine, right? Ok, move on.

Deploy (Install) OpenBD

  1. go into the tomcat folder
    1. cd /opt/tomcat/
  2. download the openbd.war file (be sure to check the OpenBD download site for the latest war file link)
    1. wget
  3. once the file has downloaded move it to the tomcat webapps folder where it will automatically deploy
    1. mv /opt/tomcat/openbd.war /opt/tomcat/webapps
  4. once the war file is in webapps Tomcat will pick it up and create an openbd folder
  5. go to the administrator
    1. http://localhost:8080/openbd/bluedragon/administrator
      1. the default bluedragon administrator password is admin

Configure Tomcat to run on startup

Now, that Tomcat and OpenDB runs nicely you might want to have it automatically started when you reboot your system. For that we can use the following script and "chkconfig" command line.
  1. Create a "tomcat" file in "/etc/init.d"
vi /etc/init.d/tomcat
  1. Copy the below startup script
# Init file for SixSigns Tomcat server
# chkconfig: 2345 55 25
# description: SixSigns Tomcat server

# Source function library.
. /etc/init.d/functions

RUN_AS_USER=tomcat # Adjust run user here

start() {
        echo "Starting Razuna Tomcat: "
        if [ "x$USER" != "x$RUN_AS_USER" ]; then
          su - $RUN_AS_USER -c "$CATALINA_HOME/bin/"
        echo "done."
stop() {
        echo "Shutting down Razuna Tomcat: "
        if [ "x$USER" != "x$RUN_AS_USER" ]; then
          su - $RUN_AS_USER -c "$CATALINA_HOME/bin/"
        echo "done."

case "$1" in
        sleep 10
        #echo "Hard killing any remaining threads.."
        #kill -9 `cat $CATALINA_HOME/work/`
        echo "Usage: $0 {start|stop|restart}"

exit 0
  1. Save the file (case you forgot "esc + x) :-)
  2. Add the tomcat startup script to the chkconfig with:
chkconfig --add tomcat
  1. Then activate it for your run level. Since I am not running any X Server on my server I only want to run it on level 345. Do it with:
chkconfig --level 345 tomcat on
  1. You can check if Tomcat will startup on reboot with listing the startup scripts with:
chkconfig --list
You should see a;
tomcat         	0:off	1:off	2:on	3:on	4:on	5:on	6:off
  1. If you have done all well, you should now be able to bounce Tomcat with this script as well. Try it with:
/etc/init.d/tomcat restart

Thursday, October 06, 2011

Speeding up mysql restoration of data

Mysql restoration too slow? Try the following steps:

1. Open the file my.ini inside the MySQL installation directory and do the following:

(a) Search for innodb_buffer_pool_size and set it to approx 20% of your RAM. I set it to 500M.

(b) Search for innodb_flush_log_at_trx_commit and change it from 1 to 2:

(c) Search for key_buffer_size and set it to approx 20% of your physical RAM.

(d) In your data.sql file you are trying to restore, if it is an innodb tables, try to modify it and add the lines:
SET FOREIGN_KEY_CHECKS=0 // At the beginning

SET FOREIGN_KEY_CHECKS=1 // At the end of the file

Now restart MySQL service.

Start restoring data. It will be approximately a magnitude of 50 times faster.

The Robot Two Leg Problem in Guice DI

Sunday, October 02, 2011

Maven, configuring an http proxy

Go to your user directory (ie. /home/babbas or /c/Users/babbas) then goto ".m2" directory and create a file named settings.xml. Inside that file copy the contents below:

<?xml version="1.0"?>
<settings xmlns="" xmlns:xsi="" xsi:schemaLocation="">

Installing GIT on Linux Redhat or CentOS 5

First is first:

rpm -Uvh epel-release-5-4.noarch.rpm
yum install git

Next steps, configure git configuraiton:

git config --global "Basil Abbas"
git config --global ""
git config --global color.ui auto

Creating a bare repository on a remote server:

mkdir project_directory
cd project_directory
git init --bare

Cloning the bare remote repository on a development machine:

cd /home/babbas
git clone ssh://hostname/path/to/project_directory

Saturday, October 01, 2011

VIM ignoring case search

Just type:
:set ignorecase

and to return back to normal:
:set noignorecase

If you would like to search case insensitive one time only without changing the mode in vim, for example lets search for the word "earth" case insensitively:


The \c character tells vim that the search should be case insensitive.

Friday, September 30, 2011

Web Session Management White Paper

PDF Link:

Developing an application with secure session management requires developers to understand a few crucial subtleties of cookies — their attributes, their values, and how to keep them confidential — and to understand how real-world attackers are abusing weak session management in real applications today.

Thursday, September 29, 2011

Making VIM on windows behave like linux

The following:

1. Open the file _vimrc which you will find inside c:\Program files\vim

2. Find the line that says:

behave mswin

3. Change it to

behave xterm

4. Save and exit.

This will now allow you to select text by typing the 'vi' then using the arrows to select text.

Deleting all lines that are empty or contain spaces in vim

To delete all lines that are empty in vim:


To delete all empty lines or empty lines that contain spaces:


Note that \s represents the space character in the regular expression. Or simply, you can also represent the space character with [ ]:

:g/^[ ]*$/d

Pasting code into VIM without the indentation problem

Frequently, when pasting code into vim, i get lots of indentation spaces that really frustrate me.
I discovered that this vim issue can easily be handled by typing in the command mode in vim:

:set paste

Then going to insert mode and pasting the source code.

Disable Autoindent in VIM

To disable autoindent in vim, you can do the following:

:set noautoindent | set nosmartindent | set nocindent

Or place the folowing lines in your .vimrc (linux) or _vimrc (windows):

set noautoindent
set nosmartindent
set nocindent

Sunday, September 25, 2011

Git Cheat Sheets

Goodbye Adobe Photoshop, Goodbye Paint.NET, Good Bye Greedy Pricing Schemes

I lately found this wonderful image processing application named PhotoPlus Starter Edition and I'm now no longer using either Adobe Photoshop nor Paint.NET.


The best "git log" command to use

This is the best git log command to use:
git log --decorate --graph --oneline

You can alias this command as follows:
git config --global "log --graph --decorate --oneline"

Now you can use it as follows:
git lol

Making two branches identical after a git merge

I had two branches, heavy_refactoring and master branch in git.
I have already merged heavy_refactoring into master, but I had some trouble since master looks different than heavy_refactoring at the end due to some changes that took place on master before the merge. These changes I dont want.

What I wanted is that the 'master' branch look exactly like heavy_refactoring.

So here are the steps:

1. Go to the master branch first.

git checkout master

2. First you do a git diff between the two branches:

git diff --summary master heavy_refactoring

This will shows us the differences that should take place for master to become heavy_refactoring. It is very important that you type 'master' before 'heavy_refactoring' to advise the git diffing to give the differences so that I can get from master to heavy_refactoring.

The --summary is a switch to tell the diff not to show the contents inside each file.

3. After running the command, a list of deleted, modified and created files show up.

4. If the diff tells you that I file is "deleted", this means it should be removed from the master branch using:

git rm file_to_remove

5. If the diff tells you that I file is "created", this means you have to copy it from the heavy_refactoring branch to the master branch using:

# Copying a file from another branch to the current branch
git checkout heavy_refactoring src/main/java/com/basil/

6. If the diff tells you that I file got "modified", this means you also have to copy it from heavy_refactoring branch to the master branch. Notice that my objective here is to make master exactly like heavy_refactoring.

git checkout heavy_refactoring srcmain/java/com/basil/

At the end, I can run the git diff again and it will show me an empty result which will indicate that the two branches are exact:

git diff --summary master heavy_refactoring

Monday, September 19, 2011

Enabling SSL in Apache Tomcat 6 The Easy Way

NOTE: This article does not use the APR tomcat module but rather the default Tomcat 6 deployment.

To enable SSL for Apache Tomcat 6, perform the following:

1. Create an SSL certificate using the java supplied keytool:

$JAVA_HOME/bin/keytool -genkey -alias tomcat -keyalg RSA

NOTE: If you get the error:
keytool error: java.lang.Exception: Key pair not generated, alias <tomcat> already exists
Then most probably you have a key file already in your user directory. If you are root, this will be /root/.keystore

2. You will be requested for data that will show on your user browser's certificate, fill them all in.
Notice that the bold font is my input. No problem if you stick to the password "changeit" as it is the default password used by tomcat.

Enter keystore password: changeit
Re-enter new password: changeit
What is your first and last name: Jeremy Atkins
What is your organizational unit: OU
What is the name of your organization: NOYO
What is the name of your city or your locality: MyCity
What is the name of your state or province: Saudi Arabia
What is the two-letter country code for this unit:  uk
Is the entered data correct: yes

Enter key password for <tomcat>
        (RETURN if same as keystore password): PRESS RETURN KEY

It is important to have the keystore password and the key password the same. This is done by pressing the RETURN KEY in the last step. This is necessary since Tomcat doesn't support having different passwords in the keystore and key.

3. When you're done with the previous step, a keystore file gets created in the user directory named keystore. Since I'm the root user, I will find it in /root/.keystore.
Check that the file /root/.keystore got created.

4. Next, open the tomcat server.xml for editing:
vi ${tomcat_installation_dir}/conf/server.xml

And uncomment the following section by removing the <!-- and the --> surrounding them from top and bottom:

   <Connector port="8443" protocol="HTTP/1.1" SSLEnabled="true"
               maxThreads="150" scheme="https" secure="true"
               clientAuth="false" sslProtocol="TLS"

5. Change the port number from 8443 to 443 which is the default SSL port known to all browsers.
Switch to 8443 while in development if needed.

   <Connector port="443" protocol="HTTP/1.1" SSLEnabled="true"
               maxThreads="150" scheme="https" secure="true"
               clientAuth="false" sslProtocol="TLS"

6. Now add the following line in between to tell tomcat where to locate the keystore and specify the password you specified:

<Connector port="8443" protocol="HTTP/1.1" SSLEnabled="true"
   maxThreads="150" scheme="https" secure="true"
   clientAuth="false" sslProtocol="TLS"
   keystoreFile="${user.home}/.keystore" keystorePass="changeit"

Tomcat will automatically replace ${user.home} with the path of the home directory for the user tomcat is running under. Which in my case is "/root"

7. Restart apache tomcat using:
<tomcat_installation_dir>/bin/ stop
<tomcat_installation_dir>/bin/ start

Disabling WebDAV DELETE, PUT, OPTIONS in Apache Tomcat 6

It really took me more than two hours searching over the internet just to understand how to do this simple configuration of disabled the WebDAV methods in apache tomcat 6 for all applications.

Here is how to do it:

In your apache tomcat 6 installation, simply open the file <installation_directory>/conf/web.xml for editing. Note that this web.xml file acts as a global file for all web applications and is processed before the web.xml's web application file.

At the end of the global web.xml file and just before the closing tag place the following text:

<web-resource-name>restricted methods</web-resource-name>
<auth-constraint />

The above security-constraint simply denies the above WebDAV methods to be processed by tomcat and returns a forbidden message.

The <auth-constraint /> simply means: "For any user, deny access to PUT, DELETE, OPTIONS, and TRACE methods".

After that, restart apache tomcat 6 using:

<installation_directory>/bin/ stop
<installation_directory>/bin/ start

To be able to verify that these methods are now forbidden, I used some javascript jquery code:
1. Open firefox with the firebug plugin installed
2. Open a webapplication that has jquery javascript file included within it.
3. Open firebug and select the "Console" tab from firebug
4. Write the following javascript code:

  type: 'DELETE',
  url: "",
  data: {},
  error: function() {alert('ERROR');},
  success: function() {alert('SUCCESS');},

5. Click the Run button.
6. You should see an alert dialog with the message ERROR and a response in firebug with the following message:
"NetworkError: 403 Forbidden -"

7. Repeat the above for the OPTIONS, TRACE and PUT methods.

I'm sure there's a simpler way to verify it other than javascript. But I don't know how.