Thursday, November 29, 2012

Linux - CPU and Memory Utilization

The following command can be used to query top 15 consumers of the CPU and Memory on a Linux box

Top CPU consumers - prints users and the % CPU used

ps aux | sort -r -n -k 3|awk '{print $1,$3}'|head -15

Output

root 12.4
saikat 2.8
giri 1.8
root 1.7
giri 1.1
vvijay 0.9
root 0.7
rbadri 0.5
chirayu 0.4
root 0.3
vvijay 0.2
vvijay 0.2
tusharv 0.2
sravanti 0.2
root 0.2

Percentage of Memory used - prints users and % used

ps aux --sort -rss|head -16|awk '{print $1,$4}'|tail -15

Output

chirayu 3.1
jaipalp 2.7
saikat 1.9
spriyam 1.7
spriyam 1.4
rbadri 1.3
rshankar 1.2
giri 1.1
giri 0.9
root 0.8
sureshk 0.5
tusharv 0.5
spriyam 0.4
root 0.3
spriyam 0.3

Monday, November 26, 2012

Applet using Java: Fetch CPU Stats using SIGAR framework

Here is a demo of an applet which will fetch info from the system and updates the display periodically

CpuInfo.java

package com.giri.monitor;


import java.util.HashMap;

import org.hyperic.sigar.CpuPerc;
import org.hyperic.sigar.Sigar;
import org.hyperic.sigar.SigarLoader;
import org.hyperic.sigar.SigarException;
import org.hyperic.sigar.cmd.Shell;
import org.hyperic.sigar.cmd.SigarCommandBase;

public class CpuInfo extends SigarCommandBase {

    public boolean displayTimes = true;
    
    public CpuInfo(Shell shell) {
        super(shell);
    }

    public CpuInfo() {
        super();
    }

    public String getUsageShort() {
        return "Display cpu information";
    }
    
    public HashMap<String,String> getMap() throws SigarException {
        HashMap<String,String> hm = new HashMap<String,String>();
        CpuPerc cpu = this.sigar.getCpuPerc();
        
        hm.put("UserTime",CpuPerc.format(cpu.getUser()).substring(0, CpuPerc.format(cpu.getUser()).length()-1));
        hm.put("SysTime",CpuPerc.format(cpu.getSys()).substring(0, CpuPerc.format(cpu.getSys()).length()-1 ));
        hm.put("IdleTime",CpuPerc.format(cpu.getIdle()).substring(0, CpuPerc.format(cpu.getIdle()).length()-1));
        hm.put("WaitTime",CpuPerc.format(cpu.getWait()).substring(0, CpuPerc.format(cpu.getWait()).length()-1));
        hm.put("NiceTime",CpuPerc.format(cpu.getNice()).substring(0, CpuPerc.format(cpu.getNice()).length()-1));
        hm.put("CombinedTime",CpuPerc.format(cpu.getCombined()).substring(0, CpuPerc.format(cpu.getCombined()).length()-1));
        hm.put("IrqTime",CpuPerc.format(cpu.getIrq()).substring(0, CpuPerc.format(cpu.getIrq()).length()-1));
        if (SigarLoader.IS_LINUX) {
            hm.put("SoftIrqTime",CpuPerc.format(cpu.getSoftIrq()).substring(0, CpuPerc.format(cpu.getSoftIrq()).length()-1));
            hm.put("StolenTime",CpuPerc.format(cpu.getStolen()).substring(0, CpuPerc.format(cpu.getStolen()).length()-1));
        }
        org.hyperic.sigar.Mem mem = this.sigar.getMem();
        org.hyperic.sigar.Uptime uptime = this.sigar.getUptime();
        org.hyperic.sigar.Sigar sig = this.sigar;
        
        double free = mem.getFreePercent();
        double used = mem.getUsedPercent();
        long ram = mem.getRam();
        hm.put("FreeMemoryPercent", Double.toString(free));
        hm.put("UsedMemoryPercent", Double.toString(used));
        hm.put("RAM", Long.toString(ram));
        hm.put("UpTimeInSeconds",Double.toString(uptime.getUptime()));
        
        double[] loadAverageArray = sig.getLoadAverage();
        hm.put("LoadAverage-1-Minute", Double.toString(loadAverageArray[0]));
        hm.put("LoadAverage-5-Minutes", Double.toString(loadAverageArray[1]));
        hm.put("LoadAverage-15-Minutes", Double.toString(loadAverageArray[2]));
        
        return hm;
    }

    private void output(CpuPerc cpu) {
        println("User Time....." + CpuPerc.format(cpu.getUser()));
        println("Sys Time......" + CpuPerc.format(cpu.getSys()));
        println("Idle Time....." + CpuPerc.format(cpu.getIdle()));
        println("Wait Time....." + CpuPerc.format(cpu.getWait()));
        println("Nice Time....." + CpuPerc.format(cpu.getNice()));
        println("Combined......" + CpuPerc.format(cpu.getCombined()));
        println("Irq Time......" + CpuPerc.format(cpu.getIrq()));
        if (SigarLoader.IS_LINUX) {
            println("SoftIrq Time.." + CpuPerc.format(cpu.getSoftIrq()));
            println("Stolen Time...." + CpuPerc.format(cpu.getStolen()));
        }
        println("");
    }

    public void output(String[] args) throws SigarException {
        org.hyperic.sigar.CpuInfo[] infos = this.sigar.getCpuInfoList();

        CpuPerc[] cpus = this.sigar.getCpuPercList();

        org.hyperic.sigar.CpuInfo info = infos[0];
        long cacheSize = info.getCacheSize();
        println("Vendor........." + info.getVendor());
        println("Model.........." + info.getModel());
        println("Mhz............" + info.getMhz());
        println("Total CPUs....." + info.getTotalCores());
        if ((info.getTotalCores() != info.getTotalSockets()) || (info.getCoresPerSocket() > info.getTotalCores()))
        {
            println("Physical CPUs.." + info.getTotalSockets());
            println("Cores per CPU.." + info.getCoresPerSocket());
        }

        if (cacheSize != Sigar.FIELD_NOTIMPL) {
            println("Cache size...." + cacheSize);
        }
        
        println("");

        if (!this.displayTimes) {
            return;
        }

        for (int i=0; i<cpus.length; i++) {
            println("CPU " + i + ".........");
            output(cpus[i]);
        }

        println("Totals........");
        output(this.sigar.getCpuPerc());
    }
}

Main.java

package com.giri.monitor;

import java.applet.*;
import java.awt.*;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import org.hyperic.sigar.SigarException;

public class Main extends Applet implements Runnable {

    private static final long serialVersionUID = 1L;
    private static int x_start = 40;
    private static int y_start = 40;
    private static int y_gap = 30;
    private static int x_gap = 250;
    private static HashMap<String,String> hmap  = null;
    private static Set<Map.Entry<String, String>> entries = null;
        
    private static Thread t;
    public void init() {
        setSize(800, 600);
        t = new Thread(this);
        try {
            hmap = new CpuInfo().getMap();
            entries = hmap.entrySet();
        } catch (SigarException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    
    
    public void start() {
        t = new Thread(this);
        t.start();
    }
    
    public void stop() {
        t.stop();
    }
    
    public void destroy() {
        
    }
    
    public void update(Graphics g) {
        Dimension d = getSize();
        g.setColor(Color.WHITE);
        g.fillRect(0, 0, d.width, d.height);
        
        g.setColor(Color.BLACK);
        g.setFont(new Font("Tahoma", Font.BOLD,14));
        
        //g.drawString("Hello World", 20, 20);
        
        if(hmap != null) {
            int count = 0;
            for(Map.Entry<String, String> entry : entries) {
                String strKey = entry.getKey();
                String strVal = entry.getValue();
                g.drawString(strKey, x_start         , y_start + (count*y_gap));
                g.drawString(strVal, x_start + x_gap , y_start + (count*y_gap));
                count++;
            }
        }
    }
    
    public void paint(Graphics g) {
        update(g);
    }
    
    public static void main(String[] args) {
        Frame appletFrame = new Frame("Stats App");
        appletFrame.setLayout(new GridLayout(1,0));
        appletFrame.resize(800, 600);
        appletFrame.show();
        Applet myApplet = new Main();
        appletFrame.add(myApplet);
        myApplet.init();
        myApplet.start();
    }

    @Override
    public void run() {
        
        while(true) {
            try {
                hmap = new CpuInfo().getMap();
                entries = hmap.entrySet();
                System.out.println("\n @ MAP >> " + hmap);
            } catch (SigarException e) {
                e.printStackTrace();
            }
            
                       
            try {
                Thread.sleep(200);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            repaint();
        }
    }
}

applet.java

<html>
<head>
    <title>Hello World Applet</title>
</head>

<body>
    <applet 
        code="com.giri.monitor.Main" archive="cpu-stats.jar" height="600" width="800">
    </applet>
</body>
</html>

Files


[giri@mint bin]$ls -l

total 820
-rw-rw-r-- 1 giri giri    198 Nov 26 14:21 applet.html
drwxrwxr-x 3 giri giri   4096 Nov 26 11:08 com
-rw-rw-r-- 1 giri giri 822594 Nov 26 14:22 cpu-stats.jar
-rw-rw-r-- 1 giri giri    141 Nov 26 10:30 java.policy.applet
-rw-rw-r-- 1 giri giri   1220 Nov 26 14:08 myKeystore

[giri@mint bin]$find .

.
./applet.html
./java.policy.applet
./com
./com/giri
./com/giri/monitor
./com/giri/monitor/CpuInfo.class
./com/giri/monitor/Main.class
./myKeystore
./cpu-stats.jar

[giri@mint bin]$

Sign the JAR: "cpu-stats.jar" it the above Eclipse project exported as a "Runnable Jar"

#  keytool -genkey -keystore myKeystore -alias myself
#  keytool -selfcert -alias myself -keystore myKeystore
#  keytool -list -keystore myKeystore
#  jarsigner -keystore myKeystore cpu-stats.jar myself

That's it ! Launch the browser and open the "applet.html" file, which will run the applet !

Sunday, November 25, 2012

CPU Monitor in Java - using SIGAR

Here is a small demo using SIGAR framework to display CPU statistics

File:Constants.java

package com.giri.cpu;


public class Constants {
 public static String USER_TIME = "UserTime";
 public static String SYS_TIME = "SysTime";
 public static String IDLE_TIME = "IdleTime";
 public static String WAIT_TIME = "WaitTime";
 public static String NICE_TIME = "NiceTime";
 public static String COMBINED_TIME = "CombinedTime";
 public static String IRQ_TIME = "IrqTime";
}


File:CpuInfo.java

package com.giri.cpu;


import java.util.HashMap;

import org.hyperic.sigar.CpuPerc;
import org.hyperic.sigar.Sigar;
import org.hyperic.sigar.SigarLoader;
import org.hyperic.sigar.SigarException;
import org.hyperic.sigar.cmd.Shell;
import org.hyperic.sigar.cmd.SigarCommandBase;

public class CpuInfo extends SigarCommandBase {

    public boolean displayTimes = true;
    
    public CpuInfo(Shell shell) {
        super(shell);
    }

    public CpuInfo() {
        super();
    }

    public String getUsageShort() {
        return "Display cpu information";
    }
    
    public HashMap<String,String> getMap() throws SigarException {
     HashMap<String,String> hm = new HashMap<String,String>();
     CpuPerc cpu = this.sigar.getCpuPerc();
     
     hm.put("UserTime",CpuPerc.format(cpu.getUser()).substring(0, CpuPerc.format(cpu.getUser()).length()-1));
     hm.put("SysTime",CpuPerc.format(cpu.getSys()).substring(0, CpuPerc.format(cpu.getSys()).length()-1 ));
     hm.put("IdleTime",CpuPerc.format(cpu.getIdle()).substring(0, CpuPerc.format(cpu.getIdle()).length()-1));
     hm.put("WaitTime",CpuPerc.format(cpu.getWait()).substring(0, CpuPerc.format(cpu.getWait()).length()-1));
     hm.put("NiceTime",CpuPerc.format(cpu.getNice()).substring(0, CpuPerc.format(cpu.getNice()).length()-1));
     hm.put("CombinedTime",CpuPerc.format(cpu.getCombined()).substring(0, CpuPerc.format(cpu.getCombined()).length()-1));
     hm.put("IrqTime",CpuPerc.format(cpu.getIrq()).substring(0, CpuPerc.format(cpu.getIrq()).length()-1));
     if (SigarLoader.IS_LINUX) {
      hm.put("SoftIrqTime",CpuPerc.format(cpu.getSoftIrq()).substring(0, CpuPerc.format(cpu.getSoftIrq()).length()-1));
      hm.put("StolenTime",CpuPerc.format(cpu.getStolen()).substring(0, CpuPerc.format(cpu.getStolen()).length()-1));
     }
     
     return hm;
    }

    private void output(CpuPerc cpu) {
        println("User Time....." + CpuPerc.format(cpu.getUser()));
        println("Sys Time......" + CpuPerc.format(cpu.getSys()));
        println("Idle Time....." + CpuPerc.format(cpu.getIdle()));
        println("Wait Time....." + CpuPerc.format(cpu.getWait()));
        println("Nice Time....." + CpuPerc.format(cpu.getNice()));
        println("Combined......" + CpuPerc.format(cpu.getCombined()));
        println("Irq Time......" + CpuPerc.format(cpu.getIrq()));
        if (SigarLoader.IS_LINUX) {
            println("SoftIrq Time.." + CpuPerc.format(cpu.getSoftIrq()));
            println("Stolen Time...." + CpuPerc.format(cpu.getStolen()));
        }
        println("");
    }

    public void output(String[] args) throws SigarException {
        org.hyperic.sigar.CpuInfo[] infos = this.sigar.getCpuInfoList();

        CpuPerc[] cpus = this.sigar.getCpuPercList();

        org.hyperic.sigar.CpuInfo info = infos[0];
        long cacheSize = info.getCacheSize();
        println("Vendor........." + info.getVendor());
        println("Model.........." + info.getModel());
        println("Mhz............" + info.getMhz());
        println("Total CPUs....." + info.getTotalCores());
        if ((info.getTotalCores() != info.getTotalSockets()) || (info.getCoresPerSocket() > info.getTotalCores()))
        {
            println("Physical CPUs.." + info.getTotalSockets());
            println("Cores per CPU.." + info.getCoresPerSocket());
        }

        if (cacheSize != Sigar.FIELD_NOTIMPL) {
            println("Cache size...." + cacheSize);
        }
        
        println("");

        if (!this.displayTimes) {
            return;
        }

        for (int i=0; i<cpus.length; i++) {
            println("CPU " + i + ".........");
            output(cpus[i]);
        }

        println("Totals........");
        output(this.sigar.getCpuPerc());
    }
}

File:CpuStatsThread.java

package com.giri.cpu;

import java.util.HashMap;
import org.hyperic.sigar.SigarException;

public class CpuStatsThread implements Runnable {
 
 public CpuStatsThread() {
  
 }

 @Override
 public void run() {
  HashMap hmap  = null;
  while(true) {
   try {
    hmap = new CpuInfo().getMap();
    
    Frame.updateProgressGivenMap(hmap);
   } catch (SigarException e) {
    e.printStackTrace();
   }
   
   try {
    Thread.sleep(100);
   } catch (InterruptedException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }
  }

 }

}

File:Frame.java

package com.giri.cpu;

import java.awt.EventQueue;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JLabel;
import java.awt.Font;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import javax.swing.JProgressBar;
import javax.swing.SwingConstants;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

public class Frame extends JFrame {

 private static final long serialVersionUID = 1L;

 private JPanel contentPane;
  
 private static JProgressBar pb_usertime = new JProgressBar();
 
 private static JProgressBar pb_systime = new JProgressBar();
 
 private static JProgressBar pb_idletime = new JProgressBar();
 
 private static JProgressBar pb_waittime = new JProgressBar();
 
 private static JProgressBar pb_nicetime = new JProgressBar();
 
 private static JProgressBar pb_combinedtime = new JProgressBar();
 
 private static JProgressBar pb_irqtime = new JProgressBar();
 
 public static void updateProgressGivenMap(HashMap<String,String> map) {
  Set<Map.Entry<String, String>> entries = map.entrySet();
  
        for(Map.Entry<String, String> entry : entries) {
            String strKey = entry.getKey();
            String strVal = entry.getValue();
            
            if(strKey.equals(Constants.COMBINED_TIME)) {
             pb_combinedtime.setValue((int) Float.parseFloat(strVal)); 
   }
   
   if(strKey.equals(Constants.IDLE_TIME)) {
    pb_idletime.setValue((int) Float.parseFloat(strVal));
   }
   
   if(strKey.equals(Constants.IRQ_TIME)) {
    pb_irqtime.setValue((int) Float.parseFloat(strVal));
   }
   
   if(strKey.equals(Constants.NICE_TIME)) {
    pb_nicetime.setValue((int) Float.parseFloat(strVal));
   }
   
   if(strKey.equals(Constants.SYS_TIME)) {
    pb_systime.setValue((int) Float.parseFloat(strVal));
   }
   
   if(strKey.equals(Constants.USER_TIME)) {
    pb_usertime.setValue((int) Float.parseFloat(strVal));    
   }
   
   if(strKey.equals(Constants.WAIT_TIME)) {
    pb_waittime.setValue((int) Float.parseFloat(strVal));
   }
        }
 }

 public static void main(String[] args) {
  EventQueue.invokeLater(new Runnable() {
   public void run() {
    try {
     Frame frame = new Frame();
     frame.setVisible(true);
     Thread t = new Thread(new CpuStatsThread());
     t.start();
    } catch (Exception e) {
     e.printStackTrace();
    }
   }
  });
 }

 /**
  * Create the frame.
  */
 public Frame() {
  setTitle("CPU Monitor (Author: Giridhar Bhujanga)");
  setResizable(false);
  setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  setBounds(100, 100, 780, 590);
  contentPane = new JPanel();
  contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
  setContentPane(contentPane);
  contentPane.setLayout(null);
  
  JLabel lblNewLabel = new JLabel("User Time");
  lblNewLabel.setBounds(53, 33, 666, 16);
  contentPane.add(lblNewLabel);
  
  JLabel lblSystemTime = new JLabel("System Time");
  lblSystemTime.setBounds(53, 101, 666, 16);
  contentPane.add(lblSystemTime);
  
  JLabel lblIdleTime = new JLabel("Idle Time");
  lblIdleTime.setBounds(53, 169, 666, 16);
  contentPane.add(lblIdleTime);
  
  JLabel lblWaitTime = new JLabel("Wait Time");
  lblWaitTime.setBounds(53, 237, 666, 16);
  contentPane.add(lblWaitTime);
  
  JLabel lblCombinedTime = new JLabel("Nice Time");
  lblCombinedTime.setBounds(53, 305, 666, 16);
  contentPane.add(lblCombinedTime);
  
  JLabel lblIrqTime = new JLabel("Combined Time\n");
  lblIrqTime.setBounds(53, 373, 666, 16);
  contentPane.add(lblIrqTime);
  
  JLabel lblIrqTime_1 = new JLabel("IRQ Time");
  lblIrqTime_1.setBounds(53, 441, 666, 16);
  contentPane.add(lblIrqTime_1);
  
  pb_usertime.setBounds(53, 61, 666, 20);
  contentPane.add(pb_usertime);

  pb_systime.setBounds(53, 129, 666, 20);
  contentPane.add(pb_systime);
  

  pb_idletime.setBounds(53, 192, 666, 20);
  contentPane.add(pb_idletime);
  

  pb_waittime.setBounds(53, 265, 666, 20);
  contentPane.add(pb_waittime);
  

  pb_nicetime.setBounds(53, 333, 666, 20);
  contentPane.add(pb_nicetime);
  

  pb_combinedtime.setBounds(53, 401, 666, 20);
  contentPane.add(pb_combinedtime);
  

  pb_irqtime.setBounds(53, 469, 666, 20);
  contentPane.add(pb_irqtime);
  
  JLabel lblCpuMonitor = new JLabel("CPU Monitor");
  lblCpuMonitor.setFont(new Font("Lucida Grande", Font.PLAIN, 15));
  lblCpuMonitor.setHorizontalAlignment(SwingConstants.RIGHT);
  lblCpuMonitor.setBounds(408, 19, 311, 16);
  contentPane.add(lblCpuMonitor);
  
  JButton btnExit = new JButton("Exit");
  btnExit.addActionListener(new ActionListener() {
   public void actionPerformed(ActionEvent arg0) {
    System.exit(0);
   }
  });
  btnExit.setBounds(513, 516, 206, 29);
  contentPane.add(btnExit);
 }
}

Tuesday, November 20, 2012

My FLUXBOX settings

This is my fluxbox settings

File:~/.fluxbox/startup

#!/bin/sh
#
# fluxbox startup-script:
#
# Lines starting with a '#' are ignored.

# Change your keymap:
xmodmap "/home/giri/.Xmodmap"

# Applications you want to run with fluxbox.
# MAKE SURE THAT APPS THAT KEEP RUNNING HAVE AN ''&'' AT THE END.
#
# unclutter -idle 2 &
# wmnd &
# wmsmixer -w &
# idesk &

# And last but not least we start fluxbox.
# Because it is the last app you have to run it with ''exec'' before it.

exec fluxbox &
# or if you want to keep a log:
# exec fluxbox -log "/home/giri/.fluxbox/log"
fbpid=$!

sleep 1
{
   # Applications you want to run after fluxbox has started
   # MAKE SURE THAT APPS THAT KEEP RUNNING HAVE AN & AT THE END.
   # ipager &
   # gkrellm2 &
   sh /home/giri/giri_startup -log "/home/giri/giri.log" &
} &
 
wait $fbpid

File:~/.fluxbox/keys

# click on the desktop to get menus
OnDesktop Mouse1 :HideMenus
OnDesktop Mouse2 :WorkspaceMenu
OnDesktop Mouse3 :RootMenu

# scroll on the desktop to change workspaces
OnDesktop Mouse4 :PrevWorkspace
OnDesktop Mouse5 :NextWorkspace

# scroll on the toolbar to change current window
OnToolbar Mouse4 :PrevWindow {static groups} (iconhidden=no)
OnToolbar Mouse5 :NextWindow {static groups} (iconhidden=no)

# alt + left/right click to move/resize a window
OnWindow Mod1 Mouse1 :MacroCmd {Raise} {Focus} {StartMoving}
OnWindowBorder Move1 :StartMoving

OnWindow Mod1 Mouse3 :MacroCmd {Raise} {Focus} {StartResizing NearestCorner}
OnLeftGrip Move1 :StartResizing bottomleft
OnRightGrip Move1 :StartResizing bottomright

# alt + middle click to lower the window
OnWindow Mod1 Mouse2 :Lower

# control-click a window's titlebar and drag to attach windows
OnTitlebar Control Mouse1 :StartTabbing

# double click on the titlebar to shade
OnTitlebar Double Mouse1 :Shade

# left click on the titlebar to move the window
OnTitlebar Mouse1 :MacroCmd {Raise} {Focus} {ActivateTab}
OnTitlebar Move1  :StartMoving

# middle click on the titlebar to lower
OnTitlebar Mouse2 :Lower

# right click on the titlebar for a menu of options
OnTitlebar Mouse3 :WindowMenu

# alt-tab
Mod1 Tab :NextWindow {groups} (workspace=[current])
Mod1 Shift Tab :PrevWindow {groups} (workspace=[current])

# cycle through tabs in the current window
Mod4 Tab :NextTab
Mod4 Shift Tab :PrevTab

# go to a specific tab in the current window
Mod4 1 :Tab 1
Mod4 2 :Tab 2
Mod4 3 :Tab 3
Mod4 4 :Tab 4
Mod4 5 :Tab 5
Mod4 6 :Tab 6
Mod4 7 :Tab 7
Mod4 8 :Tab 8
Mod4 9 :Tab 9

# open a terminal
Mod1 F1 :Exec x-terminal-emulator

Control Mod1 t :Exec /usr/bin/terminator
Control Mod1 s :Exec /usr/bin/virtualbox
Control Mod1 g :Exec /usr/bin/gedit
Control Mod1 h :Exec /home/giri
Control Mod1 v :Exec /opt/TurboVNC/bin/vncviewer
Control Mod1 c :Exec /usr/bin/google-chrome
Control Mod1 p :Exec /usr/bin/pidgin

# open a dialog to run programs
Mod1 F2 :Exec fbrun

# volume settings, using common keycodes
# if these don't work, use xev to find out your real keycodes
176 :Exec amixer sset Master,0 1+
174 :Exec amixer sset Master,0 1-
160 :Exec amixer sset Master,0 toggle

# current window commands
Mod1 F4 :Close
Mod1 F5 :Kill
Mod1 F9 :Minimize
Mod1 F10 :Maximize
Mod4 Up :Maximize
Mod1 F11 :Fullscreen

# open the window menu
Mod1 space :WindowMenu

# exit fluxbox
Control Mod1 Delete :Exit

# change to previous/next workspace
Control Mod1 Left :PrevWorkspace
Control Mod1 Right :NextWorkspace

# send the current window to previous/next workspace
Mod4 Left :SendToPrevWorkspace
Mod4 Right :SendToNextWorkspace

# send the current window and follow it to previous/next workspace
Control Mod4 Left :TakeToPrevWorkspace
Control Mod4 Right :TakeToNextWorkspace

# change to a specific workspace
Control F1 :Workspace 1
Control F2 :Workspace 2
Control F3 :Workspace 3
Control F4 :Workspace 4
Control F5 :Workspace 5
Control F6 :Workspace 6
Control F7 :Workspace 7
Control F8 :Workspace 8
Control F9 :Workspace 9
Control F10 :Workspace 10
Control F11 :Workspace 11
Control F12 :Workspace 12

# send the current window to a specific workspace
Mod4 F1 :SendToWorkspace 1
Mod4 F2 :SendToWorkspace 2
Mod4 F3 :SendToWorkspace 3
Mod4 F4 :SendToWorkspace 4
Mod4 F5 :SendToWorkspace 5
Mod4 F6 :SendToWorkspace 6
Mod4 F7 :SendToWorkspace 7
Mod4 F8 :SendToWorkspace 8
Mod4 F9 :SendToWorkspace 9
Mod4 F10 :SendToWorkspace 10
Mod4 F11 :SendToWorkspace 11
Mod4 F12 :SendToWorkspace 12

# send the current window and change to a specific workspace
Control Mod4 F1 :TakeToWorkspace 1
Control Mod4 F2 :TakeToWorkspace 2
Control Mod4 F3 :TakeToWorkspace 3
Control Mod4 F4 :TakeToWorkspace 4
Control Mod4 F5 :TakeToWorkspace 5
Control Mod4 F6 :TakeToWorkspace 6
Control Mod4 F7 :TakeToWorkspace 7
Control Mod4 F8 :TakeToWorkspace 8
Control Mod4 F9 :TakeToWorkspace 9
Control Mod4 F10 :TakeToWorkspace 10
Control Mod4 F11 :TakeToWorkspace 11
Control Mod4 F12 :TakeToWorkspace 12

Mod4 l :Exec ls
Control Mod1 e :Exec /home/giri/Downloads/eclipse/eclipse

Control Mod1 Up :Exec amixer set Master,0 5%+
Control Mod1 Down :Exec amixer set Master,0 5%-

Control Mod1 l :Exec gnome-screensaver-command -l

Control Mod1 k :Exec /usr/bin/konqueror

File:~/.fluxbox/styles/sonar-fluxbox/theme.cfg

############################################################
#  This work is licensed under the Creative Commons        #
#  Attribution-NonCommercial-ShareAlike 2.5 License.       #
#  To view a copy of this license, visit                   #
#  http://creativecommons.org/licenses/by-sa/2.5/          #
#  or send a letter to Creative Commons,                   #
#  559 Nathan Abbott Way, Stanford, California 94305, USA. #
############################################################



############################################################
style.name:   Sonar Fluxbox
style.author:   Suovainaja
style.date:   May 24, 2010
style.credits:   blaah
#  
############################################################

############################################################
# FONTS

menu.title.font:   DejaVu Sans Condensed-11:bold
*font:    DejaVu Sans Condensed-9

############################################################

############################################################
# MENU

menu.roundCorners:  
menu.title.pixmap:  menu.xpm
menu.title.justify:  center
menu.title.textColor:  #e6e6e6
menu.titleHeight:  25

menu.frame:   flat
menu.frame.justify:  left
menu.frame.color:  #303030
menu.frame.textColor:  #e6e6e6
menu.frame.disableColor: #9b9b9b

menu.hilite:   flat
menu.hilite.color:  #333333
menu.hilite.pixmap:  menu-hilight.xpm
menu.hilite.textColor:  #ffffff

menu.bevelWidth:  3
menu.itemHeight:  23
menu.borderColor:  #303030
menu.borderWidth:  0
menu.bullet:   triangle
menu.bullet.position:  Right

############################################################

############################################################
# TOOLBAR

#general settings

toolbar.roundCorners:

toolbar.borderWidth:  0
toolbar.borderColor:   #303030

toolbar.shaped:   false
toolbar.alpha:    255
toolbar.height:   21

#The clock area

toolbar.clock.textColor:  #e6e6e6
toolbar.clock.justify:   center

toolbar.clock:    flat
toolbar.clock.pixmap:   toolbar.xpm

#The workspace title area

toolbar.workspace.textColor:  #e6e6e6
toolbar.workspace.justify:  center

toolbar.workspace: flat
toolbar.workspace.pixmap:  toolbar.xpm

#The iconbar

toolbar.iconbar.empty:   flat
toolbar.iconbar.empty.pixmap:  toolbar.xpm

#Focused window icon

toolbar.iconbar.focused.textColor: #FFFFFF
toolbar.iconbar.focused.justify: center
toolbar.iconbar.focused:   flat
toolbar.iconbar.focused.pixmap:  focused.xpm

#Unfocused window icon

toolbar.iconbar.unfocused.textColor:  #BBBBBB
toolbar.iconbar.unfocused.justify:  center
toolbar.iconbar.unfocused:   flat
toolbar.iconbar.unfocused.pixmap:  toolbar.xpm

#The toolbar buttons for prevworkspace, nextworkspace, prevwindow and next window

toolbar.button.picColor: #e6e6e6
toolbar.button.pressed.picColor:  #ffffff

############################################################

############################################################
# WINDOWS

#general

window.justify:   center
window.roundCorners:  
window.bevelWidth:  0
window.borderWidth:   1
window.borderColor:  #AAAAAA

#focused and unfocused window
#titlebar

#the "background" of the window title. This is layered under window.label - see the note in part one

window.title.height:  24

#label
#the text background. This is layered over window.title - see the note in part one

window.label.focus.pixmap:  window.xpm
window.label.focus.textColor:  #FFFFFF

window.label.unfocus.pixmap:  window.xpm
window.label.unfocus.textColor: #444444

#handle

#the bar along the bottom of the window for resizing vertically

window.handleWidth:   1
window.handle.focus:   flat
window.handle.focus.color:  #303030
window.handle.unfocus:   flat
window.handle.unfocus.color:  #303030

#grips
#either side of the handle for resizing in horizontally and vertically

window.grip.focus:   flat
window.grip.focus.color:  #303030
window.grip.unfocus:   flat
window.grip.unfocus.color:  #303030

#button

#sets the background for the window buttons - not visible if window buttons (below) are used

#close, max and min, shade, stick and stuck
#close

window.close.pixmap:   close.xpm
window.close.unfocus.pixmap:  close-unfocused.xpm
window.close.pressed.pixmap:  close-pressed.xpm

#max

window.maximize.pixmap:  max.xpm
window.maximize.unfocus.pixmap: max-unfocused.xpm
window.maximize.pressed.pixmap: max-pressed.xpm

#icon

window.iconify.pixmap:   min.xpm
window.iconify.unfocus.pixmap:  min-unfocused.xpm
window.iconify.pressed.pixmap:  min-pressed.xpm

#stick

window.stick.pixmap:   stick.xpm
window.stick.unfocus.pixmap:  stick-unfocused.xpm
window.stick.pressed.pixmap:  stick-pressed.xpm
stuck

window.stuck.pixmap:   stick-pressed.xpm
window.stuck.unfocus.pixmap:  stick-pressed.xpm

window.frame.focusColor  #303030
window.frame.unfocusColor #303030

############################################################

############################################################
# TABS

window.tab.justify   center
window.tab.label.unfocus.pixmap  window.xpm
window.tab.label.unfocus.textColor #9b9b9b
window.tab.label.focus.pixmap  window.xpm
window.tab.label.focus.textColor #e6e6e6
window.tab.borderWidth   1
window.tab.borderColor   #9b9b9b

############################################################

Linux VPN Client Configuration

If you wish to connect to a Windows VPN Server from Linux, something like this would work

File:/etc/ppp/peers/myvpn

remotename myvpn
linkname myvpn
ipparam myvpn
pty "pptp [IP-Addr-of-Windows-VPN-Server] --nolaunchpppd"
name [User-Name]
require-mppe
refuse-eap
noauth
file /etc/ppp/options.pptp

File:/etc/ppp/chap-secrets

# Secrets for authentication using CHAP
# client   server  secret   IP addresses

[UserName] myvpn [MyVPN-Password] *

This file is used for setting up routing (will be different for your network) after the VPN connection is established. File:/etc/ppp/ip-up.d/my-vpn-up

#!/bin/bash

route add -net 10.0.0.0/8 ppp0

This is the final script that must be run to establish the VPN connection. File:/bin/vpn_connect.sh

#!/bin/bash

nohup pon myvpn nodetach >/dev/null 2>&1 &

Oracle (Sun) Virtual Box

How to hide the annoying MENU BAR and STATUS BAR of your VM that is created using Sun Virtual Box ?

All you have to do is run this command and then it would be removed. Make sure your VM is powered down first, then run this command. When you bring the VM back up, the status bar and menu bar would be gone.

Locate the file "vboxmanage" and then run the following command:

vboxmanage setextradata global GUI/Customizations noMenuBar,noStatusBar

Monday, November 12, 2012

Password Manager (DB) in JAVA

Here is a small java application - that will maintain all your passwords in a file which is encrypted

File: EncryptDecrypt.java

package com.giri.manager;

import java.io.*;

import javax.crypto.Cipher;
import javax.crypto.SealedObject;
import javax.crypto.KeyGenerator;
import javax.crypto.SealedObject;
import javax.crypto.SecretKey;

public class EncryptDecrypt {
 private static String secretKeyFile = ".secretKey.dat";
 private static String sealedObjectFileName = ".sealed.dat";
 private static String userHome = System.getProperty("user.home");
 private static SealedObject _sealedObject;
 private static ListAndMasterPassword _lamp;
   
 public static SealedObject get_sealedObject() {
  return _sealedObject;
 }

 public static void set_sealedObject(SealedObject _sealedObject) {
  EncryptDecrypt._sealedObject = _sealedObject;
 }

 public static ListAndMasterPassword get_lamp() {
  return _lamp;
 }

 public static void set_lamp(ListAndMasterPassword _lamp) {
  EncryptDecrypt._lamp = _lamp;
 }

 private static String getCompletePathToSealedObjectFileName() {
  return (System.getProperty("user.home")+"/"+sealedObjectFileName);
 }
 
 private static String getCompletePathToSecretKeyFileName() {
  return (System.getProperty("user.home")+"/"+secretKeyFile);
 }

 private static void writeToFile(String filename, Object object) throws Exception {
  FileOutputStream fos = null;
  ObjectOutputStream oos = null;

  try {
   fos = new FileOutputStream(new File(filename));
   oos = new ObjectOutputStream(fos);
   oos.writeObject(object);
   oos.flush();
  } catch (Exception e) {
   e.printStackTrace();
  } finally {
   if (oos != null) {
    oos.close();
   }
   if (fos != null) {
    fos.close();
   }
  }
 }

 private static Object readFromFile(String filename) throws Exception {
  FileInputStream fis = null;
  ObjectInputStream ois = null;
  Object object = null;

  try {
   fis = new FileInputStream(new File(filename));
   ois = new ObjectInputStream(fis);
   object = ois.readObject();
  } catch (Exception e) {
   e.printStackTrace();
  } finally {
   if (ois != null) {
    ois.close();
   }
   if (fis != null) {
    fis.close();
   }
  }
  return object;
 }

 public static ListAndMasterPassword decrypt() {
  MainFrame._p("decrypt()");
  ListAndMasterPassword out = null;
  File f = new File(getCompletePathToSecretKeyFileName());
  if(!f.exists()) {
   MainFrame._p("file " + getCompletePathToSecretKeyFileName() + " does not exist !" );
   return null;
  }
  
  try {
   SecretKey key = (SecretKey) readFromFile(getCompletePathToSecretKeyFileName());
   SealedObject sealedObject = (SealedObject) readFromFile(getCompletePathToSealedObjectFileName());
   String algorithmName = sealedObject.getAlgorithm();
   Cipher cipher = Cipher.getInstance(algorithmName);
   cipher.init(Cipher.DECRYPT_MODE, key);
   out = (ListAndMasterPassword) sealedObject.getObject(cipher);
   _lamp = out;
  } catch (Exception e) {
   MainFrame._p("error in decryption..!");
   e.printStackTrace();
  }
  return out;
 }

 public static void encrypt(ListAndMasterPassword object) {
  MainFrame._p("encrypt()");
  SealedObject sealed_obj = null;
  try {
   SecretKey key = KeyGenerator.getInstance("DES").generateKey();
   writeToFile(getCompletePathToSecretKeyFileName(), key);
   Cipher cipher = Cipher.getInstance("DES");
   cipher.init(Cipher.ENCRYPT_MODE, key);
   sealed_obj = new SealedObject((Serializable) object, cipher);
   _sealedObject = sealed_obj;
   writeToFile(getCompletePathToSealedObjectFileName(), sealed_obj);
  } catch (Exception e) {
   MainFrame._p("error in encryption...");
   e.printStackTrace();
  }
 }
}

File: ListAndMasterPassword.java

package com.giri.manager;

import java.awt.List;
import java.io.Serializable;

public class ListAndMasterPassword implements Serializable {
 
 private static final long serialVersionUID = 1L;
 
 private String masterPassword;
 private List list;
 
 public ListAndMasterPassword() {
  masterPassword = null;
  list = null;
 }
 
 public ListAndMasterPassword(String masterPassword, List list) {
  super();
  this.masterPassword = masterPassword;
  this.list = list;
 }

 public String getMasterPassword() {
  return masterPassword;
 }

 public void setMasterPassword(String masterPassword) {
  this.masterPassword = masterPassword;
 }

 public List getList() {
  return list;
 }

 public void setList(List list) {
  this.list = list;
 };
 
 public void printDetails() {
  MainFrame._p("\n @ Master password: " + masterPassword);
  MainFrame._p("\n @ List contents:");
  for(int i =0; i < list.getItemCount(); i++) {
   MainFrame._p("\n\t list["+i+"]="+list.getItem(i));
  }
 }
}

File: MainFrame.java

package com.giri.manager;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.List;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.Toolkit;
import java.awt.Window;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.table.DefaultTableModel;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JOptionPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.JViewport;
import javax.swing.SwingConstants;
import javax.swing.JLabel;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.UIManager.LookAndFeelInfo;

import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;
import java.awt.event.MouseMotionListener;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Vector;
import java.awt.ScrollPane;
import javax.swing.ListSelectionModel;
import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
import javax.swing.JPasswordField;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.io.File;
import java.awt.Font;
import javax.swing.JList;
import java.awt.event.MouseAdapter;


public class MainFrame extends JFrame {
 private static final long serialVersionUID = 1L;
 private static JPanel contentPane;
 
 private static DefaultTableModel dtm;
 private static MainFrame frame;
 private static JPasswordField tf_password_first;
 private static JPasswordField tf_password_second;
 private static String userHome;
 private static String DATAFILE = ".pwdmgr.dat";
 private static LinkedList<String> main_list = new LinkedList<String>();
 private static JTextField tf_user_portal_password;
 private static List list;
 private static ListAndMasterPassword LAMP;
 private static JTextField tf_modify;
 private static int select;
 private static boolean check = false;
 private static String hiddenFile = "__debug.txt";
 
 public static void _p(String s) {
  File f = new File(getUserHome() + "/" + hiddenFile);
  if(f.exists()) {
   System.out.println("\n #> " + s);
  }
 }
 
 
 private static void saveData() {
  String first = new String(tf_password_first.getPassword());
  String second = new String(tf_password_second.getPassword());
  
  if(!first.equals(second)) {
   _p("Passwords are not same !");
   JOptionPane.showMessageDialog(null,"Both the master passwords must be equal !");
  } else {
   _p("Saving data...");
   LAMP = new ListAndMasterPassword(new String(tf_password_second.getPassword()), list);
   EncryptDecrypt.encrypt(LAMP);
   LAMP.printDetails();
  }
 }
 
 @SuppressWarnings("deprecation")
 private static void loadSavedData() {
  _p("Loading data...");
  LAMP = EncryptDecrypt.decrypt();
  if(LAMP != null) {
   LAMP.printDetails();
   List new_list = LAMP.getList();
   tf_password_first.setText(LAMP.getMasterPassword());
   tf_password_second.setText(LAMP.getMasterPassword());
   for(int i=0; i<new_list.getItemCount(); i++) {
    list.addItem(new_list.getItem(i), i);
   }
  }
 }
 
 
 public static void centreWindow(Window frame) {
     Dimension dimension = Toolkit.getDefaultToolkit().getScreenSize();
     int x = (int) ((dimension.getWidth() - frame.getWidth()) / 2);
     int y = (int) ((dimension.getHeight() - frame.getHeight()) / 2);
     frame.setLocation(x, y);
 }
 
 private static String getUserHome() {
  return System.getProperty( "user.home" );
 }
 
 private static String getCompletePathToDataFile() {
  return getUserHome() + "/" + DATAFILE;
 }
 
 public static void main(String[] args) {
  
  userHome = System.getProperty( "user.home" );
  _p("user home is : " + userHome);
  
  try {
      for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
          if ("Nimbus".equals(info.getName())) {
              UIManager.setLookAndFeel(info.getClassName());
              break;
          }
      }
  } catch (Exception e) {
   _p("error in setting the UI look and feel !");
      // If Nimbus is not available, you can set the GUI to another look and feel.
   e.printStackTrace();
  }
  
  
  EventQueue.invokeLater(new Runnable() {
   public void run() {
    
    try {
     frame = new MainFrame();
     frame.setVisible(false);
     centreWindow(frame);
     
     LAMP = EncryptDecrypt.decrypt();
     
     if(LAMP != null && LAMP.getMasterPassword() != null) {
     
      JPasswordField pwd = new JPasswordField(20);
      pwd.setHorizontalAlignment(SwingConstants.CENTER);
      Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
      int w = pwd.getSize().width;
      int h = pwd.getSize().height;
      int x = (dim.width-w)/2;
      int y = (dim.height-h)/2;
      pwd.setLocation(x, y);
      int action = JOptionPane.showConfirmDialog(null, pwd,"Enter Master Password to Unlock",JOptionPane.OK_CANCEL_OPTION);
      pwd.setFocusable(true);
      pwd.grabFocus();
      
      if(action < 0) {
       // JOptionPane.showMessageDialog(null,"Cancel, X or escape key selected");
       System.exit(0);
      } else {
       
       String curr_pwd = LAMP.getMasterPassword();
       if(curr_pwd.equals(new String(pwd.getPassword()))) {
        frame.setVisible(true);
       } else {
        JOptionPane.showMessageDialog(null,"Incorrect Master Password "+new String(pwd.getPassword()) + " !");
        System.exit(0);
       }
      }
     } else {
      frame.setVisible(true);
     }
     
    } catch (Exception e) {
     e.printStackTrace();
    }
    
    
   }
  });
  
  
  
 }
 public MainFrame() {
  
  setTitle("Password Manager v1.0");
  
  setResizable(false);
  setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  setBounds(100, 100, 612, 627);
  contentPane = new JPanel();
  contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
  setContentPane(contentPane);
  contentPane.setLayout(null);
  
  JLabel lblNewLabel = new JLabel("Portals & Passwords : Please enter the password below and click on 'Save' button");
  lblNewLabel.setFont(new Font("Tahoma", Font.BOLD, 11));
  lblNewLabel.setHorizontalAlignment(SwingConstants.CENTER);
  lblNewLabel.setBounds(66, 121, 477, 16);
  contentPane.add(lblNewLabel);
  
  JLabel lblTypePassword = new JLabel("Type Password");
  lblTypePassword.setHorizontalAlignment(SwingConstants.RIGHT);
  lblTypePassword.setBounds(28, 35, 119, 16);
  contentPane.add(lblTypePassword);
  
  JLabel lblRetypePassword = new JLabel("Retype Password");
  lblRetypePassword.setHorizontalAlignment(SwingConstants.RIGHT);
  lblRetypePassword.setBounds(28, 74, 119, 16);
  contentPane.add(lblRetypePassword);
   
  
  JButton button_save = new JButton("Save !");
  button_save.addActionListener(new ActionListener() {
   public void actionPerformed(ActionEvent e) {
    if(new String(tf_password_first.getPassword()).isEmpty() || new String(tf_password_second.getPassword()).isEmpty()) {
     JOptionPane.showMessageDialog(frame,"Please enter a valid master password. It cannot be empty.");
     return;
    }
    _p("\nfirst = " + new String(tf_password_first.getPassword()));
    _p("\nsecond = " + new String(tf_password_second.getPassword()));
    String first_pwd = new String(tf_password_first.getPassword());
    String second_pwd = new String(tf_password_second.getPassword());
    if(! first_pwd.equals(second_pwd)) {
     JOptionPane.showMessageDialog(frame,"Both the passwords must be identical !");
    } else {
     saveData();
    }
   }
  });
  
  button_save.setBounds(66, 502, 207, 62);
  contentPane.add(button_save);
  
  JButton button_quit = new JButton("Quit");
  button_quit.addActionListener(new ActionListener() {
   public void actionPerformed(ActionEvent e) {
    System.exit(0);
   }
  });
  button_quit.setBounds(294, 502, 108, 62);
  contentPane.add(button_quit);
  
  JButton btnAbout = new JButton("About");
  btnAbout.addActionListener(new ActionListener() {
   public void actionPerformed(ActionEvent e) {
    JOptionPane.showMessageDialog(frame,"Password Manager - Written by Giridhar Bhujanga (giridharmb@gmail)");
   }
  });
  btnAbout.setBounds(421, 536, 122, 28);
  contentPane.add(btnAbout);
  
  tf_password_first = new JPasswordField();
  tf_password_first.setHorizontalAlignment(SwingConstants.CENTER);
  tf_password_first.setBounds(157, 29, 372, 28);
  contentPane.add(tf_password_first);
  
  tf_password_second = new JPasswordField();
  tf_password_second.setHorizontalAlignment(SwingConstants.CENTER);
  tf_password_second.setBounds(157, 68, 372, 28);
  contentPane.add(tf_password_second);
  
  list = new List();
  
  list.setFont(new Font("Arial", Font.PLAIN, 12));
  list.setBounds(52, 202, 491, 210);
  contentPane.add(list);
  
  tf_user_portal_password = new JTextField();
  tf_user_portal_password.addFocusListener(new FocusAdapter() {
   @Override
   public void focusGained(FocusEvent arg0) {
    tf_user_portal_password.selectAll();
   }
  });
  tf_user_portal_password.setHorizontalAlignment(SwingConstants.CENTER);
  tf_user_portal_password.setBounds(52, 150, 355, 28);
  contentPane.add(tf_user_portal_password);
  tf_user_portal_password.setColumns(10);
  
  JButton button_add = new JButton("Add");
  button_add.addActionListener(new ActionListener() {
   public void actionPerformed(ActionEvent e) {
    if( ((String) tf_user_portal_password.getText()).equals("") ) {
     return;
    }
    list.add(tf_user_portal_password.getText());
   }
  });
  button_add.setBounds(438, 148, 87, 30);
  contentPane.add(button_add);
  
  JButton button_delete = new JButton("Delete");
  button_delete.addActionListener(new ActionListener() {
   public void actionPerformed(ActionEvent e) {
    int selectedItem = list.getSelectedIndex();
    if( selectedItem == -1 ) {
     return;
    } else {
     list.remove(selectedItem);
    }
   }
  });
  button_delete.setBounds(421, 502, 122, 28);
  contentPane.add(button_delete);
  
  JLabel lblMasterPassword = new JLabel("Master Password");
  lblMasterPassword.setFont(new Font("Tahoma", Font.BOLD, 11));
  lblMasterPassword.setHorizontalAlignment(SwingConstants.CENTER);
  lblMasterPassword.setBounds(157, 11, 368, 14);
  contentPane.add(lblMasterPassword);
  
  tf_modify = new JTextField();
  tf_modify.addFocusListener(new FocusAdapter() {
   @Override
   public void focusGained(FocusEvent e) {
    check = true;
   }
  });
  tf_modify.setHorizontalAlignment(SwingConstants.CENTER);
  tf_modify.setBounds(52, 429, 355, 38);
  contentPane.add(tf_modify);
  tf_modify.setColumns(10);
  
  JButton button_modify = new JButton("Modify");
  button_modify.addMouseListener(new MouseAdapter() {
   @Override
   public void mouseClicked(MouseEvent e) {

   }
  });
  button_modify.addActionListener(new ActionListener() {
   public void actionPerformed(ActionEvent e) {
    
    if(list.getSelectedIndex() == -1) {
     return;
    }
    
    list.remove(select);
    list.add(tf_modify.getText(), select);
    check = false;
   }
  });
  button_modify.setBounds(421, 429, 122, 38);
  contentPane.add(button_modify);
  
  
  loadSavedData();
  
  Thread t = new Thread() {
         @Override
         public void run() {
             try {
                 while (true) {
                  if(check == false) {
                      select = list.getSelectedIndex();
                      if( select != -1 ) {
                       tf_modify.setText(list.getItem(select));
                      }
                  }
                     Thread.sleep(300);
                 }
             } catch (Exception e) {
              e.printStackTrace();
             }
         }
     };
     t.setDaemon(false);
     t.start();
 }
}

Saturday, November 10, 2012

Inheritance in Java

Here is a small code snippet which shows inheritance in Java

File: Bike.java

package com.giri.inheritance;

public class Bike {
 public int numberOfGears;
 public int topSpeedInKmph;
 public boolean hasFairing;
 
 public Bike() {
  
 }
 
 public Bike(int numberOfGears, int topSpeedInKmph, boolean hasFairing) {
  super();
  this.numberOfGears = numberOfGears;
  this.topSpeedInKmph = topSpeedInKmph;
  this.hasFairing = hasFairing;
 }

 public int getNumberOfGears() {
  return numberOfGears;
 }

 public void setNumberOfGears(int numberOfGears) {
  this.numberOfGears = numberOfGears;
 }

 public int getTopSpeedInKmph() {
  return topSpeedInKmph;
 }

 public void setTopSpeedInKmph(int topSpeedInKmph) {
  this.topSpeedInKmph = topSpeedInKmph;
 }

 public boolean isHasFairing() {
  return hasFairing;
 }

 public void setHasFairing(boolean hasFairing) {
  this.hasFairing = hasFairing;
 }
 
 public void print() {
  System.out.println("\n [Bike] Gears="+numberOfGears + " , " + "Top Speed (KM/hr)="+topSpeedInKmph + " , " + "Fairing=" + hasFairing ); 
 }
 
}

File: KawasakiNinjaBike.java

package com.giri.inheritance;

public class KawasakiNinjaBike extends Bike {
 
 public boolean hasFuelInjection;
 public boolean hasAntiLockBrakingSystem;
 
 public KawasakiNinjaBike() {
  super();
 }
 
 public KawasakiNinjaBike( int numberOfGears, 
        int topSpeedInKmph, 
        boolean hasFairing) {
  super(numberOfGears, topSpeedInKmph, hasFairing);
  
 }

 public KawasakiNinjaBike( int numberOfGears, 
        int topSpeedInKmph, 
        boolean hasFairing, 
        boolean hasFuelInjection, 
        boolean hasAntiLockBrakingSystem) {
  super(numberOfGears, topSpeedInKmph, hasFairing);
  this.hasFuelInjection = hasFuelInjection;
  this.hasAntiLockBrakingSystem = hasAntiLockBrakingSystem;
 }

 public boolean isHasFuelInjection() {
  return hasFuelInjection;
 }

 public void setHasFuelInjection(boolean hasFuelInjection) {
  this.hasFuelInjection = hasFuelInjection;
 }

 public boolean isHasAntiLockBrakingSystem() {
  return hasAntiLockBrakingSystem;
 }

 public void setHasAntiLockBrakingSystem(boolean hasAntiLockBrakingSystem) {
  this.hasAntiLockBrakingSystem = hasAntiLockBrakingSystem;
 }
 
 public void print() {
  super.print();
  System.out.println("\n [Ninja] " + " Fuel-Injection=" + hasFuelInjection + " , " + "ABS=" + hasAntiLockBrakingSystem );
 }
 
 
}

File: MainClass.java

package com.giri.inheritance;

public class MainClass {

 private static Bike              my_bike;
 private static KawasakiNinjaBike my_ninja;
 
 private static Bike              new_bike;
 private static Bike              new_ninja;
  
 
 public static void main(String[] args) {
  
  my_bike = new Bike(5, 140, true);
  my_bike.print();
  
  my_ninja = new KawasakiNinjaBike(6, 205, true, true, true);
  my_ninja.print();
  System.out.println("\n (1) my_ninja = instance of Bike() = " + (my_ninja instanceof Bike));
    
  new_bike = new Bike(4,150,false);
  new_bike.print();
  System.out.println("\n (2) new_bike = instance of Bike() = " + (new_bike instanceof Bike));
  System.out.println("\n (3) new_bike = instance of KawasakiNinjaBike() = " + (new_bike instanceof KawasakiNinjaBike));
  
  new_ninja =  new KawasakiNinjaBike(6, 260, true);
  new_ninja.print();
  System.out.println("\n (4) new_ninja = instance of KawasakiNinjaBike() = " + (new_ninja instanceof KawasakiNinjaBike));
  System.out.println("\n (5) new_ninja = instance of Bike() = " + (new_ninja instanceof Bike));
  
 }
}

Output


 [Bike] Gears=5 , Top Speed (KM/hr)=140 , Fairing=true

 [Bike] Gears=6 , Top Speed (KM/hr)=205 , Fairing=true

 [Ninja]  Fuel-Injection=true , ABS=true

 (1) my_ninja = instance of Bike() = true

 [Bike] Gears=4 , Top Speed (KM/hr)=150 , Fairing=false

 (2) new_bike = instance of Bike() = true

 (3) new_bike = instance of KawasakiNinjaBike() = false

 [Bike] Gears=6 , Top Speed (KM/hr)=260 , Fairing=true

 [Ninja]  Fuel-Injection=false , ABS=false

 (4) new_ninja = instance of KawasakiNinjaBike() = true

 (5) new_ninja = instance of Bike() = true

Simple Linux "char" Device Driver

Here is the code snippet of a tiny "character" device driver - which reverses the character string specified by the user

File : my_driver.c

#include <linux/module.h>
#include <linux/string.h>
#include <linux/fs.h>
#include <asm/uaccess.h>


MODULE_LICENSE("GPL");
MODULE_DESCRIPTION("Custom Tiny Device Driver");
MODULE_AUTHOR("Giridhar Bhujanga");


static char  msg[100]     = {0};
static short readPos      =  0;
static int   access_count =  0;
static int   MAJOR_NUMBER = 91;

static int device_open    ( struct inode * , struct file *);
static int device_release ( struct inode * , struct file *);

static ssize_t device_read  ( struct file * , char *,       size_t , loff_t *);
static ssize_t device_write ( struct file * , const char *, size_t , loff_t *);

/**********************/
/* callback functions */
/**********************/

static struct file_operations file_opts = 
{
      .read = device_read,
      .open = device_open,
     .write = device_write,
   .release = device_release
};


/************************************/
/* called when the module is loaded */
/************************************/

int init_module(void)
{
   int t = register_chrdev(MAJOR_NUMBER, "myDevice", &file_opts);
   if(t<0) 
   {
      printk(KERN_ALERT "Device registration Failed !\n");
   }
   else
   {
      printk(KERN_ALERT "Device successfully registered !\n");
   }

   return t;
}



/**************************************/
/* called when the module is unloaded */
/**************************************/

void cleanup_module(void)
{
   unregister_chrdev(91, "myDevice");
}



/*************************************************************/
/* called when 'open' system call is done on the device file */
/*************************************************************/

static int device_open(struct inode *inodep, struct file *filep)
{
   access_count++;
   printk(KERN_ALERT "Device opened %d time(s)\n", access_count);
   return 0;
}


/*************************************************************/
/* called when 'read' system call is done on the device file */
/*************************************************************/

static ssize_t device_read(struct file *filep, char *buff, size_t len, loff_t *off)
{
   short count = 0;
   while(len && (msg[readPos]!=0))
   {
      put_user(msg[readPos],buff++); /* copy byte from kernel space to user space */
      count++;
      len--;
      readPos++;
   }
   return count;
}


/**************************************************************/
/* called when 'write' system call is done on the device file */
/**************************************************************/

static ssize_t device_write(struct file *filep, const char *buff, size_t len, loff_t *off)
{
   short ind = len -1;
   short count = 0;
   memset(msg,0,100);
   readPos = 0;
   while(len >0) 
   {
      msg[count++] = buff[ind--];
      len--;
   }

   return count;
}


/**************************************************************/
/* called when 'close' system call is done on the device file */
/**************************************************************/

static int device_release(struct inode *inodep, struct file *filep)
{
   printk(KERN_ALERT "Device closed !\n");
   return 0;
}


File : Makefile

obj-m := my_driver.o
KVERSION := $(shell uname -r)
KDIR := /lib/modules/$(shell uname -r)/build/
PWD := $(shell pwd)
INC := -I/usr/src/kernels/2.6.18-194.el5-x86_64/include/ -I/usr/include -I/usr/lib/x86_64-redhat-linux4E/include/

all:
 $(MAKE) $(INC) -C $(KDIR) M=$(PWD) modules

clean:
 $(MAKE) $(INC) -C $(KDIR) M=$(PWD) clean


Output of "make" command

[root@RHEL-55 tutorial-4]# make
make -I/usr/src/kernels/2.6.18-194.el5-x86_64/include/ -I/usr/include -I/usr/lib/x86_64-redhat-linux4E/include/ -C /lib/modules/2.6.18-194.el5/build/ M=/root/kernel-programs/tutorial-4 modules
make[1]: Entering directory `/usr/src/kernels/2.6.18-194.el5-x86_64'
  CC [M]  /root/kernel-programs/tutorial-4/my_driver.o
  Building modules, stage 2.
  MODPOST
  CC      /root/kernel-programs/tutorial-4/my_driver.mod.o
  LD [M]  /root/kernel-programs/tutorial-4/my_driver.ko
make[1]: Leaving directory `/usr/src/kernels/2.6.18-194.el5-x86_64'
[root@RHEL-55 tutorial-4]# 

Create the device file through the command "mknod"


Create:

# mknod /dev/myDevice c 91 1

Set permissions:

# chmod a+r+w /dev/myDevice


Current list of files after the command : make

[root@RHEL-55 tutorial-4]# ls -l
total 364
-rw-r--r-- 1 root root    331 Nov 10 15:27 Makefile
-rw-r--r-- 1 root root      0 Nov 10 15:34 Module.markers
-rw-r--r-- 1 root root      0 Nov 10 15:34 Module.symvers
-rw-r--r-- 1 root root   3095 Nov 10 16:05 my_driver.c
-rw-r--r-- 1 root root 164963 Nov 10 16:38 my_driver.ko
-rw-r--r-- 1 root root    794 Nov 10 16:38 my_driver.mod.c
-rw-r--r-- 1 root root  80936 Nov 10 16:38 my_driver.mod.o
-rw-r--r-- 1 root root  85776 Nov 10 16:38 my_driver.o
-rwxr-xr-x 1 root root   7697 Nov 10 16:29 verify
-rw-r--r-- 1 root root    433 Nov 10 16:29 verify.c
[root@RHEL-55 tutorial-4]# 

Install the kernel module

# insmod my_driver.ko 

Verify : " tail -f /var/log/messages" "

Nov 10 16:40:23 RHEL-55 kernel: Device successfully registered !

Verify if the driver is working correctly


Feed a string to the driver:

# echo "hello world" > /dev/myDevice

"tail -f /var/log/messages":

Nov 10 16:43:13 RHEL-55 kernel: Device opened 1 time(s)
Nov 10 16:43:13 RHEL-55 kernel: Device closed !

It should reverse the string which it gets:

# cat /dev/myDevice

dlrow olleh

"tail -f /var/log/messages":

Nov 10 16:45:27 RHEL-55 kernel: Device opened 2 time(s)
Nov 10 16:45:27 RHEL-55 kernel: Device closed !


C program to verify if our driver is working correctly verify.c

#include <stdio.h>
#include <fcntl.h>
#include <assert.h>
#include <string.h>

int main(int argc, char *argv[])
{
   assert(argc > 1);
   char buff[100];
   char i = 0;
   
   memset(buff,0,100);

   printf("\nInput: %s\n", argv[1]);

   int fp = open("/dev/myDevice", O_RDWR);

   write(fp, argv[1], strlen(argv[1]));

   while(read(fp, &buff[i++], 1));

   printf("\nReversed by the driver: \n\n\t %s \n\n", buff);

   return 0;
}


Run the verify program


[root@RHEL-55 tutorial-4]# gcc verify.c -o verify
[root@RHEL-55 tutorial-4]# 
[root@RHEL-55 tutorial-4]# ./verify "holy cow"

Input: holy cow

Reversed by the driver: 

  woc yloh 

[root@RHEL-55 tutorial-4]# 


Friday, November 9, 2012

Client/Server Socket communication in Java

Here is a client/server program which uses sockets to communicate

Q: What is the role of the client and server in this program ?

A: The client enters the IP address and the text message to be sent to the server. After it submits the messages, the sever fetches the message and displays it - at the same time, it will reply back to the client with a new message


Server: Server.java

package com.msg.deploy;

import java.io.*;
import java.net.*;

public class Server implements Runnable {
 
 private String threadName;
 private String capitalizedSentence;
 private String clientSentence;
 private ServerSocket welcomeSocket;
 private Socket connectionSocket;
 private BufferedReader inFromClient;
 private DataOutputStream outToClient;
 private int PORT = 1234;
 
 public Server(String name) {
  threadName = name;
  try {
   welcomeSocket = new ServerSocket(PORT);
  } catch(Exception e) {
   e.printStackTrace();
  }
 }

 @Override
 public void run() {
  System.out.println("Starting server side listener...");

  while(true) {
   try {
    
    connectionSocket = welcomeSocket.accept();
    
    inFromClient = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
    
    outToClient = new DataOutputStream(connectionSocket.getOutputStream());
    
    clientSentence = inFromClient.readLine();
    
    Main.textField.setText(clientSentence.toString());
        
    capitalizedSentence = clientSentence.toUpperCase() + "\n";
    outToClient.writeBytes(capitalizedSentence);
    
    Main.frame.setVisible(true);
    
    //Thread.sleep(400);
   } catch(Exception e) {
    e.printStackTrace();
   }
  }
  
 }
}

Server: Main.java

package com.msg.deploy;

import java.awt.BorderLayout;
import java.awt.Dialog;
import java.awt.EventQueue;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JTextField;
import java.awt.Font;
import javax.swing.SwingConstants;

public class Main extends JFrame {

 private JPanel contentPane;
 public static JTextField textField;
 private static Server server;
 private static Thread thread;
 public static Main frame;

 /**
  * Launch the application.
  */
 public static void main(String[] args) {
  
  
  
  
  EventQueue.invokeLater(new Runnable() {
   public void run() {
    try {
     frame = new Main();
     frame.setVisible(true);
    } catch (Exception e) {
     e.printStackTrace();
    }
   }
  });
  
  Thread t = new Thread(new Server("server"));
  t.start();
 }

 /**
  * Create the frame.
  */
 public Main() {
  setResizable(false);
  
  setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
  setBounds(100, 100, 450, 258);
  contentPane = new JPanel();
  contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
  setContentPane(contentPane);
  contentPane.setLayout(null);
  
  textField = new JTextField();
  textField.setEditable(false);
  textField.setHorizontalAlignment(SwingConstants.CENTER);
  textField.setFont(new Font("Tahoma", Font.PLAIN, 22));
  textField.setBounds(31, 25, 385, 172);
  contentPane.add(textField);
  textField.setColumns(10);
 }
}


Client: Client.java

package com.giri.client;

import java.awt.TextField;
import java.io.*;
import java.net.*;

public class Client implements Runnable {
 
 private String sentence;
 private String modifiedSentence;
 private BufferedReader inFromUser;
 private Socket clientSocket;
 private DataOutputStream outToServer;
 private BufferedReader inFromServer;
 private String threadName;
 private int PORT = 1234;
 
 
 public Client(String name) {
  threadName = name;
 }
 
 public void send() {
  try {
   
   InetAddress addr = InetAddress.getByName(MainClient.textField_1.getText().toString());

   clientSocket = new Socket(addr, PORT);

   //clientSocket = new Socket(MainClient.textField_1.getText(), PORT);
   outToServer = new DataOutputStream(clientSocket.getOutputStream());
   
   inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));

   //sentence = inFromUser.readLine();
   sentence = MainClient.textField.getText().toString();
   
   outToServer.writeBytes(sentence + "\n");
   modifiedSentence = inFromServer.readLine();
   MainClient.textField_2.setText("From Server:"+modifiedSentence);
   clientSocket.close();
   
  } catch(Exception e) {
   e.printStackTrace();
  }
 }

 @Override
 public void run() {
  send();
 }
}

Client: MainClient.java

package com.giri.client;

import java.awt.BorderLayout;
import java.awt.EventQueue;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JTextField;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.SwingConstants;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

public class MainClient extends JFrame {

 private JPanel contentPane;
 public static JTextField textField;
 public static JTextField textField_1;
 public static JTextField textField_2;
 private JLabel lblFromServer;
 private Client client = null; 
 private Thread thread = null;

 /**
  * Launch the application.
  */
 public static void main(String[] args) {
  EventQueue.invokeLater(new Runnable() {
   public void run() {
    try {
     MainClient frame = new MainClient();
     frame.setVisible(true);
    } catch (Exception e) {
     e.printStackTrace();
    }
   }
  });
 }

 /**
  * Create the frame.
  */
 public MainClient() {
  setResizable(false);
  setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  setBounds(100, 100, 559, 175);
  contentPane = new JPanel();
  contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
  setContentPane(contentPane);
  contentPane.setLayout(null);
  
  textField = new JTextField();
  textField.setHorizontalAlignment(SwingConstants.CENTER);
  textField.setBounds(175, 42, 366, 20);
  contentPane.add(textField);
  textField.setColumns(10);
  
  JButton btnNewButton = new JButton("Send Message");
  btnNewButton.addActionListener(new ActionListener() {
   public void actionPerformed(ActionEvent arg0) {
    Thread t = new Thread(new Client("test"));
    t.start();
    //thread = new Thread(new Client("test"));
    //thread.start();
   }
  });
  btnNewButton.setBounds(10, 73, 531, 23);
  contentPane.add(btnNewButton);
  
  textField_1 = new JTextField();
  textField_1.setHorizontalAlignment(SwingConstants.CENTER);
  textField_1.setBounds(175, 11, 366, 20);
  contentPane.add(textField_1);
  textField_1.setColumns(10);
  
  JLabel lblNewLabel = new JLabel("IP Address");
  lblNewLabel.setBounds(10, 14, 153, 14);
  contentPane.add(lblNewLabel);
  
  JLabel lblNewLabel_1 = new JLabel("Message");
  lblNewLabel_1.setBounds(10, 45, 153, 14);
  contentPane.add(lblNewLabel_1);
  
  textField_2 = new JTextField();
  textField_2.setBounds(175, 105, 366, 20);
  contentPane.add(textField_2);
  textField_2.setColumns(10);
  
  lblFromServer = new JLabel("From Server");
  lblFromServer.setBounds(10, 108, 153, 14);
  contentPane.add(lblFromServer);
 }
}


Java Serialization and Deserialization using Generics

Here is a small example of Java's serialization and deserialization through the use of Generics

File : MyData.java

package com.giri.generics;

import java.io.Serializable;

public class MyData implements Serializable {
 private String name;
 private int age;
 private String country;
 
 
 public MyData(String name, int age, String country) {
  super();
  this.name = name;
  this.age = age;
  this.country = country;
 }
 
 public String getName() {
  return name;
 }
 public void setName(String name) {
  this.name = name;
 }
 public int getAge() {
  return age;
 }
 public void setAge(int age) {
  this.age = age;
 }
 public String getCountry() {
  return country;
 }
 public void setCountry(String country) {
  this.country = country;
 }
 
 public void print() {
  System.out.println("\n [MyData] : " + "Name => "+ name + "  Age => " + age + "  Country => " + country);
 }
 
}

File : SerializeGeneric.java

package com.giri.generics;

import java.io.FileOutputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

public class SerializeGeneric<T> {
 private String fileName;
 private T serData;
 
 public SerializeGeneric(String fileName, T serData) {
  super();
  this.fileName = fileName;
  this.serData = serData;
 }

 public String getFileName() {
  return fileName;
 }

 public void setFileName(String fileName) {
  this.fileName = fileName;
 }

 public T getSerData() {
  return serData;
 }

 public void setSerData(T serData) {
  this.serData = serData;
 }
 
 
 public void serialize() {
  FileOutputStream fos = null;
  ObjectOutputStream oos = null;
  
  try {
   fos = new FileOutputStream(fileName);
   oos = new ObjectOutputStream(fos);
   oos.writeObject(serData);
   oos.close();
   fos.close();
  } catch(Exception e) {
   e.printStackTrace();
  }
 }
}

File : DeserializeGeneric.java

package com.giri.generics;

import java.io.FileInputStream;
import java.io.ObjectInputStream;

public class DeserializeGeneric<T> {
 
 private String fileName;

 
 public DeserializeGeneric(String fileName) {
  super();
  this.fileName = fileName;
 }

 public String getFileName() {
  return fileName;
 }

 public void setFileName(String fileName) {
  this.fileName = fileName;
 }
 
 public T deserialize() {
  System.out.println("\n Reading the file " + fileName + " and calling deserialize(): ");
  T data = null;
  try {
   FileInputStream fis = new FileInputStream(fileName);
   ObjectInputStream ois = new ObjectInputStream(fis);
   data = (T) ois.readObject();
   ois.close();
   fis.close();
  } catch(Exception e) {
   e.printStackTrace();
  }
  return data;
 }
 
}

File : MainClass.java

package com.giri.generics;

public class MainClass {


 public static  <E> void printArray( E[] inputArray ) {
  int count = 0;
  for(E element : inputArray ) {
   System.out.printf("\n inputArray[%d] = %s ", count++, element);
  }
  System.out.println("\n");
 }
 
 public static void main(String[] args) {
  
  String fileName = "serialization.ser"; 
    
  Integer[] intArray = { 1,2,3,4,5,6,7,8 };
  Double[] doubleArray = { 1.1, 2.2, 3.3, 4.4, 5.5 };
  Character[] charArray = { 'J', 'A', 'V', 'A' };
  
  System.out.println("\nInteger Array:");
  printArray(intArray);
  
  System.out.println("\nDouble Array:");
  printArray(doubleArray);
  
  System.out.println("\nCharacter Array:");
  printArray(charArray);
  
  MyData myData = new MyData("Giridhar", 22, "india");
  
  System.out.println("\n 1. Doing serialization ..");
  
  SerializeGeneric<MyData> ser_gen = new SerializeGeneric<MyData>(fileName, myData);
  ser_gen.serialize();
  
  System.out.println("\n 2. Doing De-serialization ..");
  DeserializeGeneric<MyData> deser_gen = new DeserializeGeneric<MyData>(fileName);
  MyData new_data = deser_gen.deserialize();
  new_data.print();
  
 }

}

Output


Integer Array:

 inputArray[0] = 1 
 inputArray[1] = 2 
 inputArray[2] = 3 
 inputArray[3] = 4 
 inputArray[4] = 5 
 inputArray[5] = 6 
 inputArray[6] = 7 
 inputArray[7] = 8 


Double Array:

 inputArray[0] = 1.1 
 inputArray[1] = 2.2 
 inputArray[2] = 3.3 
 inputArray[3] = 4.4 
 inputArray[4] = 5.5 


Character Array:

 inputArray[0] = J 
 inputArray[1] = A 
 inputArray[2] = V 
 inputArray[3] = A 


 1. Doing serialization ..

 2. Doing De-serialization ..

 Reading the file serialization.ser and calling deserialize(): 

 [MyData] : Name => Giridhar  Age => 22  Country => india

Java Serialization and Deserialization

Here is a small example of Java's serialization and deserialization

File : Student.java

package com.giri.serial;

import java.io.Serializable;

public class Student implements Serializable {
 private String name;
 private int age;
 private float percentage;
 private String college;
 
 public Student() {
  
 }

 public Student(String name, int age, float percentage, String college) {
  super();
  this.name = name;
  this.age = age;
  this.percentage = percentage;
  this.college = college;
 }

 public String getName() {
  return name;
 }

 public void setName(String name) {
  this.name = name;
 }

 public int getAge() {
  return age;
 }

 public void setAge(int age) {
  this.age = age;
 }

 public float getPercentage() {
  return percentage;
 }

 public void setPercentage(float percentage) {
  this.percentage = percentage;
 }

 public String getCollege() {
  return college;
 }

 public void setCollege(String college) {
  this.college = college;
 }
 
 public void print() {
  System.out.println("\n[Student] Name:"+name+ " Age:"+age + " Percentage:"+percentage+ " College:"+college);
 }
 
 
}

File : Serialize.java


package com.giri.serial;

import java.io.FileOutputStream;
import java.io.ObjectOutputStream;

public class Serialize {
 
 private Student student;
 private String filename;
 
 public Serialize() {
  student = null;
  filename = null;
 }
 
 public Serialize(Student student, String filename) {
  super();
  this.student = student;
  this.filename = filename;
 }

 public Student getStudent() {
  return student;
 }

 public void setStudent(Student student) {
  this.student = student;
 }

 public String getFilename() {
  return filename;
 }

 public void setFilename(String filename) {
  this.filename = filename;
 }
 
 public void serialize() {
  FileOutputStream fos = null;
  ObjectOutputStream oos = null;
  
  try {
   fos = new FileOutputStream(filename);
   oos = new ObjectOutputStream(fos);
   oos.writeObject(student);
   oos.close();
   fos.close();
  } catch(Exception e) {
   e.printStackTrace();
  }
 }
}

File : Deserialize.java

package com.giri.serial;

import java.io.FileInputStream;
import java.io.ObjectInputStream;

public class Deserialize {
 
 private String filename;
 
 public Deserialize() {
  filename = null;
 }
 
 public Deserialize(String f) {
  filename = f;
 }

 public String getFilename() {
  return filename;
 }

 public void setFilename(String filename) {
  this.filename = filename;
 }
 
 public Student deserialize() {
  System.out.println("\n Reading the file " + filename + " and calling deserialize(): ");
  Student s = new Student();
  try {
   FileInputStream fis = new FileInputStream(filename);
   ObjectInputStream ois = new ObjectInputStream(fis);
   s = (Student) ois.readObject();
   ois.close();
   fis.close();
  } catch(Exception e) {
   e.printStackTrace();
  }
  return s;
 }
}

File : SerializableMainClass.java

package com.giri.serial;

import java.io.FileOutputStream;
import java.io.ObjectOutputStream;

public class SerializableMainClass {

 public static void main(String[] args) {
  
  String filename = "student.ser";
  FileOutputStream fos = null;
  ObjectOutputStream oos = null;
  
  
  
  Student s = new Student();
  s.setName("Bill Gates");
  s.setCollege("Microsoft University");
  s.setAge(25);
  s.setPercentage(75);
  
  System.out.println("(1) Serialization ..");
  
  Serialize ser = new Serialize(s,filename);
  ser.serialize();
  
  System.out.println("(2) Deserialization ..");
  
  Deserialize deser = new Deserialize(filename);
  Student new_student = deser.deserialize();
  new_student.print();
  
 }
}

Output

(1) Serialization ..
(2) Deserialization ..

 Reading the file student.ser and calling deserialize(): 

[Student] Name:Bill Gates Age:25 Percentage:75.0 College:Microsoft University

Thursday, November 8, 2012

Linux Kernel Modules: Example #2

Here is another example of a module for the linux kernel

File:hello-5.c

#include <linux/module.h>
#include <linux/moduleparam.h>
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/stat.h>

MODULE_LICENSE("GPL");
MODULE_AUTHOR("Giridhar Bhujanga");

static short int myshort = 1;
static int myint = 420;
static long int mylong = 9999;
static char *mystring = "blah";
static int myintArray[2] = { -1, 1 };
static int arr_argc = 0;

/*
 * module_param(foo, int, 0000)
 * the first param is the parameters name
 * the second parameter is it's data type
 * the final argument is the permission bits
 * for exposing parameters in sysfs (if non-zero) at a later stage
 */

module_param(myshort, short, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP );
MODULE_PARM_DESC(myshort, "A short integer");

module_param(myint, int, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);
MODULE_PARM_DESC(myint, "An integer");

module_param(mylong, long, S_IRUSR);
MODULE_PARM_DESC(mylong, "A long integer");

module_param(mystring , charp, 0000);
MODULE_PARM_DESC(mystring, "A character string");

/* module_param_array(name, type, num, perm);
 * the first param is the parameter's (in this case array's) name
 * the second param is the data type of the elements in the array
 * the third argument is the pointer to the variable that will store the number
 * of elements of the array initialized by the user at the module loading time
 * the fourth argument is the permission bits
 */

static int __init hello_5_init(void)
{
   int i;
   printk(KERN_INFO "Hello world 5\n=========================\n");
   printk(KERN_INFO "myshort is a short integer: %hd\n", myshort);
   printk(KERN_INFO "myint is an integer: %d\n", myint);
   printk(KERN_INFO "mylong is a long integer: %ld\n", mylong);
   printk(KERN_INFO "mystring is a string: %s\n", mystring);

   for(i=0; i< (sizeof myintArray / sizeof (int)); i++)
   {
      printk(KERN_INFO "myintArray[%d] = %d\n", i, myintArray[i]);
   }

   printk(KERN_INFO "\ngot %d arguments for myintArray\n",arr_argc);
   return 0;
}

static void __exit hello_5_exit(void)
{
   printk(KERN_INFO "\n>>> Good Bye !! <<<\n");
}

module_init(hello_5_init);
module_exit(hello_5_exit);

File:Makefile

obj-m := hello-5.o
KVERSION := $(shell uname -r)
KDIR := /lib/modules/$(shell uname -r)/build/
PWD := $(shell pwd)
INC := -I/usr/src/kernels/2.6.18-194.el5-x86_64/include/ -I/usr/include -I/usr/lib/x86_64-redhat-linux4E/include/

all:
 $(MAKE) $(INC) -C $(KDIR) M=$(PWD) modules

clean:
 $(MAKE) $(INC) -C $(KDIR) M=$(PWD) clean

Output of "make"

[root@RHEL-55 tutorial-2]# make
make -I/usr/src/kernels/2.6.18-194.el5-x86_64/include/ -I/usr/include -I/usr/lib/x86_64-redhat-linux4E/include/ -C /lib/modules/2.6.18-194.el5/build/ M=/root/kernel-programs/tutorial-2 modules
make[1]: Entering directory `/usr/src/kernels/2.6.18-194.el5-x86_64'
  CC [M]  /root/kernel-programs/tutorial-2/hello-5.o
  Building modules, stage 2.
  MODPOST
  CC      /root/kernel-programs/tutorial-2/hello-5.mod.o
  LD [M]  /root/kernel-programs/tutorial-2/hello-5.ko
make[1]: Leaving directory `/usr/src/kernels/2.6.18-194.el5-x86_64'
[root@RHEL-55 tutorial-2]# 

Output ("tail -f /var/log/messages")

Nov  8 22:19:33 RHEL-55 kernel: Hello world 5
Nov  8 22:19:33 RHEL-55 kernel: =========================
Nov  8 22:19:33 RHEL-55 kernel: myshort is a short integer: 1
Nov  8 22:19:33 RHEL-55 kernel: myint is an integer: 420
Nov  8 22:19:33 RHEL-55 kernel: mylong is a long integer: 9999
Nov  8 22:19:33 RHEL-55 kernel: mystring is a string: blah
Nov  8 22:19:33 RHEL-55 kernel: myintArray[0] = -1
Nov  8 22:19:33 RHEL-55 kernel: myintArray[1] = 1
Nov  8 22:19:33 RHEL-55 kernel: 
Nov  8 22:19:33 RHEL-55 kernel: got 0 arguments for myintArray
Nov  8 22:19:49 RHEL-55 kernel: 
Nov  8 22:19:49 RHEL-55 kernel: >>> Good Bye !! <<<

Sun Virtual Box Networking

Here is an example of assigning IP address to the VM which you've created inside Sun Virtual Box - so that from outside you could SSH to the IP address set inside the guest OS (Linux in this case) to the interface eth1 as in the example below).

Linux "hello world" Kernel Module

Here is a "hello world" program which loads and unloads a kernel module

hello.c

#undef __KERNEL__
#define __KERNEL__

#undef MODULE
#define MODULE

#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/init.h>
#include <asm/unistd.h>
#include <asm/fcntl.h>
#include <asm/errno.h>
#include <linux/types.h>
#include <linux/dirent.h>
#include <linux/string.h>
#include <linux/fs.h>

static int __init hello_init(void) {
   printk(KERN_INFO "Hello World\n");
   return 0;
}

static void __exit hello_cleanup(void) {
   printk(KERN_INFO "Cleaning up modules\n");
}

module_init(hello_init);
module_exit(hello_cleanup);

Makefile

obj-m := hello.o
KVERSION := $(shell uname -r)
KDIR := /lib/modules/$(shell uname -r)/build/
PWD := $(shell pwd)
INC := -I/usr/src/kernels/2.6.18-194.el5-x86_64/include/ -I/usr/include -I/usr/lib/x86_64-redhat-linux4E/include/

all:
 $(MAKE) $(INC) -C $(KDIR) M=$(PWD) modules

clean:
 $(MAKE) $(INC) -C $(KDIR) M=$(PWD) clean

Run "make" , Output:


[root@localhost kernel-programs]# make

make -I/usr/src/kernels/2.6.18-194.el5-x86_64/include/ -I/usr/include -I/usr/lib/x86_64-redhat-linux4E/include/ -C /lib/modules/2.6.18-194.el5/build/ M=/root/kernel-programs modules
make[1]: Entering directory `/usr/src/kernels/2.6.18-194.el5-x86_64'
  CC [M]  /root/kernel-programs/hello.o
  Building modules, stage 2.
  MODPOST
  CC      /root/kernel-programs/hello.mod.o
  LD [M]  /root/kernel-programs/hello.ko
make[1]: Leaving directory `/usr/src/kernels/2.6.18-194.el5-x86_64'

[root@localhost kernel-programs]# 

Files

[root@localhost kernel-programs]# ls -l
total 340
-rw-r--r-- 1 root root    548 Nov  8 11:59 hello.c
-rw-r--r-- 1 root root 159367 Nov  8 12:14 hello.ko
-rw-r--r-- 1 root root    660 Nov  8 12:14 hello.mod.c
-rw-r--r-- 1 root root  80528 Nov  8 12:14 hello.mod.o
-rw-r--r-- 1 root root  80128 Nov  8 12:14 hello.o
-rw-r--r-- 1 root root    327 Nov  8 11:55 Makefile
-rw-r--r-- 1 root root      0 Nov  8 11:59 Module.markers
-rw-r--r-- 1 root root      0 Nov  8 11:59 Module.symvers

[root@localhost kernel-programs]# 

Load the "hello.ko" module

[root@localhost kernel-programs]# insmod hello.ko

Verify: "tail -f /var/log/messages"

Nov  8 12:17:04 localhost kernel: Hello World

Unload the module: "rmmod hello"

Nov  8 12:18:32 localhost kernel: Cleaning up modules

Wednesday, November 7, 2012

Java thread synchronization

Here is a small example of thread synchronization in Java

File: Message.java

package com.giri.threads;

public class Message {
 
 public Message() {
  // nothing
 }
 
 public void print(String msg) {
  System.out.println("\n[Message] " + msg);
 
  try {
   Thread.sleep(1000);
  } catch(Exception e) {
   e.printStackTrace();
  }
 }
}

File: SynchronizedThread .java

package com.giri.threads;

public class SynchronizedThread implements Runnable {
 
 private String str;
 private Message message;
 private Thread t;
 
 public SynchronizedThread(Message m, String s) {
  message = m;
  str = s;
  t = new Thread(this);
  t.start();
 }
 
 // synchronized calls to print()
 @Override
 public void run() {
  synchronized(message) {
   message.print("This is from SynchronizedThread: run(): "+str);
  }
 }
}

File: MainClass.java

package com.giri.threads;

public class MainClass {

 private static Message msg = new Message();
 
 private static Thread st1 = new Thread(new SynchronizedThread(msg, "Hello"));
 private static Thread st2 = new Thread(new SynchronizedThread(msg, "This is a test of"));
 private static Thread st3 = new Thread(new SynchronizedThread(msg, "Synchronization"));
 private static Thread st4 = new Thread(new SynchronizedThread(msg, "in Java"));
 
 public static void main(String[] args) {
  try {
   st1.join();
   st2.join();
   st3.join();
   st4.join();
  } catch(Exception e) {
   e.printStackTrace();
  }
 }

}

Output


[Message] This is from SynchronizedThread: run(): Hello

[Message] This is from SynchronizedThread: run(): in Java

[Message] This is from SynchronizedThread: run(): Synchronization

[Message] This is from SynchronizedThread: run(): This is a test of

Thread Pool in Java

Here is a small code snippet which shows how we can implement Thread Pools in Java

What does the application do ?

It creates multiple threads (one can define the pool size) and each thread is responsible for calculating the size of a specified folder. If a folder has multiple folders/files and sub-folders inside them, it recursively goes into each one of them and uses the existing thread pool to re-use the threads to calculate the folder size. Thread pools limit the number of threads that are created - too many threads will start thrashing the CPU and it will hamper the performance. The code is somewhat working :-)

File: DeniedExecHandlerImpl.java

package com.giri.interview;

import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadPoolExecutor;

// in case the queue is full - the task is rejected and this function is called when a particular task is rejected

public class DeniedExecHandlerImpl implements RejectedExecutionHandler {

 @Override
 public void rejectedExecution(Runnable arg0, ThreadPoolExecutor arg1) {
  System.out.println("\nDENIED: " + arg0.toString() + " thread has not been accepted for execution !");
 }
}

File: MainClass.java

package com.giri.interview;

import java.io.File;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class MainClass {
 
 public static long CALCULATED_FOLDER_SIZE = 0;
 
 private static int q_size = 30000;      //------------------->> this has to be a large number
 private static int max_pool_size = 10;  //------------------->> Number of parallel threads
 
 private static BlockingQueue bq_runnable = new ArrayBlockingQueue(q_size);
 private static RejectedExecutionHandler deny_handler = new DeniedExecHandlerImpl();
 
 private static ThreadPoolExecutor main_executor = null;
 private static Thread main_monitor = null;
 
 
 public static MainVariables mainVars = new MainVariables();
 
 public static void main(String[] args) {
  
  main_executor = new ThreadPoolExecutor( max_pool_size, 
            max_pool_size, 
            10000, 
            TimeUnit.SECONDS, 
            bq_runnable, 
            deny_handler);
  
  main_executor.allowCoreThreadTimeOut(false);
  
  main_monitor = new Thread(new MainMonitorThread(main_executor));
  main_monitor.setDaemon(true);
  main_monitor.start();
  
    
  LinkedList allDirs = new LinkedList();
  String dirPath = "/Users/apple";
  allDirs = Utils.getAllFoldersAndSubFolders(new File(dirPath));
  System.out.println("\n Total number of directories in the directory path : " + dirPath + " = "+ allDirs.size());
  
  int t_count = 0;
  
  for(File d : allDirs) {
   String countStr = Integer.toString(t_count++);
   main_executor.execute(new ThreadedFolderSizeCalculator(countStr, d));
  }
 }
}

File: MainMonitorThread.java

package com.giri.interview;

import java.util.concurrent.ThreadPoolExecutor;


// this is the main moniting thread - which keeps dumping some important info on stdout

public class MainMonitorThread implements Runnable {
 
 private ThreadPoolExecutor exec;
 
 public MainMonitorThread(ThreadPoolExecutor e) {
  exec = e;
 }

 @Override
 public void run() {
  try {
   while(true) {
    
    System.out.println("\n @ Monitor @ >> "
      + "Pool-Size=["            + exec.getPoolSize()           + "] "
      + "Core-Pool-Size=["       + exec.getCorePoolSize()       + "] "
      + "Active-Count=["         + exec.getActiveCount()        + "] "
      + "Completed-Task-Count=[" + exec.getCompletedTaskCount() + "] "
      + "Task-Count=["           + exec.getTaskCount()          + "] "
      + "Shut-Down=["            + exec.isShutdown()            + "] "
      + "Is-Terminated=["        + exec.isTerminated()          + "] "
    );
    Thread.sleep(1000);
   } // while
  } catch(Exception e) {
   System.out.println("Error in MainMonitorThread !");
   e.printStackTrace();
  }

 }

}

File: MainVariables.java

package com.giri.interview;

public class MainVariables {
 
 // this class holds certain important variables
 
 // total file size (of all files in all directories)
 private long TOTAL_SIZE = 0;
 
 private long NUM_FILES = 0;
 private long NUM_FOLDERS = 0;
 
 public synchronized long getTOTAL_SIZE() {
  return TOTAL_SIZE;
 }
 public synchronized void setTOTAL_SIZE(long tOTAL_SIZE) {
  TOTAL_SIZE = tOTAL_SIZE;
 }
 public synchronized long getNUM_FILES() {
  return NUM_FILES;
 }
 
 public synchronized void setNUM_FILES(long nUM_FILES) {
  NUM_FILES = nUM_FILES;
 }
 
 public synchronized long getNUM_FOLDERS() {
  return NUM_FOLDERS;
 }
 
 public synchronized void setNUM_FOLDERS(long nUM_FOLDERS) {
  NUM_FOLDERS = nUM_FOLDERS;
 }
 
 public synchronized void increaseNUM_FOLDERS_byOne() {
  NUM_FOLDERS = NUM_FOLDERS + 1;
 }
 
 public synchronized void increaseNUM_FILES_byOne() {
  NUM_FILES = NUM_FILES +1;
 }
 
 public synchronized void increaseTOTAL_SIZE(long val) {
  TOTAL_SIZE = TOTAL_SIZE + val;
 }
 
   
}

File: ThreadedFolderSizeCalculator

package com.giri.interview;

import java.io.File;

public class ThreadedFolderSizeCalculator implements Runnable{
 
 //our thread name
 private String name;
 
 // the file object
 private File file;
 
 // constructor
 public ThreadedFolderSizeCalculator(String n) {
  name = n;
 }
 
 // constructor
 public ThreadedFolderSizeCalculator(String n, File f) {
  file = f;
  name = n;
 }
 
 // actual function that is executed - which is - the thread calculates the specified directory size
 @Override
 public void run() {
  System.out.println("\n [Thread-"+name+"] is running !");
  
  Utils.getFolderSize(file);
  
  System.out.println("\n [Thread-"+name+"] is done !");
 }
 
 @Override
 public String toString() {
  return name;
 }

}

File: Utils

package com.giri.interview;

import java.awt.List;
import java.io.File;
import java.io.FileFilter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;


public class Utils {
 
 // this has the entire folder/directory list
 public static LinkedList utils_linkedlist = new LinkedList();
 
 // this fetches the folder size - for a given directory
 // if a directory called "keshav" (Directory points to "/home/keshav") and 
 // inside that if there are 3 files and 2 directories
 // 1. foo.txt - 100 bytes
 // 2. hello.doc - 200 bytes
 // 3. foo.exe - 300 bytes
 // 4. Interviews/      (directory - which may have folders or files inside them)
 // 5. SourceCode/      (directory - which may have files or folders inside them)
 //   Calling the below function on the directory "keshav" should return 100+200+300 = 600 bytes
 public static long getFolderSize(File folder) {
  long totalSize = 0;
  
  System.out.println("\nFolder="+folder.getName());
  
  if(!folder.isDirectory()) {
   return 0;
  }
  
  File[] filesInFolder = folder.listFiles();
  
  for(int i = 0; i< filesInFolder.length; i++ ) {
   
   if(filesInFolder[i].isFile()) {
    MainClass.mainVars.increaseNUM_FILES_byOne();
    totalSize = totalSize + filesInFolder[i].length();
    MainClass.mainVars.increaseTOTAL_SIZE(filesInFolder[i].length());
   }
  }
  System.out.println("\nSize of the current folder ("+folder.getName()+")="+totalSize);
  System.out.println("\nCurrent Total File Size="+MainClass.mainVars.getTOTAL_SIZE());
  System.out.println("\n-------------------------");
  return totalSize;
 }
 
 // this recursive function - populates our list - with all directories and sub-directories
 public static LinkedList getAllFoldersAndSubFolders(File dirPath) {
  
  File[] files = dirPath.listFiles();
  for(File f : files ) {
   if(f.isDirectory()) {
    utils_linkedlist.add(f);
    getAllFoldersAndSubFolders(f);
   }
  }
  return utils_linkedlist;
 }
}

Monday, November 5, 2012

Java: Arrays vs ArrayList

Difference between ArrayList and Array in Java

In Java an Array is always of fixed size. The size has to be defined at the initializing time of the array. The number of the rows is a must for any array, though the number of columns may be specified later. By using Array, there is comparatively less flexibility, as the size need to be known before hand. And if you initialize an array that is too long, then it results in wastage of precious memory of the heap. The Garbage Collector then has a tough time maintaining the memory for other resources.


On the other hand, the ArrayList is dynamic in nature. It provides for automatic resizing of the List. Moreover you need not specify the size at the beginning of the initialization part. The ArrayList is therefore much more widely used as compared to an Array in Java. ArrayList is and extension of the List Interface. So it is a part of the Collections framework.


Talking about the drawbacks of ArrayList, then there is probably only one, and that is typecasting. When an Object is added to an ArrayList it goes inside as an Object, and so when it is retrieved back, then it needs to be typecast back into the original Object.


The Arrays have a positive point in this regard, that is an array is always of a particular type that is an array of ints, or an array of Strings, etc. So when data is retrieved back from an Array, then no typecasting is required.

Threads in Java

Here is a small demo of how to use threading capabilities in Java

File : ThreadModule.java

package com.giri.thread;

public class ThreadModule implements Runnable {
 
 private String threadName;
 private Thread t;
 private boolean suspendFlag;
 
 
 public Thread getT() {
  return t;
 }

 public void setT(Thread t) {
  this.t = t;
 }

 public String getThreadName() {
  return threadName;
 }

 public void setThreadName(String threadName) {
  this.threadName = threadName;
 }

 public ThreadModule(String name) {
  this.threadName = name;
  t = new Thread(this, name);
  System.out.println("\n ThreadModule() : New Thread : " + t);
  suspendFlag = false;
  t.start();
 }
 
 // this is the entry point for the thread
 @Override
 public void run() {
  
  System.out.println("\n run() block called for thread " + threadName + " ! Running... \n\n");
  try {
   for(int i=1; i<20; i++) {
    System.out.print("\n Value="+i+"["+this.threadName+"]");
    Thread.sleep(800);
    synchronized(this) {
     while(suspendFlag) {
      wait();
     }
    }
   }
  } catch(Exception e) {
   System.out.println("\nError in doing the run() of the thread : " + threadName);
   e.printStackTrace();
  }
  System.out.println("\n Exiting thread: " + threadName + "\n\n");
  
 }
 
 public void mySuspend() {
  System.out.println("\n\n mySuspend() called for thread " + threadName + " !");
  suspendFlag = true;
 }
 
 synchronized void myResume() {
  System.out.println("\n\n myResume() called for thread " + threadName + " !");
  suspendFlag = false;
  notify();
 }
 

}

File : ThreadDemo.java

package com.giri.thread;

public class ThreadDemo {

 public static void main(String[] args) {
  ThreadModule t1 = new ThreadModule(" { First  } ");
  ThreadModule t2 = new ThreadModule(" { Second } ");
  
  try {
   Thread.sleep(5000);
   t1.mySuspend();
   System.out.println("\n [ThreadDemo.java] : Suspending thread: " + t1.getThreadName());
   Thread.sleep(5000);
   t1.myResume();
   System.out.println("\n [ThreadDemo.java] : Resuming thread: " + t1.getThreadName());
   
   t2.mySuspend();
   System.out.println("\n [ThreadDemo.java] : Suspending thread: " + t2.getThreadName());
   Thread.sleep(5000);
   t2.myResume();
   System.out.println("\n [ThreadDemo.java] : Resuming thread: " + t2.getThreadName());
   
  } catch(Exception e) {
   System.out.println("\n Error in the main try {} block !");
   e.printStackTrace();
  }
  
  try {
   System.out.println("\n Waiting for the threads to finish...");
   t1.getT().join();
   t2.getT().join();
  } catch(Exception e) {
   System.out.println("\nError in doing a join() of the threads !");
   e.printStackTrace();
  }
  
  System.out.println("\n Done ! Exiting Main Thread..!");

 }
}

Output


 ThreadModule() : New Thread : Thread[ { First  } ,5,main]

 run() block called for thread  { First  }  ! Running... 



 Value=1[ { First  } ]
 ThreadModule() : New Thread : Thread[ { Second } ,5,main]

 run() block called for thread  { Second }  ! Running... 



 Value=1[ { Second } ]
 Value=2[ { First  } ]
 Value=2[ { Second } ]
 Value=3[ { First  } ]
 Value=3[ { Second } ]
 Value=4[ { First  } ]
 Value=4[ { Second } ]
 Value=5[ { First  } ]
 Value=5[ { Second } ]
 Value=6[ { Second } ]
 Value=6[ { First  } ]
 Value=7[ { First  } ]
 Value=7[ { Second } ]

 mySuspend() called for thread  { First  }  !

 [ThreadDemo.java] : Suspending thread:  { First  } 

 Value=8[ { Second } ]
 Value=9[ { Second } ]
 Value=10[ { Second } ]
 Value=11[ { Second } ]
 Value=12[ { Second } ]
 Value=13[ { Second } ]

 myResume() called for thread  { First  }  !

 [ThreadDemo.java] : Resuming thread:  { First  } 

 Value=8[ { First  } ]

 mySuspend() called for thread  { Second }  !

 [ThreadDemo.java] : Suspending thread:  { Second } 

 Value=9[ { First  } ]
 Value=10[ { First  } ]
 Value=11[ { First  } ]
 Value=12[ { First  } ]
 Value=13[ { First  } ]
 Value=14[ { First  } ]

 myResume() called for thread  { Second }  !

 [ThreadDemo.java] : Resuming thread:  { Second } 

 Value=14[ { Second } ]
 Waiting for the threads to finish...

 Value=15[ { First  } ]
 Value=15[ { Second } ]
 Value=16[ { First  } ]
 Value=16[ { Second } ]
 Value=17[ { First  } ]
 Value=17[ { Second } ]
 Value=18[ { First  } ]
 Value=18[ { Second } ]
 Value=19[ { First  } ]
 Value=19[ { Second } ]
 Exiting thread:  { First  } 



 Exiting thread:  { Second } 



 Done ! Exiting Main Thread..!