Posts Tagged ‘java’

Zombie killer on linux or how to end the financial crisis?

Monday, January 5th, 2009

Have you ever tried to identify zombie processes on your server? The zombie identification application is written in java and could be used on linux. It is very easy to adopt the code for other operating systems. The zombie killer has been originally written to kill zombie processes on Oracle Application Server.

Go to the end if you are only interested how to end the financial crisis…;)

Application has two parameters:

  • the process name is used to find out only the specific processes. In my example the parameter value is frmweb. Parameter value frmweb is used to limit the application to check only the cpu time spent by oracle forms processes
  • the cpu time used by process is used to define the maximum allowed cpu time spent by particular process

How does it works:

  1. Application first get all the processes in desired format.
    1. ps -eo (to see every process with a user defined format)
    2. ps -eo user, pid, time, command (to see every process in format user, process id, time spent by process and command)
  2. Application checks only the processes where the parameter value for process name match the command (parameter value is in command string)
  3. Application parses the process values and check the cpu time spent by the process. Process is terminated if the cpu time spent is greater than the parameter value for cpu time.

Application could be run using crontab each 15 minutes. Example below shows how to kill oracle forms sessions which exceeds more than 1000 seconds of cpu time
0,15,30,45 * * * * /usr/java/jdk1.6.0_11/bin/java -cp . ZombieKiller frmweb 1000


import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;

/**
*
* @author http://www.javanus.com/blogs
*/

public class ZombieKiller {
public static String getUnparsedProcessList() {
InputStream in = null;
InputStream buffer = null;
Reader reader = null;
try {
//get all processes
Process p = Runtime.getRuntime().exec("ps -eo user,pid,time,command --sort stime");
in = p.getInputStream();
buffer = new BufferedInputStream(in);
reader = new InputStreamReader(buffer);
char[] charr = new char[1024];
StringBuffer strbuff = new StringBuffer();
while(true) {
int r = reader.read(charr);
if(r<=0) {
break;
}
strbuff.append(charr, 0, r);
}
return strbuff.toString();
}catch(IOException e) {
//todo - error handling
e.printStackTrace();
}
return null;
}


/**
* @param args the command line arguments
*/
public static void main(String[] args) throws IOException {
System.out.println("Check out http://www.javanus.com/blogs && http://www.javanus.com/blog");
if (args.length==0) {
System.out.println("Usage: java -classpath . ZombieKiller ");
return;
}
String ls_processName = args[0];

int li_maxSecAllow = 9999;
//Is the maximum number of seconds defined
if (args.length>1 && args[1] != null) {
li_maxSecAllow = Integer.parseInt(args[1]);
}
String ls_procesi = getUnparsedProcessList();
while (ls_procesi.indexOf("\n")>=0) {
String ls_rowValue = ls_procesi.substring(0, ls_procesi.indexOf("\n"));
//parse row if process name match
if (ls_rowValue.indexOf(ls_processName)>=0) {
//user
String ls_user = ls_rowValue.substring(0, ls_rowValue.indexOf(" "));
ls_rowValue = ls_rowValue.substring(ls_rowValue.indexOf(" ")+1, ls_rowValue.length()).trim();
//pid
String ls_pid = ls_rowValue.substring(0, ls_rowValue.indexOf(" "));
ls_rowValue = ls_rowValue.substring(ls_rowValue.indexOf(" ")+1, ls_rowValue.length()).trim();
//time
String ls_time = ls_rowValue.substring(0, ls_rowValue.indexOf(" "));
//System.out.println(ls_time);
ls_time = ls_time.substring(ls_time.indexOf(":")+1, ls_time.length()).trim();
String ls_minute = ls_time.substring(0, ls_time.indexOf(":"));
//System.out.println("ls_minute="+ls_minute);
ls_time = ls_time.substring(ls_time.indexOf(":")+1, ls_time.length()).trim();
String ls_sek = ls_time;
//cmd
ls_rowValue = ls_rowValue.substring(ls_rowValue.indexOf(" ")+1, ls_rowValue.length()).trim();
String ls_cmd = ls_rowValue;//.substring(0, ls_rowValue.indexOf(" "));
//ali je noter ip adressa
int li_spentCputTime = Integer.parseInt(ls_minute)*60+Integer.parseInt(ls_sek);
//System.out.println(ls_cmd);
ls_rowValue = ls_rowValue.substring(ls_rowValue.indexOf(" ")+1, ls_rowValue.length()).trim();
//should I terminate this session?
if (li_spentCputTime>li_maxSecAllow) {
Process p = Runtime.getRuntime().exec("kill -9 " + ls_pid);
System.out.println("Process " + ls_pid + " has been successfully terminated!");
}
}
ls_procesi = ls_procesi.substring(ls_procesi.indexOf("\n")+1, ls_procesi.length());
}

}
}

It would be nice to end the financial crisis on the same way. I suggest to use kill -9 42 to end the economic depression. 42???

Do you find this post useful? Do not hesitate to leave a reply! Go to the bottom of this page.

how to get a ProxyEnable value from windows registry in java

Thursday, October 9th, 2008
I have developed a webservice which checks if a new version of software exists. Webservice works fine if the user does not use a proxy otherwise it raises an error “connection timeout….”.
 
If the user uses a proxy then the program should read a proxy settings first. I have found a lot of examples how to read a proxy settings from windows registry and this is not a problem at all (search for JavaRegistryHack).
 
The problem occurs when a user has VPN. In my example I use a proxy when I am connected to VPN but I do not have a proxy when I do not use VPN. I always get proxy address and proxy port regardless of the value in check box “Use a proxy server for your LAN”.
 
 
How to find out if the value of upper checkbox is selected? The answer is in a registry value ProxyEnable. ProxyEnable is set to 0 if a proxy is not selected and it has a value 1 if the proxy is used.
 
But there is another problem. There are two different types of values in registry: REG_SZ and REG_DWORD. It is very easy to read a value for REG_SZ but I have wasted a lot of time to find out how to read a value for REG_DWORD type. Below is a function which is used to read a ProxyEnable. You can use this function also for other REG_DWORD values.
import java.io.*;
public class ProxyEnable {
  private static final String REGQUERY_UTIL = “reg query “;
  private static final String REGDWORD_TOKEN = “REG_DWORD”;
  private static final String PROXYENABLE = REGQUERY_UTIL +
   “\”HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings\”" 
   + ” /v ProxyEnable”;
  public static String getProxyEnable() {
    try {
      Process process = Runtime.getRuntime().exec(PROXYENABLE);
      StreamReader reader = new StreamReader(process.getInputStream());
      reader.start();
      process.waitFor();
      reader.join();
      String result = reader.getResult();
      int p = result.indexOf(REGDWORD_TOKEN);
      if (p == -1)
         return null;
      // value is 0×0 or 0×1
      String temp = result.substring(p + REGDWORD_TOKEN.length()).trim();
      temp = temp.substring(2, temp.length());
      return Integer.toString
          ((Integer.parseInt(temp)));
    }
    catch (Exception e) {
      return null;
    }
  }
  static class StreamReader extends Thread {
    private InputStream is;
    private StringWriter sw;
    StreamReader(InputStream is) {
      this.is = is;
      sw = new StringWriter();
    }
    public void run() {
      try {
        int c;
        while ((c = is.read()) != -1)
          sw.write(c);
        }
        catch (IOException e) { ; }
      }
    String getResult() {
      return sw.toString();
    }
  }
  public static void main(String s[]) {
    System.out.println(“Proxy Enable : ” + getProxyEnable());
  }
}
I hope this will help someone oneday somewhere…

Do you find this post useful? Do not hesitate to leave a reply! Go to the bottom of this page.

My first webservice deployed to javanus.com

Saturday, August 23rd, 2008

Hi,

Today I will try to deploy my first webService on www.javanus.com. I will not go into detail. You can read more about this example at javaPassion http://www.javapassion.com/handsonlabs/wshelloworld/.

First I create a new project and I select Web Application for project type. I choose Apache Tomcat as a Server. I am wondering if it would works if I select the Glassfish and deploy to the Tomcat? Anybody knows?

I create a new class Hello.

package mypackage;
import javax.jws.WebService;
/**
 *
 * @author sang
 */
@WebService()
public class Hello {    // Business method we want to expose as
    // Web service operation
    public String sayHello(String name) {
        return “Hello ” + name + “!”;
    }
}

I build and deploy webService to localhost. I check out the WSDL:

http://localhost:8084/HelloWebService/HelloService?wsdl

It works fine till know. Ok, I will try to deploy this webService on web. Unfortunatelly it does not work I will contact my web hosting support. Helpdesk from www.dailyrazor.com solved my issue. I am satisfied with their support.

In the second step I develop web client so I create a new Project HelloWebServiceClient as Java application. Use right click on the project to add a new Web Service Client File. See the picture below.

I do not use URL from my localhost. I decide to take the real one http://javanus.com/HelloWebService/HelloService?WSDL

There was no problem with client generation. In the next step I generate the code in the Main class. Netbeans is great, just click in the main class, right click for popup menu and select Web Service Client Resources -> Call Web Service Operation.

I get all information about web service methods!!! I select sayHello. Code is added to Main class.

    try { // Call Web Service Operation
       mypackage.HelloService service = new mypackage.HelloService();
       mypackage.Hello port = service.getHelloPort();
       // initialize WS operation arguments here
       java.lang.String arg0 = “Java is a great language!”;
       // process result here
       java.lang.String result = port.sayHello(arg0);
       System.out.println(“Result = “+result);
    } catch (Exception ex) {
       // TODO handle custom exceptions here
    }

The last step. Do you think everything will be ok?

Let check it out. I run the class.

B I N G O !!!

It is very easy to develop system tray in java

Saturday, August 23rd, 2008
I have found a very good example on google how to develop system tray functionallity in java. Please check it out Michael Nascimento blog

Unfortunatelly the code could not be compiled without additional imports. Missing imports are included into Michael code.

Here are some pictures:

1.System tray pop up after execution java -cp . SysTray

 System tray

2.System tray tooltip

3.System tray popup menu

I already see different useful situations.

Here is Michael code with missing imports. I do the following modifications: add another menu item an change sleep time to 2 seconds

import java.awt.HeadlessException;
import java.awt.Image;
import java.awt.MenuItem;
import java.awt.Panel;
import java.awt.PopupMenu;
import java.awt.SystemTray;
import java.awt.TrayIcon;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import javax.swing.Icon;
import javax.swing.JOptionPane;
import javax.swing.plaf.metal.MetalIconFactory;

public class SysTray {
   public static void main(String[] args) throws Exception {
      TrayIcon icon = new TrayIcon(getImage(), “Java application as a tray icon”,
            createPopupMenu());
      icon.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent e) {
            JOptionPane.showMessageDialog(null, “Hey, you activated me!”);
         }
      });
      SystemTray.getSystemTray().add(icon);

      Thread.sleep(2000);

      icon.displayMessage(“Attention”, “Please click here”,
            TrayIcon.MessageType.WARNING);
   }

   private static Image getImage() throws HeadlessException {
      Icon defaultIcon = MetalIconFactory.getTreeHardDriveIcon();
      Image img = new BufferedImage(defaultIcon.getIconWidth(),
            defaultIcon.getIconHeight(), BufferedImage.TYPE_4BYTE_ABGR);
      defaultIcon.paintIcon(new Panel(), img.getGraphics(), 0, 0);

      return img;
   }

   private static PopupMenu createPopupMenu() throws HeadlessException {
      PopupMenu menu = new PopupMenu();

      MenuItem run = new MenuItem(“Run”);
      menu.add(run);
     
      MenuItem exit = new MenuItem(“Exit”);
      exit.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent e) {
            System.exit(0);
         }
      });
      menu.add(exit);

      return menu;
   }
}