links for 2011-08-26

27 08 2011

links for 2011-08-17

18 08 2011

links for 2011-08-16

17 08 2011
  • In CSS, pattern matching rules determine which style rules apply to elements in the document tree. These patterns, called selectors, may range from simple element names to rich contextual patterns. If all conditions in the pattern are true for a certain element, the selector matches the element.

    The case-sensitivity of document language element names in selectors depends on the document language. For example, in HTML, element names are case-insensitive, but in XML they are case-sensitive.

  • <style>
    a:link { color: #000099; text-decoration: none;}
    a:visited { color: #CCC; text-decoration: none;}
    a:active { color: #666; text-decoration: none;}
    a:hover { color: #000; text-decoration: underline;}
  • Once a Swing component has been realized, all code that might affect or depend on the state of that component should be executed in the event-dispatching thread.
  • There are 3 ways to terminate a thread:

    The thread has finished the work it is designed to do, and exits the run() method naturally.
    The thread has received an interruption signal, while doing its work. It decides to not continue with work and exits the run() method. It may also decide to ignore the signal and continue to work.
    The thread has been marked as daemon thread. When the parent thread who created this thread terminates, this thread will be forcefully terminated by the JVM.

  • In a Swing application, most of the processing takes place in a single, special thread called the event dispatch thread.

    This thread becomes active after a component becomes realized : either pack, show, or setVisible(true) has been called. When a top level window is realized, all of its components are also realized. Swing is mostly single-threaded : almost all calls to realized components should execute in the event dispatch thread. The thread-safe exceptions are

    some methods of JComponent : repaint, revalidate, invalidate
    all addXXXListener and removeXXXListener methods
    all methods explicitly documented as thread-safe

  • System.exit should be used with care. The normal method of terminating a program is to terminate all user threads.

    Cases in which System.exit is appropriate :

    utility scripts
    GUI applications, in which the event dispatch user thread is created in the background. Here, the program may be terminated by calling System.exit, or, for example, by setting :


    From Sun's Portability Cookbook :

    "The System.exit method forces termination of all threads in the Java virtual machine. This is drastic….System.exit should be reserved for a catastrophic error exit, or for cases when a program is intended for use as a utility in a command script that may depend on the program's exit code."

  • // :
    // The safe way to stop a thread.
    // From 'Thinking in Java, 3rd ed.' (c) Bruce Eckel 2002
    // See copyright notice in CopyRight.txt.

    import java.util.Timer;
    import java.util.TimerTask;

    class CanStop extends Thread {
    // Must be volatile:
    private volatile boolean stop = false;

    private int counter = 0;

    public void run() {
    while (!stop && counter < 10000) {
    if (stop)
    System.out.println("Detected stop");

    public void requestStop() {
    stop = true;

    public class Stopping {
    public static void main(String[] args) {
    final CanStop stoppable = new CanStop();
    new Timer(true).schedule(new TimerTask() {
    public void run() {
    System.out.println("Requesting stop");
    }, 500); // run() after 500 milliseconds
    } ///:~

  • How to stop a Thread is a perannual question for Java programmers. Finally with the release of Java V5.0 (or V1.5), which incorporates java.util.concurrent, a definitive answer can be given. The answer is you stop a thread by using interrupt(). This article covers some of the background to stopping threads and the suggested alternatives and discusses why interrupt() is the answer. It also discusses interrupting blocking I/O and what else the programmer needs to do to ensure their threads and tasks are stoppable.
  • Here is an example of a utility Stopwatch class which can provide timings for any section of code.

    For measuring the relative execution times of alternate implementations, consider turning off the HotSpot compiler, using java -Xint. This will ensure a uniform environment for the entire duration of a program.

  • Pattern objects compile the regular expressions which are passed to them. If a regular expression is used many times, then this compilation should be performed only once.

    Be wary of the these convenience methods, which compile a regular expression each time they are called:


links for 2011-08-09

10 08 2011
  • import;

    public class Main {
    public static String deserializeString(File file)
    throws IOException {
    int len;
    char[] chr = new char[4096];
    final StringBuffer buffer = new StringBuffer();
    final FileReader reader = new FileReader(file);
    try {
    while ((len = > 0) {
    buffer.append(chr, 0, len);
    } finally {
    return buffer.toString();

  • protected void processLine(String aLine){
    //use a second Scanner to parse the content of each line
    Scanner scanner = new Scanner(aLine);
    if ( scanner.hasNext() ){
    String name =;
    String value =;
    log("Name is : " + quote(name.trim()) + ", and Value is : " + quote(value.trim()) );
    else {
    log("Empty or invalid line. Unable to process.");
    //no need to call scanner.close(), since the source is a String
  • You look at Commons Exec and think "Wow – calling Runtime.exec() is easy and the Apache folks are wasting their and my time with tons of code". Well, we learned it the hard way that using plain Runtime.exec() can be a painful experience […] you are invited to delve into commons-exec and have a look at the hard lessons the easy way…

    CommandLine cmdLine = new CommandLine("AcroRd32.exe");
    HashMap map = new HashMap();
    map.put("file",new File("invoice.pdf"));
    DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler();
    ExecuteWatchdog watchdog=new ExecuteWatchdog(60*1000);
    Executor executor = new DefaultExecutor();
    executor.execute(cmdLine, resultHandler);
    //some time later the result handler callback was invoked so we can safely request the exit value
    int exitValue=resultHandler.waitFor();

  • Apache Commons-exec samples
  • Commons exec provides a PumpStreamHandler which redirects standard output to the Java process' standard output. How can I capture the output of the command into a String? He're what I found:

    import org.apache.commons.exec.CommandLine;
    import org.apache.commons.exec.DefaultExecutor;
    import org.apache.commons.exec.Executor;
    import org.apache.commons.exec.PumpStreamHandler;

    public String execToString(String command) throws Exception {
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    CommandLine commandline = CommandLine.parse(command);
    DefaultExecutor exec = new DefaultExecutor();
    PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream);