Tuesday, January 31, 2012

Return no wildcard

From Effective Java, 2nd edition:

Do not use wildcard types as return types.

E.g.,
public static <E> Set<E> union(Set<E> s1, Set<E> s2)
should be re-written
public static <E> Set<E> union(Set<? extends E> s1, Set<? extends E> s2)

Java bounded wildcards

From Effective Java, 2nd edition

For maximum flexibility, use wildcard types on input parameters that represent producers or consumers.
Mnemonic:
PECS stands for producer-extends, consumer-super.

E.g., method that takes a sequence of elements and pushes them all onto the stack:
// pushAll method without wildcard type - deficient!
public void pushAll(Iterable<E> src) {
    for (E e : src) {
        push(e);
    }
}
should be re-written:
// Wildcard type for parameter that serves as an E producer
public void pushAll(Iterable<? extends E> src) {
    for (E e : src) {
        push(e);
    }
}
Similarly, a method that pops each element off the stack and adds the elements to the given collection:
// popAll method without wildcard type - deficient!
public void popAll(Collection<E> dst) {
    while (!isEmpty()) {
        dst.add(pop());
    }
}
should be re-written:
// Wildcard type for parameter that serves as an E consumer
public void popAll(Collection<? super E> dst) {
    while (!isEmpty()) {
        dst.add(pop());
    }
}

Java unbounded wildcards

From Effective Java, 2nd edition:

If a type parameter appears only once in a method declaration, replace it with a wildcard.

For example, given a static method swapping 2 items in a list, prefer
public static void swap(List<?> list, int i, int j);
over
public static <E> void swap(List<E> list, int i, int j);
However, this implementation won't compile:
public static void swap(List<?> list, int i, int j) {
    list.set(i, list.set(j, list.get(i)));
}
because you can’t put any value except null into a List<?>. Instead, we will have to use:
public static void swap(List<?> list, int i, int j) {
    swapHelper(list, i, j);
}
// Private helper method for wildcard capture
private static <E> void swapHelper(List<E> list, int i, int j) {
    list.set(i, list.set(j, list.get(i)));
}

Wednesday, January 25, 2012

SyntaxHighLighter with java and generics

In order to use SyntaxHighLighter with java code containing generics, you first need to have all < and > being replaced with &lt; and &gt;
This can be done automatically by this online HTML encoder.

Use composition in place of inheritance

From Effective java, 2nd edition:
// Wrapper class - uses composition in place of inheritance
public class InstrumentedSet<E> extends ForwardingSet<E> {
    private int addCount = 0;
    public InstrumentedSet(Set<E> s) {
        super(s);
    }
    @Override public boolean add(E e) {
        addCount++;
        return super.add(e);
    }
    @Override public boolean addAll(Collection<? extends E> c) {
        addCount += c.size();
        return super.addAll(c);
    }
    public int getAddCount() {
        return addCount;
    }
}
// Reusable forwarding class
public class ForwardingSet<E> implements Set<E> {
    private final Set<E> s;

    public ForwardingSet(Set<E> s) { this.s = s; }
    public void clear() { s.clear(); }
    public boolean contains(Object o) { return s.contains(o); }
    public boolean isEmpty() { return s.isEmpty(); }
    public int size() { return s.size(); }
    public Iterator<E> iterator() { return s.iterator(); }
    public boolean add(E e) { return s.add(e); }
    public boolean remove(Object o) { return s.remove(o); }
    public boolean containsAll(Collection<?> c)
    { return s.containsAll(c); }
    public boolean addAll(Collection<? extends E> c)
    { return s.addAll(c); }
    public boolean removeAll(Collection<?> c)
    { return s.removeAll(c); }
    public boolean retainAll(Collection<?> c)
    { return s.retainAll(c); }
    public Object[] toArray() { return s.toArray(); }
    public <T> T[] toArray(T[] a) { return s.toArray(a); }
    @Override public boolean equals(Object o)
    { return s.equals(o); }
    @Override public int hashCode() { return s.hashCode(); }
    @Override public String toString() { return s.toString(); }
}
// Example use
Set<Date> s = new InstrumentedSet<Date>(new TreeSet<Date>(comparator));

Tuesday, January 24, 2012

Adove Reader: save last page

Edit -> Preferences -> Documents
[x] Restore last view settings when reopening documents

Exposing class fields

From Effective Java, 2nd edition:

In summary, public classes should never expose mutable fields. It is less harmful, though still questionable, for public classes to expose immutable fields. It is, however, sometimes desirable for package-private or private nested classes to expose fields, whether mutable or immutable.

Beware of public static final array fields

From Effective Java, 2nd edition:

Note that a nonzero-length array is always mutable, so it is wrong for a class to have a public static final array field, or an accessor that returns such a field. If a class has such a field or accessor, clients will be able to modify the contents of the array.
// Potential security hole!
public static final Thing[] VALUES = { ... };
Solution:
Either:
private static final Thing[] PRIVATE_VALUES = { ... };
public static final List<Thing> VALUES =
    Collections.unmodifiableList(Arrays.asList(PRIVATE_VALUES));
Or:
private static final Thing[] PRIVATE_VALUES = { ... };
public static final Thing[] values() {
    return PRIVATE_VALUES.clone();
}

The Bridge pattern

Problem: Draw rectangles and circles with either of two drawing programs without causing an explosion in the number of classes.
Solution: Decoupling implementation from the objects that use them.
public abstract class AbstractShape {
    private DrawingProgram dp;
    public abstract void draw();
    public AbstractShape(DrawingProgram dp) {
        this.dp = dp;
    }
    public void drawLine() {
        this.dp.drawLine();
    }
    public void drawCircle() {
        this.dp.drawCircle();
    }
}
public class Rectangle extends AbstractShape {
    public Rectangle(DrawingProgram dp) {
        super(dp);
    }
    @Override public void draw() {
        drawLine(); drawLine(); drawLine(); drawLine();
    }
}
public class Circle extends AbstractShape {
    public Circle(DrawingProgram dp) {
        super(dp);
    }
    @Override public void draw() {
        drawCircle();
    }
}
public interface DrawingProgram {
    void drawLine(); // implicitly public
    void drawCircle();
}
public class DrawingProgram1 implements DrawingProgram {
    @Override public void drawLine() { ... }
    @Override public void drawCircle() { ... }
}
public class DrawingProgram2 implements DrawingProgram {
    @Override public void drawLine() { ... }
    @Override public void drawCircle() { ... }
}
public class client {
    public static void main(String[] args) {
        Drawing dp1 = new DrawingProgram1();
        Rectangle rectangle = new Rectangle(dp1);
        Drawing dp2 = new DrawingProgram2();
        Circle circle = new Circle(dp2);

        circle.draw();
        rectangle.draw();
    }
}

The Abstract Factory pattern

Problem: Instantiate families of objects.
Solution: The Abstract Factory pattern defines the interface for how to create each member of the family.
public interface WindowFactory {
    Window createWindow(); // implicitly public
}
public MsWindowFactory implements WindowFactory {
    @Override public Window createWindow() {
        return new MsWindow();
    }
}
public AppleWindowFactory implements WindowFactory {
    @Override public Window createWindow() {
        return new AppleWindow();
    }
}
public Client {
    public static void main(String[] args) {

        WindowFactory  factory;
        String osName = System.getProperty("os.name");
        if ((osName != null) && (osName.indexOf("Windows") != -1)) {
            factory = new MsWindowFactory();
        } else {
            factory = new AppleWindowFactory();
        }

        Window window = factory.createWindow();
    }
}

SwingWorker

Problem: Perform a time-consuming task, likely to freeze the GUI.
Solution: Use the SwingWorker class, part of java 6.
Example:
private Document doc;
...
JButton button = new JButton("Load");
button.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
        SwingWorker<Document, Void> worker = 
            new SwingWorker<Document, Void>() {
                @Override public Document doInBackground() {
                    return load();
                }
                @Override public void done() {
                    try {
                        doc = get();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            };
        worker.execute();
   }
});

invokeLater vs. invokeAndWait

SwingUtilities.invokeLater(Runnable):
Asynchronous call used to update the GUI from the AWT Event Dispatching Thread.
SwingUtilities.invokeAndWait(Runnable):
Synchronous call used to update the GUI from the application thread.

Password strength validation with regex

Checking passwords with regex by using positive lookahead assertions.

Monday, January 23, 2012

Update VirtualBox to 4.1.8

  • Download VirtualBox-4.1.8-75467-Win.exe
  • Download VBoxGuestAdditions_4.1.8.iso
  • Unmount the VBoxGuestAdditions.iso under "Parameters | Storage | IDE Controller"
  • Do the update of VirtualBox
  • Restart VirtualBox
  • Copy the new VBoxGuestAdditions ISO into c:\program files\oracle\virtualbox
  • Mount the new VBoxGuestAdditions ISO under "IDE Controller"
  • Start the new VM
  • Re-install VBoxLinuxAdditions like previously done:
  • sudo mount /dev/cdrom /media/cdrom
    cd /media/cdrom
    sudo ./VBoxLinuxAdditions.run
    sudo reboot
  • Unmount the VBoxGuestAdditions ISO
In case of problems with VirtualBox Guest Additions:
http://www.if-not-true-then-false.com/2010/install-virtualbox-guest-additions-on-fedora-centos-red-hat-rhel/

The Factory Method pattern

Problem: A class needs to instantiate a derivation of another class, but doesn't know which one.
Solution: The Factory Method defines an interface for creating objects, but lets subclasses decide which classes to instantiate.
public interface Logger {
    void debug(String message); // implicitly public
}
public class FileLogger implements Logger {
    @Override public void debug(String message) { ... }
}
public abstract class AbstractLoggerFactory {
    public abstract Logger createLogger(); // factory method

    public Logger getLogger() {
        Logger logger = createLogger();
        ...
        return logger;
    }
}
public class FileLoggerFactory extends AbstractLoggerFactory {
    @Override
    public Logger createLogger() {
        return new FileLogger();
    }
}
public class Client {
    private AbstractLoggerFactory factory = new FileLoggerFactory();
    public doSomething(AbstractLoggerFactory factory) {
        Logger logger = factory.getLogger();
        logger.debug("debug message");
    }
}

The Singleton pattern

Problem: Several clients need to refer to the same thing.
Solution: The Singleton pattern guarantees a class has only one instance.
// Enum singleton - the preferred approach: concise + serializable
public enum Singleton { // implicitly final
    INSTANCE; // implicitly public static final
    public void doSomething() { ... }
}

Saturday, January 21, 2012

Online tool for Visio like UML modelling

You can try gliffy for free.

The Visitor pattern

Problem: Determine the postage for the items in a shopping cart.
Solution: The Visitor pattern creates an external class that will use the data of the cart items to compute the postage.
public interface Visitable {
    void accept(Visitor visitor); // implicitly public
}
public class Book implements Visitable {
    @Override public void accept(Visitor visitor) {
        if (...) visitor.visit(this);
    }
}
public interface Visitor {
    void visit(Book book); // implicitly public
    void visit(CD cd);
}
public class PostageVisitor implements Visitor {
    @Override public void visit(Book book) {
        this.totalPostage += ...;
    }
    @Override public void visit(CD cd) {
        this.totalPostage += ...;
    }
    public void getTotalPostage() {
        return this.totalPostage;
    }
}
public class Client {
    public double calculatePostage() {
        PostageVisitor visitor = new PostageVisitor();
        for (Visitable item : this.items) {
            item.accept(visitor);
        }
        return visitor.getTotalPostage();
    }
}

The Adapter pattern

Problem: A system has the right data and behavior but the wrong interface.
Solution: The Adapter provides a wrapper with the desired interface.

The Facade pattern

Problem: Use a subset of a complex system.
Solution: The Facade presents a new interface of the system.

SyntaxHighlighter splits my source code

My first install of SyntaxHighlighter in Blogger was splitting my source code like this:

This was due to my using some Blogger CSS customization for the <code> tag:
code {
    ...
    display: block;
}

Superfluous vertical scrollbars in SyntaxHighlighter

Add this to the Blogger CSS:
.syntaxhighlighter {
    padding: 1px !important;
}

SyntaxHighlighter in Blogger

This article says it all. The site also generates the lines to add in Blogger template.

Friday, January 20, 2012

Push a bunch of files over SSH to a remote location

Example given:
  1. TAR + GZIP some files (including directories)
  2. SSH them onto mamlan.com remote host using me as a user and www/ectasea as a target directory
  3. UnGZIP + unTAR everything
tar czf - 3rdparty common ectasea extensions global.inc index.php login 
| ssh me@mamlan.com "tar xzf - -C www/ectasea"

Thursday, January 19, 2012

GWT debugging on Windows in a VirtualBox Linux VM

This post shows how to use a browser on a host (Windows 7) with Eclipse running a GWT project on the VirtualBox guest (Ubuntu server).

Below, my Ubuntu guest has been named "fart".

Close frame programmatically

If we assume we are in a MyJFrame sub-class:

MyJFrame.this.processWindowEvent(
    new WindowEvent(MyJFrame.this,WindowEvent.WINDOW_CLOSED));

Java SE is deprecated!

[Charles Humble]:

"JavaFX 2 is something that completely replaces AWT, Java2D, Swing, Java Sound, Applets, ImageIO, Accessibility - in short, the entire Client layer of the JavaSE platform."

Recording events

Recording events in a suitable format will be supported in a later version of this product, once the replay side has stabilised. In the meantime, you can get event information in an undocumented way. The Java home directory has a subdirectory lib containing a file awt.properties. If you add the line
AWT.EventQueueClass=jnewmarch.replay.TracedEventQueue
to this, then all events that enter the event queue will be printed to standard output.

Where does this beep come from?

I was recently given the task of figuring out why our client application kept beeping all the time. It sounds funny but the continued noise was getting on my nerves. I searched our application for all calls to beep() on the toolkit and found nothing. Apparently, it was coming from one of our commercially purchased components that we do not have the source code for ... great. What to do now? Well I thought about trying to use AOP in some fashion to find the source of the problem but we don't have AOP currently in our application. I finally decided to do the following:
  1. Subclass MToolkit
  2. Call System.setProperty("awt.toolkit", "com.MyToolkit") to install it at startup.
  3. Set a breakpoint in my toolkit's beep() method. View the stacktrace when the beep is invoked.

equals()

Because the default hashCode() gives an answer based on the instance's identity, it is incorrect to implement equals() without implementing a corresponding hashCode() method. e.g.
public class Person {
    private String name;
    private Date birth;
    public boolean equals(Object other) {
        if (other == this) return true;
        if (other == null) return false;
        if (getClass() != other.getClass()) return false;
        Person person = (Person)other;
        return (
            (name == person.name ||
             (name != null && name.equals(person.name))) &&
            (birth == person.birth ||
             (birth != null && birth.equals(person.birth)))
            );
    }
}

instanceof

Toujours privilegier getClass() sur instanceof() car instanceof n'est pas symetrique.

Update a jar

jar uvf jgui-2.0.jar -C src/

Print stack trace in normal situation

Thread.currentThread().dumpStack();

Swing tips

  • Keep all your UI/view code in a separate package like blackmamba.ui.
  • Create a package for the control, such as blackmamba.ui.control. This is where you write all your UI logic. I like to name my control classes as verbs (Start, Login, Configure, etc.) and my view classes as nouns.

Find the frame or desktop pane which the specified component is in.

static Frame JOptionPane.getFrameForComponent(Component)

Center dialog relatively to frame

            // Always pack before using setLocationRelativeTo
            myDialog.dialog.pack();
            myDialog.dialog.setLocationRelativeTo(frame);

applet AccessControlException java.net.SocketPermission denied

Look in:
C:\Program Files\j2sdk1.4.2\jre\lib\security\java.policy
and
C:\Documents and Settings\gallinari\.java.policy

How detecting whether a JTable cell has the focus?

boolean rowIsAnchor = (getSelectionModel().getAnchorSelectionIndex() == row);
boolean colIsAnchor =
    (getColumnModel().getSelectionModel().getAnchorSelectionIndex() == column);

How can I simulate a double click from a single click in a JTable?

javax.swing.DefaultCellEditor dce =
          (javax.swing.DefaultCellEditor)table.getDefaultEditor(Object.class);
      dce.setClickCountToStart(1);

Add a black border

import javax.swing.BorderFactory;
import java.awt.Color;

setBorder(BorderFactory.createLineBorder(Color.black);

How can I access text entered in a JComboBox, when the user does not hit enter?

Location: http://www.jguru.com/faq/view.jsp?EID=53753 Author: Sandip Chitale Question originally asked by tracey marsh The easiest way to do this is to watch for changes in focus. WHen the user leaves the combo box (to press a button or work with another component, for example) you can catch a focusLost event from the JComboBox's editor. The following code assumes you haven't changed the editor for the combo box (which is probably the case).
if (comboBox.getEditor().getEditorComponent()
    instanceof JTextField) {
  JTextField tf = 
    (JTextField)comboBox.getEditor().getEditorComponent();

  tf.addFocusListener(new FocusAdapter() {
    public void focusLost(FocusEvent fe) {
      // get the text using getText() method
    }});
}

How can I set the minimum size of a Window/Frame?

Derived from A question posed by David Jones Topics Java:API:AWT:Widgets Author Sandip Chitale Answer Subclass and override -
public Dimension getMinimumSize() {
  return new Dimension(
    MINIMUM_WIDTH, MINIMUM_HEIGHT);
}
Note that the native implementation of Frame does not allow minimum size below certain size.

JTable size policy

Here's the deal. During layout, the viewport is queried for its preferred size. The viewport returns one of the following:
  1. zero width, zero height
  2. its single child's preferred size if the child's not a Scrollable
  3. its single child's preferredScrollableViewportSize if the child's a Scrollable
Since JTable is a Scrollable(i.e., it implements the Scrollable interface), the viewport returns 3) above. JTable's initial preferredScrollableViewportSize's height is 400. Thus, you get a height of 400 even if you set the table's preferred size's height to 17. Call setPreferredScrollableViewportSize() to change the preferred viewport size.

Reads next token from stream tokenizer

    /**
     * Reads the next token from the given stream tokenizer.
     *
     * @param aScanner  Stream tokenizer to read from.
     * @return          Read string token or null.
     *
     * @ulcm.msg 403 getString()
     * @ulcm.msg 410 EOF
     * @ulcm.msg 411 EOL
     */
    private String getString(StreamTokenizer aScanner) {

        String rtnString = null;
        try {
            aScanner.nextToken();
            switch (aScanner.ttype) {
                case StreamTokenizer.TT_EOF:
                    rtnString = CommItlBundle.getString(410);
                    break;
                case StreamTokenizer.TT_EOL:
                    rtnString = CommItlBundle.getString(411);
                    break;
                case StreamTokenizer.TT_WORD:
                    rtnString = aScanner.sval;
                    break;
                case StreamTokenizer.TT_NUMBER:
                    rtnString = String.valueOf((int) aScanner.nval);
                    break;
                case '"':
                    rtnString = aScanner.sval;
                    break;
                default:
                    rtnString = String.valueOf((char) aScanner.ttype);
            }
        } catch (IOException e) {

            if (this.LOGGER.isLoggable(Level.FINER)) {

                this.LOGGER.throwing(getClass().getName(),
                                     CommItlBundle.getString(403),
                                     e);
            }
        }
        return rtnString;
    }

Testing your css or javascript code

  1. Go to JSFiddle.
  2. Put the HTML in the HTML area, the CSS in the CSS area, and the JavaScript in the JavaScript area
  3. Press Run and see if the result is demonstrating the problem, adjust as needed to make the problem very clear.
  4. Press Save to get a public URL.
  5. Share that URL where you are trying to get the troubleshooting help.

Git worflow

Git training

A Git training by Ralf Ebert.

Monday, January 16, 2012

Installing ant 1.8.2 onto ubuntu 11.10

Download ant and copy it under /usr/lib:
cd /usr/lib
sudo tar xvfz /media/host/apache-ant-1.8.2-bin.tar.gz
sudo ln -s apache-ant-1.8.2 apache-ant
sudo update-alternatives --install /usr/bin/ant ant /usr/lib/apache-ant/bin/ant 1

Install JDK 7 onto Ubuntu 11.10

Download the latest Oracle JDK 7 from here.
sudo mkdir -p /usr/lib/jvm/
cd /usr/lib/jvm/
tar xvfz /media/host/jdk-7u2-linux-x64.tar.gz
ln -s jdk1.7.0_02 jdk
sudo apt-get install python-software-properties
sudo apt-add-repository ppa:nilarimogard/webupd8
sudo apt-get update
sudo apt-get install update-java
sudo update-java
and select /usr/lib/jvm/jdk