Showing posts with label Java. Show all posts
Showing posts with label Java. Show all posts

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/

Wednesday, July 4, 2007

Java: Send a Http Request

Here is the sample code for sending a http request using Java Library

===================================================
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.io.OutputStream;

public class HttpTest extends Thread{
public static void main(String[] args) {
try {
URL u = new URL("http://192.168.1.10:80/http/incoming");
HttpURLConnection uc = (HttpURLConnection) u.openConnection();
uc.setRequestMethod("POST");
uc.setRequestProperty("Host" , "1.1.1.1");
uc.setRequestProperty("Accept", "*/*");
uc.setRequestProperty("Content-Type", "application/octet-stream");
uc.setDoOutput(true);
uc.connect();
OutputStream os = uc.getOutputStream();
os.write("123456".getBytes());
uc.disconnect();
System.out.println("Response code: " + uc.getResponseCode());
String key = null;
for (int i=1; ((key = uc.getHeaderFieldKey(i))!=null); i++) {
System.out.println(key + ": " + uc.getHeaderField(key));
}
} catch (IOException e) {
e.printStackTrace();
}
}
}

===================================================

In my opinion, if it was a very simple application such as only sending a simple message via HTTP protocol, it was better to implement by yourself because it is more flexible and more efficient. I did it in my current project. However, there is a risk for implement by yourself. It's that Java Sock library is not thread safe. Be careful.

Here is a HTTP message sample:
==============================================
POST /http/incoming HTTP/1.1
Accept: */*
Content-Length: 6
Host: 192.168.1.10:80
Content-Type: application/octet-stream
Date: 2007-07-04 12:12:12

123456
==============================================

Wednesday, June 27, 2007

Getting environment values

There are two ways for getting the environment values in Java:

1. We can use System.getProperty(systemPropertyString) to retrieve the values, such as java.version, java.home, os.name, user.name, user.home, user.dir, java.io.tmpdir etc;

2. Use System.getenv to enumerate all the system environment:

==============================================================
import java.util.*;

public class ListEnv {
public static void listAllEnv(){
Map variables = System.getenv();
Set variableNames = variables.keySet();

Iterator nameIterator = variableNames.iterator();

for(int index=0; index < variableNames.size(); index++){
String name = (String) nameIterator.next();
String value = (String) variables.get(name);
System.out.println(name + "=" + value);
}
}

public static void main(String[] args) {
listAllEnv();
}
}
==============================================================

Tuesday, June 19, 2007

Java mail SMTP sample code

This sample code demonstrates the minimum Java code for using regular SMTP service and GMail SMTP service.

First of all, we download the Java Activation Framework and JavaMail packages.

Sample code is followed:

===============================================================

import java.security.Security;
import java.util.Date;
import java.util.Properties;

import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.NoSuchProviderException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class AlarmMail {
public void sendGMail() {
Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";

// Get a Properties object, and set the parameters of mail service
Properties props = new Properties();
props.setProperty("mail.smtp.host", "smtp.gmail.com");
props.setProperty("mail.smtp.socketFactory.class", SSL_FACTORY);
props.setProperty("mail.smtp.socketFactory.fallback", "false");
props.setProperty("mail.smtp.port", "465");
props.setProperty("mail.smtp.socketFactory.port", "465");
props.put("mail.smtp.auth", "true");
final String username = "shuzhanqiang@gmail.com";
final String password = "******";
Session session = Session.getDefaultInstance(props,
new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});

session.setDebug(true);

// -- Create a new message --
Message msg = new MimeMessage(session);

// -- Set the FROM, TO, and Mail contain fields --
try {
msg.setFrom(new InternetAddress(username));
msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(
"shu_zhq@yahoo.com", false));
msg.setSubject("Hello");
msg.setText("Hello");
msg.setSentDate(new Date());
System.out.println("Start sending");
Transport.send(msg);
} catch (AddressException e) {
e.printStackTrace();

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

}

System.out.println("Message sent.");
}

private String mailhost = "mail.abc.com";
private String user = "qiang@abc.com";
private String password = "123456";
private String from, to, cc, bcc;
private String subject;
private String text;
private String mailer = "smtpsend";
private boolean ssl = false;
private boolean verbose;

public void sendMsg() {
try {
InternetAddress[] address = null;

// Get a Properties object, and set the parameters of mail service
Properties props = new Properties();
props.put("mail.smtp.host", mailhost);
props.setProperty("mail.smtp.port", "25");
props.put("mail.smtp.auth", "true");
javax.mail.Session sessmail = javax.mail.Session.getInstance(props);
sessmail.setDebug(true);
MimeMessage msg = new MimeMessage(sessmail);
msg.setFrom(new InternetAddress(user));

address = InternetAddress.parse(to, false);
msg.setRecipients(Message.RecipientType.TO, address);

msg.setSubject(subject);
msg.setSentDate(new Date());
msg.setText(text, "UTF-8");
Transport transport = sessmail.getTransport("smtp");
transport.connect(mailhost, user, password);
transport.sendMessage(msg, msg.getAllRecipients());
transport.close();
} catch (AddressException e) {
e.printStackTrace();

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

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

}

}


public static void main(String[] args) {
AlarmMail am = new AlarmMail();
am.setFrom("shu_zhq@gmail.com");
am.setTo("shu_zhq@yahoo.com");
am.setSubject("Help");
am.setText("Help.");
am.sendMsg();

am.sendGMail();
}

public String getBcc() {
return bcc;

}

public void setBcc(String bcc) {
this.bcc = bcc;

}

public String getCc() {
return cc;

}

public void setCc(String cc) {
this.cc = cc;

}

public String getFrom() {
return from;

}

public void setFrom(String from) {
this.from = from;

}

public String getMailer() {
return mailer;

}

public void setMailer(String mailer) {
this.mailer = mailer;

}

public String getMailhost() {
return mailhost;

}

public void setMailhost(String mailhost) {
this.mailhost = mailhost;

}

public String getPassword() {
return password;

}

public void setPassword(String password) {
this.password = password;

}

public boolean isSsl() {
return ssl;

}

public void setSsl(boolean ssl) {
this.ssl = ssl;

}

public String getSubject() {
return subject;

}

public void setSubject(String subject) {
this.subject = subject;

}

public String getText() {
return text;

}

public void setText(String text) {
this.text = text;

}

public String getTo() {
return to;

}

public void setTo(String to) {
this.to = to;

}

public String getUser() {
return user;

}

public void setUser(String user) {
this.user = user;

}

public boolean isVerbose() {
return verbose;

}

public void setVerbose(boolean verbose) {
this.verbose = verbose;

}

}