Friday, September 14, 2007

Java: highlight and show a particular row/cell in JTable inside JScrollPane

1. When we want to highlight one particular row in a JTable, we could call:
getTable().setRowSelectionInterval(i, i);


2. When we want to show a particular row/cell in a JTable inside a JScrollPane, we could call,

getTable().scrollRectToVisible(getTable().getCellRect(row, 0, true));

But it doesn't work so well if we overwrite the DefaultTableCellRenderer.

Java: create a table that a cell can contains multilines.

By default, the container in a JTable cell for a string is a JTextField object that only show all the content in one line. Sometimes, we need to present multi-lines in one cell, so we have to overwrite the cell handle object. Here is a sample for it.

The sequence is that overwrite the abstractTableModel, then overwrite the DefaultTableCellRender.

private DefaultTableModel getLogModel(){
if(logTblModel == null){
logTblModel = new DefaultTableModel() {
public boolean isCellEditable(int row, int colum) {
return false;
}
};

for(TITLE t : TITLE.values()){
logTblModel.addColumn(t.getName());
}
}
return logTblModel;
}


private JTable getTblLogRec() {
if (tblLogRec == null) {
tblLogRec = new JTable(getLogModel());
tblLogRec.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
tblLogRec.getColumn(TITLE.TIME.getName()).setPreferredWidth(100);
tblLogRec.getColumn(TITLE.LEVEL.getName()).setPreferredWidth(50);
tblLogRec.getColumn(TITLE.MESSAGE.getName()).setPreferredWidth(375);
tblLogRec.getColumnModel().getColumn(TITLE.MESSAGE.ordinal()).setCellRenderer(new DefaultTableCellRenderer() {
private JTextPane _sumaryTxtPane;
public Component getTableCellRendererComponent(
JTable table, Object value, boolean isSelected,
boolean hasFocus, int row, int column) {
getSumaryTxtPane().setText((String) value);
TableColumnModel columnModel = table
.getColumnModel();
getSumaryTxtPane().setSize(
columnModel.getColumn(column).getWidth(),
100000);
int heightWanted = (int) getSumaryTxtPane()
.getPreferredSize().getHeight();
if (heightWanted != table.getRowHeight(row)) {
table.setRowHeight(row, heightWanted);
}
if(isSelected){
getSumaryTxtPane().setBackground(getTblLogRec().getSelectionBackground());
}else{
getSumaryTxtPane().setBackground(getTblLogRec().getBackground());
}
return getSumaryTxtPane();
}

private JTextPane getSumaryTxtPane() {
if (null == _sumaryTxtPane) {
_sumaryTxtPane = new JTextPane();
}
return _sumaryTxtPane;
}
});
}
return tblLogRec;
}
}

Monday, August 6, 2007

Java: catch a system signal

In Java, here is an example to catch a system signal:

=========================================================================
import sun.misc.Signal;
import sun.misc.SignalHandler;
import java.util.Random;

public class SignalTerm {
public static void main(String[] args) {
try{
System.out.println("System start.");
DiagSignalHandler.install("INT");
ThreadGroup tg = new ThreadGroup("AAA");
MyThread mt[] = new MyThread[10];
for(int i=0; i < mt.length; i++){
mt[i] = new MyThread(tg,i);
mt[i].start();
}
for(int i=0; i < mt.length; i++){
mt[i].join();
}
System.out.println("System exit.");

} catch(Exception e){
System.out.println("exception: " + e.getMessage());
e.printStackTrace();
}
}
}

class MyThread extends Thread {
private int threadcnt;
public MyThread(ThreadGroup tg, int n){
super(tg, "My" + n);
threadcnt = n;
}
public void run(){
try {
System.out.println("In thread " + threadcnt);
while(true) sleep(1000);

} catch (InterruptedException e) {
Random ran = new Random();
int rn = ran.nextInt(20);
System.out.println("Thread " + threadcnt + " is shuting down. Please wait " + rn + " seconds.");
try {
sleep(rn* 1000);

} catch (InterruptedException e1) {}
System.out.println("Thread " + threadcnt + " exit.");
}
}
}

//Diagnostic Signal Handler class definition
class DiagSignalHandler implements SignalHandler {
private SignalHandler oldHandler;

// Static method to install the signal handler
public static DiagSignalHandler install(String signalName) {
Signal diagSignal = new Signal(signalName);
DiagSignalHandler diagHandler = new DiagSignalHandler();
diagHandler.oldHandler = Signal.handle(diagSignal,diagHandler);
return diagHandler;
}

// Signal handler method
public void handle(Signal sig) {
System.out.println("Diagnostic Signal handler called for signal "+sig);
try {
// Output information for each thread
Thread[] threadArray = new Thread[Thread.activeCount()];
int numThreads = Thread.enumerate(threadArray);
System.out.println("Current threads:");
for (int i=0; i < numThreads; i++) {
System.out.println(" "+threadArray[i] + ", " + threadArray[i].getThreadGroup().getName());
if(threadArray[i].getThreadGroup().getName().equalsIgnoreCase("AAA")){
threadArray[i].interrupt();
}
}

for (int i=0; i < numThreads; i++) {
if((threadArray[i] != null) && (threadArray[i].getThreadGroup() != null) &&
(threadArray[i].getThreadGroup().getName().equalsIgnoreCase("AAA"))){
threadArray[i].join();
}
}

// Chain back to previous handler, if one exists
if ( oldHandler != SIG_DFL && oldHandler != SIG_IGN ) {
oldHandler.handle(sig);
}

} catch (Exception e) {
System.out.println("Signal handler failed, reason "+e);
e.printStackTrace();
}
}
}
=========================================================================

Heinz[2] mentioned the signal lists in different OSs:
Windows: ABRT, FPE, ILL, INT, SEGV, TERM

Solaris: ABRT, ALRM, BUS, CHLD, CONT, EMT, FPE, HUP, ILL, INT, IO, KILL, PIPE, POLL, PROF, PWR, QUIT, SEGV, STOP, SYS, TERM, TRAP, TSTP TTIN, TTOU, URG, USR1, USR2, VTALRM, WINCH, XCPU, XFSZ

References:

Chris White, Revelations on Java signal handling and termination, http://www.ibm.com/developerworks/ibm/library/i-signalhandling/
Dr. Heinz M. Kabutz, Switching off OS signals at runtime,
http://www.roseindia.net/javatutorials/
switching_off_os_signals_at_runtime.shtml

Java: construct a class with parameters in reflection

Here is a simple example for constructing a object with two parameters in Java Reflection:

=====================================================================
import java.lang.reflect.*;

public class LoadParamObject {
public LoadParamObject() {}

public LoadParamObject(int a, String b) {
System.out.println("a = " + a + " b = " + b);
}

public static void main(String args[]) {
try {
Class cls = Class.forName("LoadParamObject");
Class partypes[] = new Class[2];
partypes[0] = Integer.TYPE;
partypes[1] = String.class;
Constructor ct = cls.getConstructor(partypes);
Object arglist[] = new Object[2];
arglist[0] = new Integer(37);
arglist[1] = new String("BBB");
Object retobj = ct.newInstance(arglist);

} catch (Throwable e) {
System.err.println(e);
}
}
}
=====================================================================

The detail explanation please read below:
http://java.sun.com/developer/technicalArticles/ALT/Reflection/

Thursday, July 12, 2007

Getting the program name that is listening on a specified port

Sometimes we need to find out which program is listening on a specified port.

In Linux, we can use:
netstat -natlp

-n, --numeric don't resolve names
-a, --all, --listening display all sockets (default: connected)
< Socket >={-t|--tcp} {-u|--udp} {-w|--raw} {-x|--unix} --ax25 --ipx --netrom
-l, --listening display listening server sockets
-p, --programs display PID/Program name for sockets

In windows, we can use fport which can be downloaded in the internet.

Its official website: http://www.foundstone.com/us/resources-free-tools.asp

Friday, July 6, 2007

Java: a simple HTTP server sample

In JDK 6, it is very easy to create a HTTP server. Here is a sample in SDK 6.

===================================================
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import com.sun.net.httpserver.spi.HttpServerProvider;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;


public class SimpleHttpServer {
public static void main(String[] args) throws Exception{
HttpServerProvider httpServerProvider = HttpServerProvider.provider();
InetSocketAddress addr = new InetSocketAddress(8888);
HttpServer httpServer = (HttpServer)httpServerProvider.createHttpServer(addr, 1);
httpServer.createContext("/mydemo/", new MyHttpHandler());
httpServer.setExecutor(null);
httpServer.start();
System.out.println("started");
}

static class MyHttpHandler implements HttpHandler{
public void handle(HttpExchange httpExchange) throws IOException {
String response = "Hello world!";
httpExchange.sendResponseHeaders(200, response.length());
OutputStream out = httpExchange.getResponseBody();
out.write(response.getBytes());
out.close();
}
}
}
===================================================

Website visited statistics

For counting the visited amount, first of all, add one configuration in config/environment.rb
RAILS_DEFAULT_LOGGER = Logger.new("#{RAILS_ROOT}/log/#{RAILS_ENV}.log", "daily")

1. get the request statistics
cat production.log.20070702|grep "200 OK"|wc -l

2. get the URL visited statistics
cat production.log.20070702 | grep "200 OK" | awk '{print $17}'|sort|uniq -c | sort -r -n > stat.log