Pages

Thursday, December 27, 2012

mvn jetty:run port

To start the jetty server in a different port than 8080 we can use this command.

mvn -Djetty.port=9999 jetty:run

Thursday, December 20, 2012

MySQL and Epoch Time

While working on MySQL, I found some useful functions to work with epoch time. They are well documented in the MySQL reference manual. Here is a list of few that I have used for my piece of work.
  • UNIX_TIMESTAMP() : Return a UNIX timestamp i.e. current time in epoch. See some examples below.
mysql> SELECT UNIX_TIMESTAMP() as cuurent_epoch_time;
       ->1355992290
  • UNIX_TIMESTAMP(DATE: Return a UNIX timestamp i.e. current time in epoch. See some examples below.
mysql> SELECT UNIX_TIMESTAMP(NOW()) as cuurent_epoch_time;
       ->1355993021
mysql> SELECT UNIX_TIMESTAMP('2012-12-20 10:30:19');
       ->1355979619
  • FROM_UNIXTIME(UNIX_TIMESTAMP: Format UNIX timestamp as a date. See some examples below.
mysql> SELECT FROM_UNIXTIME(1355993021);
       ->2012-12-20 14:13:41
mysql> SELECT FROM_UNIXTIME(UNIX_TIMESTAMP());
       ->2012-12-20 14:22:19
  • FROM_UNIXTIME(UNIX_TIMESTAMP , format: Format UNIX timestamp as per the format specified. See some examples below.
mysql> SELECT FROM_UNIXTIME(1355993021, "%Y");
       ->2012
mysql> SELECT FROM_UNIXTIME(UNIX_TIMESTAMP(), "%M");
       ->December
mysql> SELECT FROM_UNIXTIME(UNIX_TIMESTAMP(),'%Y %D %M %h:%i:%s %x');
       ->2012 20th December 02:35:53 2012

Wednesday, December 19, 2012

Current epoch time

Perl                    time
PHP                     time()
Java                  long epoch = System.currentTimeMillis()/1000;
MySQL                 SELECT unix_timestamp(now())
Oracle PL/SQL         SELECT (SYSDATE - TO_DATE('01-01-1970 00:00:00','DD-MM-YYY HH24:MI:SS')) * 24 * 60 * 60 FROM DUAL
JavaScript           Math.round(new Date().getTime()/1000.0) getTime() returns time in milliseconds.
Unix/Linux Shell     date +%s

Tuesday, December 18, 2012

Character count problem

You have a string of small letters a-e, which can be represented as a regular expression in the form of [a-e]*

Example: abcdef, eafdceeafe, etc etc

Problem: Write a program that counts maximum continuous occurrence of a character and their indexes. For example, if the string is "abbbbdcdef", it will be "b" : 4, starting at index 1 to 4.

public class TestStringCharCount {

   public static void main(String[] args) {

        int start = 0;
        int count = 0;
        int maxCount = 0;
        char maxChar = 'a';
        String str = "abcdefabbbbbbbbcdaeff";
        char[] chars = str.toCharArray();

        for (int i = 0; i < chars.length; i++) {
            count = 0;
            for (int j = i; j < chars.length; j++) {

                if (chars[i] == chars[j]) {
                    count++;
                } else {
                    break;
                }
                i = j;
            }

            if (count > maxCount) {
                maxCount = count;
                maxChar = chars[i];
                start = i;
            }

        }
        System.out.println("string = "+ str + ", length = "+ str.length());
        
        System.out.println(maxChar + ":" + maxCount + " starting at "
                + (start - maxCount) + " to " + start);
    }
}

Output: 
string = abcdefabbbbbbbbcdaeff, length = 21
b:8 starting at 6 to 14

Friday, December 14, 2012

Get current time in perl

#!/usr/bin/perl -w

print "current time in epoch is : ". time(). "\n";
print "current time is : ". localtime(time()). "\n";

my ($sec,$min,$hour,$day,$month,$yr19,@rest) =   localtime(time);

print "----------------------------------------\n";
print "Sec : ". $sec . "\n";
print "Min : ". $min . "\n";
print "Hour : ". $hour . "\n";
print "Day : ". $day . "\n";
print "Month : ". $month . "\n";
print "Year : ". $yr19 . "\n";
Output
current time in epoch is : 1355483046
current time is : Fri Dec 14 16:34:06 2012
-------------------------------------------
Sec : 6
Min : 34
Hour : 16
Day : 14
Month : 11
Year : 112

Monday, November 19, 2012

Hello World! Perl Example

My first PERL program. Create a new file

vi hello_world.pl

#!/usr/bin/perl -w
#
#
print "Hello World!\n";

exit;


Execute the above script with the command below.

perl hello_world.pl

Saturday, November 17, 2012

MySQL Performance Tuning



SHOW VARIABLES LIKE 'have_query_cache';
SHOW VARIABLES LIKE 'query_cache_size';
SET GLOBAL query_cache_size = 256000000;

Gradle jettyRun debug

To start gradle jettyRun in debug mode, follow the steps below.

Set the GRADLE_OPTS as shown in the screen

$ export GRADLE_OPTS="-Xdebug -Xrunjdwp:transport=dt_socket,address=9999,server=y,suspend=n"
$ gradle jettyRun

Start the jetty server

Jetty server started

Open the debug configuration settings in Eclipse
Click on the debug button to start debugger

Set the breakpoints
Call the methods and debug


Set the debug points in your code and open the URL

http://localhost:9999/komliprime-trafficking-service/api/strategi?authtoken=6991a70eb121f3f623ebc2567927fef5


Truncating log files in UNIX/Linux

Most of the time we need log files to be truncated for many reasons. We can use the below command to truncate the file contents.


sudo cp /dev/null trafficking.log

Friday, August 3, 2012

Mounting exFAT in Ubuntu

Recently, I was trying to access NTFS based partitions in Mac OSX Snow Leopard, which always shows them as "read only" partitions. I got to understand that OSX by default only supports NTFS read only. I have had an option of using FAT with OSX and that too have its own limitation, one I know is the max file size less than 4gb.

So, I decided to partition my drive as exFAT, which is supported in both Windows and Mac. But when I tried accessing the same from my Ubuntu machine, it failed. So here is what I did to fix the problem in Ubuntu.
sudo su -
add-apt-repository ppa:relan/exfat
apt-get update
apt-get install fuse-exfat
With the above setting you will be able to manually mount the drives. In order to make this process automated this is what  I followed.
apt-get install build-essential
apt-get install ncurses-dev
apt-get install util-linux

With this it worked in all the operating systems I work on. 

Tuesday, July 3, 2012

Function in JavaScript


Passing functions to another function
    function invoke_and_add(a,b){
        return a() + b();
    }

    function one(){
        return 1;
    }

    function two(){
        return 2;
    }

    invoke_and_add(one,two);

Callback function
    function multiplyByTwo(a,b,c, callback){
        var i, array = [];
        for(i=0;i<3; i++){
        array[i] = callback(arguments[i] * 2);
        }
        return array;
    }

    function addOne(a){
        return a+1;
    }

    myarr = multiplyByTwo(1,2,3,addOne);

Self-invoking function
    (
        function(){
            alert('this is a self invoking function');
        }
    )()

Inner (Private) function
    function a(param){
        function b(input){
        return input * 2;
        };
        
        return 'the result is ' + b(param);
    };

    a(2);

Functions that return function
    function a(){
        alert('a');
        return function(){
        alert('b');
        };
    }

    var newFn = a();
    newFn();

    // also the above 2 lines can be replaced with this one liner

    a()();


Function rewriting itself
    function a(){
        alert('a');
        a = function(){
        alert('b');
        };
    }

    a();
    a();

JavaScript Quiz

Here are some of the questions that I found in a book titled "Object-Oriented JavaScript" by Stoyan Stefanov.


    var a; typeof a;
    var s = 'ls'; s++;
    !!false;
    !!undefined;
    typeof -Infinity;
    10 % "0";
    undefined == null;
    false  === "";
    typeof "2E+2";
    a = 3e+3; a++;
    var v = v || 10;
    typeof NaN;

Wednesday, June 27, 2012

Check / Un-check ExtJS Grid header check box

Problem Statement: I have an ExtJS Grid with check boxes a shown in the figure below. The header check box toggles the selections of all the records in the grid. But many times I want to manually check and un-check the header check box and also I need a way to identify whether it's already checked or not.


Problem Solution: Here is a way out to find whether the header check box is selected or not.
/*
 * This function tells whether grid header checkbox is checked or not
 * 
 */
function isHeaderchecked(gridId){
    var view   = Ext.getCmp(gridId).getView();
    var chkdiv = Ext.fly(view.innerHd).child(".x-grid3-hd-checker");
    if(chkdiv.getAttribute('class') === 'x-grid3-hd-inner x-grid3-hd-checker'){
        return false;
    }else{
        return true;
    }
}

The methods to check and uncheck the header check box are as below.
/*
 * This function checks grid's header checkbox
 * 
 */
function checkHeader(gridId){
    var view   = Ext.getCmp(gridId).getView();
    var chkdiv = Ext.fly(view.innerHd).child(".x-grid3-hd-checker")
    chkdiv.addClass('x-grid3-hd-checker-on');
}
/*
 * This function un-checks grid's header checkbox
 * 
 */
function uncheckHeader(gridId){
    var view   = Ext.getCmp(gridId).getView();
    var chkdiv = Ext.fly(view.innerHd).child(".x-grid3-hd-checker")
    chkdiv.removeClass('x-grid3-hd-checker-on');
}

Installing RPM's In CentOS

Problem Statement: I have a web application that runs on Tomcat server 7. I have created RPM for the same. How do I deploy the RPM and restart the web application and Tomcat 7.

Problem Solution:

wget "rpm location"
Example:  wget http://192.168.0.59:8080/mywebapp_01_may_2012.rpm

yum localinstall "rpm file name"

Example:  yum localinstall mywebapp_01_may_2012.rpm
service tomcat7 restart

Thursday, June 7, 2012

Default selection in ExtJS combo boxes

Problem Statement: I have a combo box and the options are populated from a data store. In my case the date store is local data store. Only thing that I want is to make some option selected by default.


This is what my code looks like.

var statusStore = new Ext.data.ArrayStore({
    id: 0,
    fields: [
        'status',
        'label'
    ],
    data: [
           ["", 'All'],
           [true, 'Active'], 
           [false, 'Inactive']
          
    ]
});

items: [{                        
    mode:'local',
    hideLabel:true,    
    xtype: 'combo',
    id: 'filterStatus',
    editable:false,
    typeAhead: true,
    triggerAction: 'all',
    forceSelection: true,
    store: statusStore,
    displayField: 'label',
    width: 110,
    ctCls: 'MB'
}]

Problem Solution: One of the solution lies around using listeners. After the combo box is rendered, make the default selection. The one that works for me is as given in the code below.


var statusStore = new Ext.data.ArrayStore({
    id: 0,
    fields: [
        'status',
        'label'
    ],
    data: [
           ["", 'All'],
           [true, 'Active'], 
           [false, 'Inactive']
          
    ]
});

items: [{                        
    mode:'local',
    hideLabel:true,    
    xtype: 'combo',
    id: 'filterStatus',
    editable:false,
    typeAhead: true,
    triggerAction: 'all',
    forceSelection: true,
    store: statusStore,
    displayField: 'label',
    width: 110,
    ctCls: 'MB',
    listeners:{
        afterrender:function(){
            this.setValue(true);
            this.setRawValue('All');
        }
    }
}]

What I have done here is added a listener i.e. afterrender to make the default selection. The code above is self explanatory.

Enable/Disable button in ExtJS 3.2.1

Problem Statement: How to enable disable buttons in ExtJS 3.2.1?

Problem Solution:  ExtJs button is basically instance of Ext.Button class. There are two ways we can enable/disable
  1. Using config option
  2. Programmatically enabling & disabling
USING CONFIG OPTIONS
In order to set any button enabled or disabled, config option disabled can be set as true or false.


Ext.Button({
    text: 'Edit',
    id: 'edit',
    cls: 'edit_class',
    diasabled: 'true', // button is disabled
    listeners: {
    'click': function () {}                
    }
})

Ext.Button({
    text: 'Edit',
    id: 'edit',
    cls: 'edit_class',
    diasabled: 'false', // button is enabled
    listeners: {
    'click': function () {}                
    }
})

PROGRAMMATICALLY
Ext.getCmp('edit').setDisabled(true);

Ext.getCmp('edit').setDisabled(false);

Read more : Ext JS 3.2.1 API DOCS (http://extjs.cachefly.net/ext-3.2.1/docs/)

Java program to find host name and IP address of local and remote machine

Problem Statement: Many times we need to find the host name and IP address of local and the remote machines. Most importantly I want to do this with a Java program.

Solution: Here is the main class, I have named it as HostNameFinder and to test these methods I've another class called as HostNameFinderTest.

/**
 * 
 * Classname : HostNameFinder.java
 * <b>HostNameFinder<b><br> 
 * <p>
 *     This class helps to get the host name and the IP addresses of the local machine and 
 *     remote machines. It provides static methods that can be used to get the very specific
 *     information such as host name or the IP address.
 * </p>
 * 
 * @author Manohar Negi
 * @version 1.0
 * @since 1.0
 * @see
 * Copyright notice
 *
 * Revision History: 
 *
 * Date            By              Version        Comments
 * ---------------------------------------------------------------------------------
 * Aug 31, 2011    Manohar Negi    1.0            Initial Draft
 * Sep 01, 2011    Manohar Negi    1.1            Modified to include more methods
 *
 **/

package com.mani.util;

import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * <p>
 * <b>Functional Description:</b>
 * <p>
 * Some Description of the file
 * 
 * Created: Month, Day ,YYYY
 * 
 * @author
 * @version
 */
public class HostNameFinder {

    public static String getMyHostName() {
        String hostname = null;
        try {
            InetAddress addr = InetAddress.getLocalHost();
            hostname = addr.getHostName();
            System.out.println("Host Name = " + hostname);

        } catch (UnknownHostException e) {
            e.printStackTrace();
        }

        return hostname;
    }

    public static String getMyIPAddress() {
        String ipAddress = null;
        try {
            InetAddress addr = InetAddress.getLocalHost();
            String ipAddr = addr.getHostAddress();
            System.out.println("IP Address = " + ipAddr.toString());

        } catch (UnknownHostException e) {
            e.printStackTrace();
        }

        return ipAddress;
    }

    public static String getIPByAddress(String address) {
        String ipAddress = null;
        try {
            InetAddress addr = InetAddress.getByName(address);
            String ipAddr = addr.getHostAddress();
            System.out.println("IP Address = " + ipAddr.toString());

        } catch (UnknownHostException e) {
            e.printStackTrace();
        }

        return ipAddress;
    }

    public static String getHostNameByAdress(String address) {
        String hostname = null;
        try {
            InetAddress addr = InetAddress.getByName(address);
            hostname = addr.getHostName();
            System.out.println("Host Name = " + hostname);

        } catch (UnknownHostException e) {
            e.printStackTrace();
        }

        return hostname;
    }

}


Here is the test class.

/**
 * 
 * Classname : HostNameFinderTest.java
 * <b>HostNameFinderTest<b><br> 
 * <p>
 *     This class is to test the methods of HostNameFinder.class
 * </p>
 * 
 * @author Manohar Negi
 * @version 1.0
 * @since 1.0
 * @see
 * Copyright notice
 *
 * Revision History: 
 *
 * Date            By              Version        Comments
 * ---------------------------------------------------------------------------------
 * Aug 31, 2011    Manohar Negi    1.0            Initial Draft
 * Sep 01, 2011    Manohar Negi    1.1            Modified to include more methods
 *
 **/
package com.mani.util;

public class HotmNameFinderTest {

    public static void main(String[] args) {

        /* get the host name for local machine */
        HostNameFinder.getMyHostName();

        /* get the IP for local machine */
        HostNameFinder.getMyIPAddress();

        /* get the host name for localhost */
        HostNameFinder.getHostNameByAdress("localhost");

        /* get the IP for localhost */
        HostNameFinder.getIPByAddress("localhost");

        /* get the host name for www.google.com */
        HostNameFinder.getHostNameByAdress("www.google.com");

        /* get the IP for www.google.com */
        HostNameFinder.getIPByAddress("www.google.com");

    }

}


And here is the output that I got.

Host Name = mani-mac
IP Address = 192.168.2.4
Host Name = localhost
IP Address = 127.0.0.1
Host Name = www.google.com
IP Address = 74.125.236.83

Friday, May 18, 2012

Transaction management in Hibernate

A transaction is an atomic unit of work. There are only two outcomes, either success or failure. In hibernate one way to manage transactions is as given below.

Session session = null;
Transaction tx = null;
try {
    session = sessionFactory.openSession();
    tx = session.beginTransaction();
    //perform the transactions here
    // some more transactions
    tx.commit();
} catch (RuntimeException ex) {
    tx.rollback();

} finally {
    session.close();
}

Handling window close or hide event in ExtJS 3.2.1

In case you need to do something specific on window close or hide. Here is a way to do so.

var myPopUpWindow = new Ext.Window({
    layout : 'hbox',
    layoutConfig : {
        align : 'stretch',
        pack : 'start',
    },
    width : popUpWindowWidth,
    height : popUpWindowHeight,
    modal : true,
    resizable : true,
    closable : true,
    draggable : true,
    animate : true,
    id : myPopUpWindow,
    shadow : true,
    closeAction : 'hide',
    hideMode : 'visibility',
    title : 'Selection Box Example',
    items : [ my_popUp_grid, my_selections_grid ],
    bbar : new Ext.Toolbar({
        items : [ {
            xtype : 'tbbutton',
            text : 'Cancel',
            handler : function() {
                myPopUpWindow.hide();
            }
        }, {
            xtype : 'tbfill'
        }, {
            xtype : 'tbbutton',
            text : 'Save',
            handler : function() {
                saveData();
                myPopUpWindow.hide();
            }
        } ]
    }),
    listeners:{
         'close':function(win){
                  console.info('bye');
                  saveData();
          },
         'hide':function(win){
                  console.info('just hidden');
                  saveData();
          }
 }
});

In the example above, I'm calling saveDate() on window close and hide.

Thursday, May 3, 2012

Handling exceptions in ExtJS

Problem Statement: I struggled almost for a week to fix exception handling in ExtJS. The problem is when I make an AJAX call or make any asynchronous server side call, I was not able to read exact exception message thrown by server. I saw different ways to implement exception listeners in ExtJS but most of them didn't work for me.

Problem Solution: This is what I am using to handle exceptions in ExtJS.

var reportProxy = new Ext.data.HttpProxy({
    url : 'myReportURL',  // web URL
    method : 'post',      // HTTP method
    timeout : 180000,     // request timeout
    listeners : {         // configure listener
        exception : function(proxy, type, action, options,
                response, arg) {
            // this block is reached on any exception
            if (!response.isTimeout) {
                // check if response didn't timed out
                Ext.Msg.show({
                    title : '',
                    msg : "Oops !! There is some Internal Server Error.",
                    buttons : Ext.Msg.OK,
                    icon : Ext.MessageBox.INFO
                });
            } else {
                // this block is called on response timeout
                Ext.Msg.show({
                    title : '',
                    msg : "Its taking too long. Response timed out.",
                    buttons : Ext.Msg.OK,
                    icon : Ext.MessageBox.INFO
                });
            }
        }
    }
});

Note the syntax for defining exception block, the function signature is important. I have seen different signatures for this function but this is the one that worked for me.