September 30, 2016

My bashrc file (for reference)



# reload other bash script file, if any
source /usr/share/defaults/etc/profile

# set PATH
export PATH=$PATH:/usr/sbin:/usr/local/mysql/bin:.:/home/raf/Tools/gwt-2.7.0:/home/raf/Tools/apache-log4j-2.6.2-bin

# other environment variables
PROJECT_HOME=/home/raf/Workspace/trunk-umobile-work
export PROJECT_HOME

ANT_HOME=/opt/apache-ant-1.9.7
export ANT_HOME

GWT_23_HOME=/home/raf/Tools/gwt-2.3.0/gwt-2.3.0
GWT_27_HOME=/home/raf/Tools/gwt-2.7.0
GWT_HOME=${GWT_23_HOME}
export GWT_HOME

APACHE_HOME=/usr/local/apache/htdocs
export APACHE_HOME

MSYQL_HOME=/usr/local/mysql
export MYSQL_HOME

AXIS2_HOME=/home/raf/Tools/axis2-1.5.4
export AXIS2_HOME

JUNIT=/home/raf/Tools/eclipse/plugins/org.junit_4.12.0.v201504281640/junit.jar
export JUNIT

JAVA_7_HOME=/opt/jdk1.7.0_80
JAVA_8_HOME=/usr/lib/jvm/java-8-openjdk-
JAVA_HOME=${JAVA_7_HOME}
export JAVA_HOME JAVA_7_HOME JAVA_8_HOME

# to switch between java7 and java8
alias java7="sudo rm /usr/bin/java; sudo rm /usr/bin/javac; sudo ln -s /opt/jdk1.7.0_80/bin/java /usr/bin/java; sudo ln -s /opt/jdk1.7.0_80/bin/javac /usr/bin/javac; export JAVA_HOME=${JAVA_7_HOME}"
alias java8="sudo rm /usr/bin/java; sudo rm /usr/bin/javac; sudo ln -s /usr/lib/openjdk-8/bin/java /usr/bin/java; sudo ln -s /usr/lib/openjdk-8/bin/javac /usr/bin/javac; export JAVA_HOME=${JAVA_8_HOME}"

TOMCAT_WEBAPPS=/home/raf/Tools/apache-tomcat-8.5.4/webapps
export TOMCAT_WEBAPPS

EDITOR=/opt/sublime_text/sublime_text
export EDITOR

# bash setting
export HISTFILESIZE=3000    # the bash history should save 3000 commands
export HISTCONTROL=ignoredups   #don't put duplicate lines in the history.

# define colours
BLACK='\e[0;30m'
BLUE='\e[0;34m'
GREEN='\e[0;32m'
CYAN='\e[0;36m'
RED='\e[0;31m'
PURPLE='\e[0;35m'
BROWN='\e[0;33m'
LIGHTGRAY='\e[0;37m'
DARKGRAY='\e[1;30m'
LIGHTBLUE='\e[1;34m'
LIGHTGREEN='\e[1;32m'
LIGHTCYAN='\e[1;36m'
LIGHTRED='\e[1;31m'
LIGHTPURPLE='\e[1;35m'
YELLOW='\e[1;33m'
WHITE='\e[1;37m'
NC='\e[0m'

# check PID of current running process. Usage : ps java
alias ps="ps -awwef | grep "

# frequently used directories for bookmarking purposes
alias cdt="cd /home/raf/Tools/apache-tomcat-8.5.4/webapps"
alias cdw="cd /home/raf/Workspace/"
alias cdwu="cd /home/raf/Workspace/trunk-umobile-work"
alias cdp="cd ~/Workspace/cpx/source/merchant_portal"

# short forms command for other most used software
alias apache-up="sudo /usr/local/apache2/bin/apachectl restart; tail -f /usr/local/apache2/logs/error_log;"
alias tomcat-up="~/Tools/apache-tomcat-8.5.4/bin/catalina.sh start;"
alias tomcat-log="tail -f /home/raf/Tools/apache-tomcat-8.5.4/logs/catalina.out;"
alias tomcat-clearlog="rm /home/raf/Tools/apache-tomcat-8.5.4/logs/catalina.out; touch /home/raf/Tools/apache-tomcat-8.5.4/logs/catalina.out;"
alias tomcat-clear="rm -rfv /home/raf/Tools/apache-tomcat-8.5.4/work/Catalina/"
alias sub="/opt/sublime_text/sublime_text"
alias nau="nautilus "
alias fire="cd /home/raf/Tools/firefox-24; setsid ./firefox"

# short forms command for favourite linux tools
alias ..="cd .."
alias ...="cd ..."
alias ls="ls -lsaXB"    # sort by extension
alias ls_size='ls -lSar' # sort by size
alias cls="clear"
alias cl="clear"
alias sls="clear"
alias s;s="clear"
alias s:="clear"
alias ;s="clear"
alias hist='history | grep $1'  # check previously executed command. Usage : hist tomcat*
alias sc='source '
alias find_pattern="grep -rnwl . -e "   # find file that contain pattern. Usage : find mytext
alias find="find "  # let it be here. Needed to fix bug betwen find_pattern and find_file
alias find_file="find -name "   # find file by file name. Usage : find_file mytext.txt

# listing files within directory
alias structure="tree -P '*.jar|*.java|*.xml|*.html|*.css' | less "
alias structure-nojar="tree -P '*.java|*.xml|*.html|*.css' | less "
alias structure-nojava="tree -P '*.xml|*.html|*.css' | less "

# command line pre-fix
export PS1="pwd : ${LIGHTGREEN} \w\n${BLUE}\u${RED}:$ ${BLUE}"

# show network info
netinfo ()
{
    echo "--------------- Network Information ---------------"
    /usr/bin/ifconfig | awk /'inet addr/ {print $2}'
    /usr/bin/ifconfig | awk /'Bcast/ {print $3}'
    /usr/bin/ifconfig | awk /'inet addr/ {print $4}'
    /usr/bin/ifconfig | awk /'HWaddr/ {print $4,$5}'
    echo "---------------------------------------------------"
}

# enable programmable completion features
if [ -f /etc/bash_completion ]; then
    . /etc/bash_completion
fi

# extract things . Usage : extract file.zip
extract () {
     if [ -f $1 ] ; then
         case $1 in
             *.tar.bz2)   tar xjf $1        ;;
             *.tar.gz)    tar xzf $1     ;;
             *.bz2)       bunzip2 $1       ;;
             *.rar)       rar x $1     ;;
             *.gz)        gunzip $1     ;;
             *.tar)       tar xf $1        ;;
             *.tbz2)      tar xjf $1      ;;
             *.tgz)       tar xzf $1       ;;
             *.zip)       unzip $1     ;;
             *.Z)         uncompress $1  ;;
             *.7z)        7z x $1    ;;
             *)           echo "'$1' cannot be extracted via extract()" ;;
         esac
     else
         echo "'$1' is not a valid file"
     fi
}

# WELCOME SCREEN
################################################## #####

clear

echo -ne "${PURPLE}";cal;
. /etc/lsb-release
echo -ne "${BROWN}Linux Kernel : $gras$(uname -r)$fin \n"      
echo -ne "Distro       : $DISTRIB_ID $DISTRIB_RELEASE ($DISTRIB_CODENAME)$fin \n${BLACK}"

September 26, 2016

Markdown for blogger

Well, it seems like I have to get familiar with markdown since my company's WIKI is written using it.

Here's one useful tool : StackEdit

I would like to re-write all posts from this blog by using markdown. Still waiting for official support from Blogger but it does not seem it's going to happen real soon.

Any ideas?

September 23, 2016

Posting code snippet to blogspot post (no syntax highlighting)

Encode your code using an online HTML Encoder and then put it inside pre
<pre>
    <%--your encoded code goes here--%>
</pre>
HTML Encoder

Logging with GWT

1. First, modify our module configuration file (X.gwt.xml) where X is the class which holds the EntryPoint of your application.

<inherits name="com.google.gwt.logging.Logging" />
<set-property name="gwt.logging.logLevel" value="INFO"/>
<set-property name="gwt.logging.enabled" value="TRUE"/>
<set-property name="gwt.logging.consoleHandler" value="ENABLED"/>
<set-property name="gwt.logging.popupHandler" value="DISABLED" /><!-- Disable PopupLogHandler -->
<set-property name="gwt.logging.simpleRemoteHandler" value="DISABLED" />


2. This configuration cause logs to be printed to standard output, that is usually Eclipse console window. You can also view this logs in Javascript console, which present in Chrome, Firefox and IE.

See here on how to view them in Javascript console : http://webmasters.stackexchange.com/questions/8525/how-to-open-the-javascript-console-in-different-browsers


3. In your class, import the library.

import java.util.logging.Logger;
import java.util.logging.Level;


4. Then, instantiate the logger with whatever name, possibly with the class name to make it more descriptive.

public Logger logger = Logger.getLogger("MyClassLogger");


5. Then it can be used anywhere within it's scope. Examples :

logger.log(Level.SEVERE, "Connection refused: ");
logger.log(Level.INFO, "Query executed : " + executedQuery);


6. The log levels define the severity of a message. The Level class is used to define which messages should be written to the log. You can set the minimum level by the following :

logger.setLevel(Level.INFO); 


7. These are the typical usage of these levels :

ERROR: Any error/exception that is or might be critical.

WARN: Any message that might warn us of potential problems, e.g. when a user tried to log in with wrong credentials - which might indicate an attack if that happens often or in short periods of time

INFO: Anything that we want to know when looking at the log files, e.g. when a scheduled job started/ended.

September 21, 2016

Increment a day in Java or get previous date

1. Using java.util.Calendar in typical Java application

SimpleDateFormat dateFormat = new SimpleDateFormat( "yyyy-MM-dd" );
Calendar cal = Calendar.getInstance();
cal.setTime( dateFormat.parse( inputString ) );
cal.add( Calendar.DATE, 1 );

2. Using java.util.Date - this does't take care Daylight saving but might be required for certain use cases and especially in GWT where Calendar is not supported.

Date date = new Date(); 
Date daysAgo = new Date(date.getTime() - (1000*60*60*24)); 

3. Using 3rd party library. For example, http://joda-time.sourceforge.net

Date date = new Date(); // Or where ever you get it from
Date daysAgo = new DateTime(date).minusDays(300).toDate();

Creating a new Github repository and link it to the local existing project in your computer

1. Create a new repository on GitHub

2. Get the remote repository Web URL by pressing the "Clone or Download" button (coloured green). It looks like this : https://github.com/iserifith/ScoreBoard.git

3. Open Terminal and go to your local project folder where you have the files you have been working on.

4. Initialize the local project folder as a Git repository using the following command :
git init

5. Add the files in the project folder into "local git repository" - this is called "staging".
git add .

Note : This does not connect to "remote git repository". Understand the difference between local and remote git repository.

6. Commit the files that you've staged in your local repository.
git commit -m "First commit"

7. Now we set so that our local repository are linked to the remote repository. This command set the remote repository as the "origin".
git remote add origin {remote repository Web URL}

Example : git remote add origin https://github.com/iserifith/ScoreBoard.git

8. Verify that our remote repository are linked properly using
git remote -v

It will prompt you something like this :
origin https://github.com/iserifith/ScoreBoard.git (fetch)
origin https://github.com/iserifith/ScoreBoard.git (push)

9. Once all set, push the all files (that we have committed just now) in your local repository to GitHub using the following command :
git push origin master



Extra :
Now, to make sure you keep updated Github with your work, all you need to are 3 steps :

1. Add all files (staging)
git add .

2. Commit
git commit -m "I did some changes"

3. Push to Github (remote repository)
git push origin master

September 20, 2016

Using EOPKG via proxy

Edit file /etc/eopkg/eopkg.conf

Add the following line

http_proxy = http://yourproxysite
https_proxy = http://yourproxysite

September 14, 2016

Git diff using meld, a graphical file comparator

1. First, install meld (or from source : http://meldmerge.org)
sudo apt-get install meld

2. Then, create a directory named script in home folder
cd ~; mkdir script; cd script;

3. Create a file and name it git_meld.py
touch git_meld.py

4. Insert the following codes :

#!/usr/bin/python

import sys
import os

os.system('meld "%s" "%s"' % (sys.argv[2], sys.argv[5]))

5. Save the file.

6. Then, set git to use this script as part of 'diff' command
git config --global diff.external /home/script/git_meld.py

That's it, we're done. Use git diff as the following

// compares working directory with index
// i.e. shows the changes that are not staged yet.
git diff

// compares working directory with local repository.
// shows the list of changes after your last commit.
git diff HEAD

// compares index with local repository.
// shows the diff between your last commit and changes to be committed next (already staged, but not yet commited)
git diff --cached
Full manual available :
https://www.kernel.org/pub/software/scm/git/docs/git-diff.html

If you want to compare between 2 commits, use
git log and then copy the commit ID of the 2 commits you want to compare
i.e.
commit 8c9dcaa5424a67ddf20cd453bcb6db4c5b04edbf --- copy this
Author: Raf
Date:   Sat Sep 3 17:49:19 2016 +0800

And then, run the following
git diff [commitA] [commitB]




Install terminator, a nice terminal application for Linux

Use terminator if you use terminal alot
- multi tabs
- multi panels
- fast

More info : http://gnometerminator.blogspot.my/p/introduction.html

1. To install, download tar ball from here
http://launchpad.net/terminator/trunk/0.97/+download/terminator-0.97.tar.gz

2. Copy to somewhere you usually install your application
sudo cp -r terminator-0.97 /usr/local/

3. Create a symlink to our application in /usr/bin
This enable you to run it from terminal
ln -s /usr/local/terminator-0.97/terminator /usr/bin/terminator

4. Now you can run terminator from command line.
To run it without the need of the console, run
setsid terminator

September 12, 2016

Compiling and run java program in command line

1. If your code is not in any package, then running the following command will compile and execute your java program just fine

javac TheClassName.java
java TheClassName


 2. However, if the class is in a package such as below :

package thepackagename;

public class TheClassName {
    public static final void main(String[] args) {
        System.out.println("Hello World!");
    }
}

Then calling the same command will give you the following results (or similar) :

Error: Could not find or load main class TheClassName.

This is because, to run your code, it needs to be called with its fully-qualified name (include packagename in it's name) and also note that this command must be called from the directory in which the thepackagename directory exists, not where your class TheClassName is placed (not inside the thepackagename folder itself - must be one level above)

cd {path-to-one-level-above-thepackagename}
javac thepackagename/TheClassName.java
java thepackagename.TheClassName

September 11, 2016

Java basic compilation and execution


  1. Your Java File (source code)
    MyGame.java
  2. Compile the Java File to a *.class file. This is Java bytecode that can be executed on the Java Virtual Machine (JVM). JVM is installed automatically when we install Java and it will be invoked automatically when we run a java program.

    Note : In Eclipse, "run" perform both compilation and execution.
    javac MyGame.java
    • This will create a MyGame.class file 
  3. Execution of the Java File
    java MyGame
  4. Creation of an executable *.jar file. A jar file is simply a file containing a collection of java files.

    First, create a manifest file : touch manifest.mf

    In the manifest file, point Main-Class to our java file that has main entry point i.e. main() method. For example,
    Manifest-Version: 1.0
    Main-Class: MyGame
    Make sure the compiled output class files (myGame.class) and the manifest file are in the same folder.

    Create the .jar file by the following :

    jar cfm MyGame.jar manifest.mf *.class
  5. To run the Jar File
    java -jar MyGame.jar

September 8, 2016

Creating a dump file of a MySQL database for developement in other machine

Create the dump file using the following :

mysqldump --user=username --password --databases MY_DATABASE --single-transaction --add-drop-table --no-tablespaces --skip-disable-keys > dump_sit.sql

Add -h remote-server-address if you're creating from remote database server.

Afterwards, edit the dump file and put these lines at the beginning:

SET AUTOCOMMIT = 0; SET FOREIGN_KEY_CHECKS=0; And put these lines at the end: SET FOREIGN_KEY_CHECKS = 1; COMMIT; SET AUTOCOMMIT = 1;

For example, using sed on Linux to insert at the beginning of the file:
sed -i '1s/^/SET AUTOCOMMIT = 0; SET FOREIGN_KEY_CHECKS=0;\n/' dump_sit.sql

Appending at the end of the file :
echo "SET FOREIGN_KEY_CHECKS = 1; COMMIT; SET AUTOCOMMIT = 1;" >> dump_sit.sql

To understand what these options means, go to :
http://dev.mysql.com/doc/refman/5.7/en/mysqldump.html#option_mysqldump_compatible

September 5, 2016

Git through proxy

I have to go through proxy at work. Time from time, I took a break and work on my personal projects which are hosted on github and thus, git on my computer needs to be configured for it.

On the terminal, run this :

HTTP_PROXY=http://proxy.site.my:80
git config --global http.proxy $HTTP_PROXY
Back at home, I need to set it back to having no proxy

git config --global --unset http.proxy
Yeah, tedious.