Archive for the Programming Category

SwingWorker not on Java 6.0

Posted in Java, Programming with tags , on April 24, 2008 by wsjoung

SwingWorker is useful when a time-consuming task has to be performed following a user-interaction event (for example, parsing a huge XML File, on pressing a Button). The most straightforward way to do it is :

 private Document doc;
 JButton button = new JButton("Open XML");
 button.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
       doc = loadXML();

This will work, but unfortunately, the loadXML() method will be called in the same thread as the main Swing thread, so if the method needs time to perform, the GUI will freeze during this time.

package com.wsjoung.demo;
import javax.swing.SwingUtilities;

public abstract class SwingWorker {
    // see getValue(), setValue()
    private Object value;
    private Thread thread;

    private static class ThreadVar {
        private Thread thread;
        ThreadVar(Thread t) { thread = t; }
        synchronized Thread get() { return thread; }
        synchronized void clear() { thread = null; }

    private ThreadVar threadVar;

    protected synchronized Object getValue() {
        return value;

    private synchronized void setValue(Object x) {
        value = x;

    public abstract Object construct();

    public void finished() {

    public void interrupt() {
        Thread t = threadVar.get();
        if (t != null) {

    public Object get() {
        while (true) {
            Thread t = threadVar.get();
            if (t == null) {
                return getValue();
            try {
            catch (InterruptedException e) {
                // propagate
                return null;

    public SwingWorker() {
        final Runnable doFinished = new Runnable() {
           public void run() { finished(); }

        Runnable doConstruct = new Runnable() {
            public void run() {
                try {
                finally {


        Thread t = new Thread(doConstruct);
        threadVar = new ThreadVar(t);

public class Task{
  public void go() {
      current = 0;
      final SwingWorker worker = new SwingWorker() {
          public Object construct() {
              return new ActualTask();

  class ActualTask {
      ActualTask() {
          try {
          } catch (InterruptedException e) {}

what’s static?

Posted in Programming with tags , , on April 14, 2008 by wsjoung

First of all, the meaning of static in java is embedded or belong to a specific class not to its instance, and therefore there is no such static class.

  • There is no such static class
  • Embedded or belong to a specific class
  • Global variable
  • No need to load and create its instance

Most of methods and variables in Math class are static, because those are not need to be instanced in most of cases. we just use return value of PI or max(int a, int b).

class Bicycle {

private static int numberOfBicycles = 0;
private int id;

public Bicycle() {
id = ++numberOfBicycles;

public static int getNumberOfBicycles() {
return numberOfBicycles;
public int getID() {
return id;

public static void main(String[] args) {
Bicycle b1 = new Bicycle();
Bicycle b2 = new Bicycle();

System.out.println(“static result : “+getNumberOfBicycles());
System.out.println(“static result : “+numberOfBicycles);
System.out.println(“instance result : “+b1.getID());
System.out.println(“instance result : “+b2.getID());

Another characteristic of static is that even if we create instance of a class, jvm does not create instance variables for static resources. in above source code, there is no difference calling b1.getNumberOfBicycles(), b2.getNumberOfBicycles() and just getNumberOfBicycles() or directly numberOfBicycles
that mean we should call static variable with its class name because it’s belong to it. just like Bicycle.numberOfBicycles or in this example, getNumberOfBicycles() because we have a getter.
otherwise get confused.

javamail smtp with Gmail

Posted in Programming with tags , , , , on August 3, 2007 by wsjoung

package com.mycompany.emailsender;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.util.Properties;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

* Servlet implementation class for Servlet: GmailSender
public class GmailSender extends javax.servlet.http.HttpServlet implements javax.servlet.Servlet {
/* (non-Java-doc)
* @see javax.servlet.http.HttpServlet#HttpServlet()
public GmailSender() {

/* (non-Java-doc)
* @see javax.servlet.http.HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub

/* (non-Java-doc)
* @see javax.servlet.http.HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
final String SMTP_HOST_NAME = “”;
final int SMTP_HOST_PORT = 465;
final String SMTP_AUTH_USER = “”;
final String SMTP_AUTH_PWD = “XXXXXX”;
final String SSL_FACTORY = “”;

String emailFromAddress = null;
String[] sendTo = null;
String subject = null;
String content = null;

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {


String address = request.getParameter(“address”);
sendTo = address.split(“;”);

emailFromAddress = request.getParameter(“sender”);
this.subject = request.getParameter(“title”);
this.content = request.getParameter(“content”);

try {
for (int i=0; i<sendTo.length; i++) {
System.out.println(“Sucessfully Sent mail to All Users”);

} catch (Exception e) {System.out.println(e);}

public void sendSSLMessage(String dest) throws MessagingException {

Properties props = new Properties();

props.put(“mail.transport.protocol”, “smtps”);
props.put(“”, SMTP_HOST_NAME);
props.put(“mail.smtps.auth”, “true”);
props.put(“mail.smtps.quitwait”, “false”);

Session mailSession = Session.getDefaultInstance(props);
Transport transport = mailSession.getTransport();

MimeMessage message = new MimeMessage(mailSession);
InternetAddress addressFrom = new InternetAddress(emailFromAddress);
message.setContent(content, “text/html”);

message.addRecipient(Message.RecipientType.TO,new InternetAddress(dest));




Signed java applet

Posted in Programming with tags , , , on May 15, 2007 by wsjoung

Applet Security Basics

Below are the basic facts regarding applet security and Java Plug-in. More detail can be found in the next chapter, How RSA Signed Applet Verification Works in Java Plug-in.

  • All unsigned applets are run under the standard applet security model.
  • If usePolicy IS NOT DEFINED in the java.policy file, then a signed applet has the AllPermission permission if:
    Java Plug-in can verify the signers, and the user, when prompted, agrees to granting the AllPermission permission.
  • If usePolicy IS DEFINED, then a signed applet has only the permissions defined in java.policy and no prompting occurs.

Moreover, note that Java Plug-in now handles certificate management; i.e., the certificate verification task is no longer passed off to the browser.

keytool -genkey -keyalg rsa -alias MyCert
keytool -certreq -alias MyCert
keytool -import -alias MyCert -file VSSStanleyNew.cer


keytool -selfcert


jarsigner AppletName.jar MyCert
jarsigner -verify -verbose -certs AppletName.jar

What is the most popular programming language?

Posted in Programming with tags , on December 28, 2006 by wsjoung

According to TIOBE, currently Java is the most popular language and C/ C++ are second, third placed.

They update top 20 languages every month, based on their rating method. And they use couple of webs searching engines to count on its resources like availability of skilled engineers, courses and third party vendors.

I think accuracy of this result is not important. It should be just for fun especially if you are the programmer who is using one of top 5. And personally I would like to suggest them that those programming languages should be categorized, because to compare Java with SAS or PL/SQL is not make sense. It’s just like comparing orange with apple.

String constant pool

Posted in Programming with tags , , on November 26, 2006 by wsjoung

Everybody knows about String constant pool which is for efficient memory management in java. Basically most of objects are managed on heap area but String object. In most of ordinary application, programmers use String object quite often and this String object quite frequently need to be changed or it occupies large amounts of memory. Therefore instead of managing String object on heap area, they introduced String constant pool.

One of important characteristic of String constant pool is that it doesn’t create same String object if there is already String constant in the pool.

String var1 = “This is String Literal”;
String var2 = “This is String Literal”;

For above two String objects, JVM creates only one object in the String constant pool and for the second string reference variable (var2), it points the string object which is created for var1. In this case, (var1 == var2) is true.

But one thing, people make confused is that. It works only when it encounter on String Literal with double quote.

String var3 = new String(“This is String Literal”);

In this case, a regular object will be created by new keyword on heap area and it will be placed in the String constant pool. Finally it will be assigned to the reference variable, var3. This process is just by passing from String constant pool management. Therefore, (var1 == var3) is false.

Read all files in a directory

Posted in Programming with tags , , , on November 17, 2006 by wsjoung

int fileCount = 0;
File dir = new File(inputDirName);
File[] strFilesDirs = dir.listFiles();

if (strFilesDirs == null) {
System.err.println(inputDirName +” is not valid directory name or there is no pdb file”);
for (int i=0; i
if (strFilesDirs[i].isDirectory()) {
//System.out.println(“Directory: “+strFilesDirs[i]);
} else if (strFilesDirs[i].isFile()) {
//System.out.println(“File: “+strFilesDirs[i]+”(“+strFilesDirs[i].length()+”)”);
fileCount = fileCount + 1;

beside, there is no such method which is changing directory.