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;}
    –>
    </style>
  • 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 :

    JFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)

    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."

  • // : c13:Stopping.java
    // The safe way to stop a thread.
    // From 'Thinking in Java, 3rd ed.' (c) Bruce Eckel 2002
    // http://www.BruceEckel.com. 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) {
    System.out.println(counter++);
    }
    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();
    stoppable.start();
    new Timer(true).schedule(new TimerTask() {
    public void run() {
    System.out.println("Requesting stop");
    stoppable.requestStop();
    }
    }, 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:

    Pattern.matches
    String.matches
    String.replaceAll
    String.replaceFirst
    String.split





links for 2011-08-09

10 08 2011
  • import java.io.File;
    import java.io.FileReader;
    import java.io.IOException;

    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 = reader.read(chr)) > 0) {
    buffer.append(chr, 0, len);
    }
    } finally {
    reader.close();
    }
    return buffer.toString();
    }
    }

  • protected void processLine(String aLine){
    //use a second Scanner to parse the content of each line
    Scanner scanner = new Scanner(aLine);
    scanner.useDelimiter("=");
    if ( scanner.hasNext() ){
    String name = scanner.next();
    String value = scanner.next();
    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");
    cmdLine.addArgument("/p");
    cmdLine.addArgument("/h");
    cmdLine.addArgument("${file}");
    HashMap map = new HashMap();
    map.put("file",new File("invoice.pdf"));
    commandLine.setSubstitutionMap(map);
    DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler();
    ExecuteWatchdog watchdog=new ExecuteWatchdog(60*1000);
    Executor executor = new DefaultExecutor();
    executor.setExitValue(1);
    executor.setWatchdog(watchdog);
    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 java.io.ByteArrayOutputStream;
    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);
    exec.setStreamHandler(streamHandler);
    exec.execute(commandline);
    return(outputStream.toString());
    }





links for 2011-07-08

9 07 2011




links for 2011-06-29

30 06 2011




links for 2011-06-10

11 06 2011




links for 2011-06-08

9 06 2011




links for 2011-05-31

1 06 2011
  • package org.kodejava.example.util;

    import java.util.Currency;
    import java.util.Locale;

    public class CurrencySymbol {
    public static void main(String[] args) {
    Currency currency = Currency.getInstance(Locale.JAPAN);
    System.out.println("Currency.getSymbol() = " + currency.getSymbol());

    currency = Currency.getInstance(Locale.UK);
    System.out.println("Currency.getSymbol() = " + currency.getSymbol());

    currency = Currency.getInstance(Locale.US);
    System.out.println("Currency.getSymbol() = " + currency.getSymbol());

    currency = Currency.getInstance(new Locale("in", "ID"));
    System.out.println("Currency.getSymbol() = " + currency.getSymbol());
    }
    }

  • The locale is set during execution and is not stored in the JRXML file.

    If you run the report through iReport, it is possible to set the report locale in the Options window under the "Report execution options" section in the General tab. This will change how iReport runs your report.

    If you run the report embedded in Java, you set the REPORT_LOCALE parameter, like you mention. The following code is what I use:

    Locale locale = new Locale("en", "US");
    metadata.put(JRParameter.REPORT_LOCALE, locale);

    Where metadata is the parameter map sent to fillReport(…).