Archive for Java

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) {
            t.interrupt();
        }
        threadVar.clear();
    }

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

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

        Runnable doConstruct = new Runnable() {
            public void run() {
                try {
                    setValue(construct());
                }
                finally {
                    threadVar.clear();
                }

              SwingUtilities.invokeLater(doFinished);
            }
        };

        Thread t = new Thread(doConstruct);
        threadVar = new ThreadVar(t);
        t.start();
    }
}

SwingWorker.java

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

  class ActualTask {
      ActualTask() {
          try {
              Thread.sleep(1000);
          } catch (InterruptedException e) {}
      }
  }
}

Task.java

Advertisements

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.

DataSource setup on Tomcat

Posted in Server with tags , , , on September 21, 2007 by wsjoung

1. create META-INF/context.xml

<?xml version=”1.0″ encoding=”UTF-8″?>
<Context docBase=”e-sports” path=”/e-sports” debug=”0″ reloadable=”true”
source=”org.eclipse.jst.j2ee.server:e-sports”>
<Logger className=”org.apache.catalina.logger.FileLogger”
prefix=”e-sports_log.” suffix=”.txt” timestamp=”true” />
<Resource name=”jdbc/myoracle”
auth=”Container”
type=”javax.sql.DataSource”
driverClassName=”oracle.jdbc.driver.OracleDriver”
factory=”org.apache.tomcat.dbcp.dbcp.BasicDataSourceFactory”
url=”jdbc:oracle:thin:@127.0.0.1:1521:ORA92″
username=”scott”
password=”tiger”
maxActive=”20″
maxIdle=”10″
maxWait=”-1″ />
</Context>

2. test.jsp
<%@ page import=”java.sql.Connection” %>
<%@ page import=”java.sql.ResultSet” %>
<%@ page import=”java.sql.SQLException” %>
<%@ page import=”java.sql.Statement” %>
<%@ page import=”javax.naming.Context” %>
<%@ page import=”javax.naming.InitialContext” %>
<%@ page import=”javax.naming.NamingException” %>
<%@ page import=”javax.sql.DataSource” %>

<%
Context ctx = null;
DataSource source = null;
Connection con = null;

try {
ctx = new InitialContext();
ctx = (Context) ctx.lookup(“java:comp/env”);
source = (DataSource) ctx.lookup(“jdbc/myoracle”);

System.out.println(“DataSource ===========================”+ source);

con = source.getConnection();
System.out.println(“Connection ============================”+ con);
} catch (NamingException ne) {
ne.printStackTrace();
}
%>

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

or

keytool -selfcert

and

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

Eclipse web.xml validation problem

Posted in Software with tags , , , on February 7, 2007 by wsjoung

The problem is because of “http://java.sun.com/xml/ns/j2ee/j2ee_1_4.xsd&#8221; fil, it points ibm’s schema instead of Sun’s

Window -> Preferences… -> Web and XML -> XML Catalog

URI : http://java.sun.com/xml/ns/j2ee/j2ee_web_services_client_1_1.xsd
Key Type : Schema Location
Key : http://www.ibm.com/webservices/xsd/j2ee_web_services_client_1_1.xsd

Thanks Carey Evans

Java SE 6 Key Features

Posted in Java with tags , on December 13, 2006 by wsjoung

New Security Features and Enhancements

  • Native platform Security (GSS/Kerberos) integration.
  • Java Authentication and Authorization Service (JAAS) login module that employs LDAP authentication
  • New Smart Card I/O API
    » Find out more


Integrated Web Services

  • New API for XML digital signature services for secure web services
  • New Client and Core Java Architecture for XML-Web Services (JAX-WS) 2.0 APIs
  • New support for Java Architecture for XML Binding (JAXB) 2.0
    » Find out more


Scripting Language Support (JSR 223)

  • New framework and API for scripting languages
  • Mozilla Rhino engine for JavaScript built into the platform
    » Find out more


Enhanced Management and Serviceability

  • Improved JMX Monitoring API
  • Runtime Support for dTrace (Solaris 10 and future Solaris OS releases only)
  • Improved memory usage analysis and leak detection
    » Find out more


Increased Developer Productivity

  • JDBC 4.0 support (JSR 221)
  • Significant library improvements
  • Improvements to the Java Platform Debug Architecture (JPDA) & JVM Tool Interface


Improved User Experience

  • look-and-feel updates to better match underlying operating system
  • Improved desktop performance and integration
  • Enhanced internationalization support

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.