March 20, 2012

Memory Profiling Tool with Allocation Stack Trace

Hunting down memory consuming code, cannot be done without a good tool. Because guising which method or code block that consumes most memory, is at least according to me, almost impossible.

And one good tool that comes for free is Visual VM (http://visualvm.java.net/) If you are running Windows and Java SDK you already have it installed under
$ %JAVA_HOME%/bin/jvisualvm

And if you are running Ubuntu, simply install with:
$ sudo apt-get install visualvm

The tool is quite straight forward. You can see working thread and do thread dump to see what each thread is momentarily is doing, etc. And from the Profile tab you can perform memory profiling, but to see allocations stack trace you have to change the default settings.

March 9, 2012

Syslog client in Java that implements RELP, TCP, SSL/TLS, Caching and Resending

In one of my previous project we had the need of logging message in a secure way, we also needed to be sure that each message was really transmitted and if not sent successfully, should that really be detected.

When I started I thought there must be someone out there that have solved something similar or there exist a product that did this. Be after searching the web I came up with only this:

Log4J do support Syslog (org.apache.log4j.net.SyslogAppender) but is based on java.net.DatagramSocket which uses UDP, which is not a reliable transport protocol. I also looked at other common logging libraries, but they also do not support a TCP based Syslog Appender.

So I started of extended existing SocketAppender to talk Syslog instead. This worked, but then I realized that just having a client talking TCP does not make it reliable. The java.net.Socket.getOutputStream().write() will not throw Exception even if you stop the Syslog after successfully opening a Socket. Socket write operation is not a blocking operation and will not wait for any success message. You might now argue that a socket.getOutputStream().flush() will solve this problem, but as the Javadoc API points out, the flush operation does not guarantee that actual operating system socket will be flushed. “... it does not guarantee that they are actually written to a physical device such as a disk drive. ” [http://docs.oracle.com/javase/7/docs/api/java/io/OutputStream.html#flush%28%29]

So this was the background when I started to look at RELP, Reliable Event Logging Protocol [http://www.librelp.com/relp.html. Using the RELP protocol on top of the Syslog protocol really seemed to solve my problems. The only problem was that I could not find any Java implementation. [http://lists.adiscon.net/pipermail/relp/2010-October/000026.html] The closest project I could find was http://syslog4j.org/ but it does not support RELP.

After happily got my first Syslog Appender working using TCP and RELP. The next problem occurred when we also needed to protect the transport data. Fine I thought, just change my implementation to use a javax.net.ssl.SSLSocket instead of java.net.Socket. But the problem is the current librelp implementation does not support SSL/TLS. “The RELP transport can currently not be protected by TLS.” [http://www.rsyslog.com/doc/rsyslog_tls.html] And the only solution provided was to use a stunnel. Which works.

The last problem to solve was to make my Syslog TCP RELP Appender cache instead of sending Exception up, when communication fails. This was quite straightforward and the only challenge was to make my implementation threadsafe.

There has been discussion of making the solution open source, but the main problem right now is the lack of time.

March 7, 2012

Managing Multiple Java Installation on Ubuntu 11.10

In earlier blog I have discussed how to install Oracle Java 7 JDK (http://magnus-k-karlsson.blogspot.com/2012/01/how-to-install-oracle-jdk-on-ubuntu-11.html), but several application is not compatible with Java 7. And this was the case for me when running JBoss. So in this blog I will show you how to manage several Java installation on the same Ubuntu 11.10 computer.

Instead of changing symbolic link for /usr/bin/java there is a tool for you that does that consistently.

$ sudo update-alternatives --config java

There are 3 choices for the alternative java (providing /usr/bin/java).

Selection    Path                                      Priority   Status
------------------------------------------------------------
* 0            /usr/lib/jvm/java-7-oracle/bin/java        1063      auto mode
1            /usr/lib/jvm/java-6-openjdk/jre/bin/java   1061      manual mode
2            /usr/lib/jvm/java-6-sun/jre/bin/java       63        manual mode
3            /usr/lib/jvm/java-7-oracle/bin/java        1063      manual mode

Press enter to keep the current choice[*], or type selection number: 2
update-alternatives: using /usr/lib/jvm/java-6-sun/jre/bin/java to provide /usr/bin/java (java) in manual mode.


$ java -version
java version "1.6.0_26"
Java(TM) SE Runtime Environment (build 1.6.0_26-b03)
Java HotSpot(TM) 64-Bit Server VM (build 20.1-b02, mixed mode)

January 31, 2012

How to install Oracle JDK on Ubuntu 11 from repository.

With Oracle the acquisition of Sun the Oracle have retired the "Operating System Distributor License for Java" (JDL) and the only available JDK release will be the OpenJDK. I had previously some bad experience with the OpenJDK and I prefer to use the official Oracle version of JDK, but I don't want to install the JDK binaries manually – we are using Ubuntu! But the webupd8.org team have been nice to published the binaries in a Personal Package Archives (PPA) and so far I have no problem using it, so I can warmly recommend using it.

To install:
$ sudo add-apt-repository ppa:webupd8team/java
$ sudo apt-get update
$ sudo mkdir -p /usr/lib/mozilla/plugins #just in case, this will be added to the package in the next version
$ sudo apt-get install oracle-jdk7-installer

And to uninstall:
$ sudo apt-get remove oracle-jdk7-installer


And to verify your installation:
$ java -version
java version "1.7.0_02"
Java(TM) SE Runtime Environment (build 1.7.0_02-b13)
Java HotSpot(TM) 64-Bit Server VM (build 22.0-b10, mixed mode)

And to verify the web browser installation:
http://java.com/en/download/installed.jsp
Verified Java Version
Congratulations!
You have the recommended Java installed (1.7.0_02).

And with maven 2:

$ mvn -version
Java version: 1.7.0_02
Java home: /usr/lib/jvm/java-7-oracle/jre
Default locale: en_US, platform encoding: UTF-8
OS name: "linux" version: "3.0.0-15-generic" arch: "amd64" Family: "unix"

Java Web Start

The only thing that did not work out of the box was the Java Web Start. To fix that open JNLP file link and when asked for application, brows to:
/usr/lib/jvm/java-7-oracle/bin/javaws

For complete reference see:
http://www.webupd8.org/2012/01/install-oracle-java-jdk-7-in-ubuntu-via.html

How to Make a Custom Launcher (Shortcut) in Ubuntu 11.10 (Oneiric Ocelot) Dock

In my previous blog I wrote about how to create a custom launcher to the Unity dock, but when you upgrade to 11.10 (Oneiric Ocelot) that no longer holds. When you right click on the desktop the menu item Create Launcher... is no longer there.

The simplest way I have yet found is to manually create a desktop file anywhere one the file system, but I would recommend to put it in the same folder as the program you are creating to shortcut to.

Example of my eclipse.desktop:
$[Desktop Entry]
Exec=/home/magnus/bin/eclipse-jee-3.7.1/eclipse
Icon=/home/magnus/bin/eclipse-jee-3.7.1/icon.xpm
Name=Eclipse JEE 3.7.1
StartupNotify=true
Terminal=false
Type=Application
X-KDE-SubstituteUID=false

How to implement MVC (Model View Controller) Pattern with Swing – Part 3

In my third blog about implementing MVC pattern in Swing I will look at how to implement global actions, context sensitive global actions, updating status bar and popup dialogs. But before delving into these issues and I would like again to repeat each class responsibility in the MVC pattern:

Model:
  1. Simple POJO model.
View:
  1. Layout out the Swing components.
  2. Responds to user action by sending request to Control.
  3. Responds to Controller responds.
Controller:
  1. Receives request from the View.
  2. Do logic.
  3. Sends Responds to View(s).
And a last reminder the Request and Responds to and from the Controller should be TOTALLY view technique neutral as the Model. The view specific code, in our case Swing code, ends in the view. Handling all Swing code is the responsibility of each view.

In my previous blog we have seen that each View is only responsible of its Swing component and what happens in other view is it totally unaware of. Try to think of separation of concern. It is the responsibility of the Controller to call the Response methods in each Views that should be updated.

Example:
    private class CreateDocumentAction extends AbstractAction {
        private static final long serialVersionUID = 1L;

        public CreateDocumentAction() {
            putValue(Action.NAME, "Create");
            putValue(Action.SHORT_DESCRIPTION, "Create Document");
            putValue(Action.SMALL_ICON, imageIcon("/org/tango-project/tango-icon-theme/16x16/actions/document-new.png"));
        }

        @Override
        public void actionPerformed(ActionEvent e) {
            getDossierController().preCreateDocument(getModel());
        }
    }


And the corresponding Controller code:
    public void preCreateDocument(Dossier dossier) {
        // 1. do server logic
        Document document = new Document();
        document.setDossierId(dossier.getDossierId());
        // 2. do swing response
        getMainFrame().getView(DocumentModelView.class).setModel(document);
        getMainFrame().getView(DossierTreeModelView.class).addDocumentNode(document);
    }


The Toolbar is yet Another View

So now lets start with looking how to add a JToolBar to our Swing client. If you think of it for a while you will realize that the toolbar is yet another view. So lets write a new class that extends from our AbstractView.

package se.msc.mvcframework.demo.view;

import static se.msc.mvcframework.ComponentFactory.button;
import static se.msc.mvcframework.ComponentFactory.imageIcon;

import java.awt.event.ActionEvent;

import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JButton;
import javax.swing.JToolBar;

import se.msc.mvcframework.AbstractFrame;
import se.msc.mvcframework.AbstractView;
import se.msc.mvcframework.demo.controller.DossierController;

public class ToolBarView extends AbstractView<jtoolbar> {
    private JButton saveButton;
    private Action saveAction;

    public ToolBarView(AbstractFrame mainFrame) {
        super(mainFrame);
    }

    @Override
    protected JToolBar layout() {
        JToolBar toolBar = new JToolBar();
        toolBar.add(button(new OpenDossier()));
        toolBar.add(saveButton = button(saveAction = new SaveAction()));
        return toolBar;
    }

    // ---------- Request Code Goes Here

    public class OpenDossier extends AbstractAction {
        private static final long serialVersionUID = 1L;

        public OpenDossier() {
            putValue(Action.NAME, "Open");
            putValue(Action.SHORT_DESCRIPTION, "Open Dossier");
            putValue(Action.SMALL_ICON, imageIcon("/org/tango-project/tango-icon-theme/16x16/actions/document-open.png"));
        }

        @Override
        public void actionPerformed(ActionEvent e) {
            getMainFrame().getController(DossierController.class).retrieveDossierView();
        }
    }

    public class SaveAction extends AbstractAction {
        private static final long serialVersionUID = 1L;

        public SaveAction() {
            putValue(Action.DEFAULT, AbstractFrame.GLOBAL_SAVE_ACTION);
            putValue(Action.NAME, "Save");
            putValue(Action.SHORT_DESCRIPTION, "Save");
            putValue(Action.SMALL_ICON, imageIcon("/org/tango-project/tango-icon-theme/16x16/actions/document-save.png"));
        }

        @Override
        public void actionPerformed(ActionEvent e) {
        }
    }

    // ---------- Response Code Goes Here

    public void setGlobalActions(Action[] actions) {
        resetGlobalActions();
        for (Action action : actions) {
            if (AbstractFrame.GLOBAL_SAVE_ACTION.equals(action.getValue(Action.DEFAULT)))
                saveButton.setAction(action);
        }
    }

    public void resetGlobalActions() {
        saveButton.setAction(saveAction);
    }
}


I have here used javax.swing.Action for base class, since they contain all graphical properties such icon, label and tooltip. But also javax.swing.Action can be used for JButton and in JPopupMenu and JMenuItem.

And I have also deliberately not created a abstract class for our action, which could have loaded our images, since I do not believe that such extra abstraction class will not bring any extra to our code nor reduce the number of lines. It will only make our client code more less understandable. But what would justify an extra abstraction layer is if abstract action class called the Controller in thread safe ways and change cursor to busy and in case of failure show a generic exception dialog. That would really bring something to our code, but not loading icons, using Action is quite straightforward and I like to see directly what my code does.

Handling Context Sensitive Global Actions

So after realized that the toolbar is just another view, lets move onto how to make the toolbar context sensitive, i.e. when switching active panel/window the save actions is replaced with the active panel/window save action. But before we must first decide where the concrete Swing save action should be located. It clearly belong to the concrete view. Think again of separation of concern. But what we must do is to expose the global actions so we can send them to the toolbar view. And lastly where do we wire the views together? In the Controller of course.

Let first add an extra method in our abstract view:
    public Action[] getGlobalActions() { return new Action[0]; }


Then in our controller we wire the global actions from the view to the toolbar view.
    public Action[] getGlobalActions() { return new Action[0]; }


And in our toolbar view:

    public void preCreateDocument(Dossier dossier) {
        // 1. do server logic
        Document document = new Document();
        document.setDossierId(dossier.getDossierId());
        // 2. do swing response  
getMainFrame().getView(ToolBarView.class).setGlobalActions(getMainFrame().getView(DocumentModelView.class).getGlobalActions());
        getMainFrame().getView(DocumentModelView.class).setModel(document);
        getMainFrame().getView(DossierTreeModelView.class).addDocumentNode(document);
    }


The last thing we need is to do is to switch back to the default when changing to other views. Here it can be justified to introduce some kind of View lifecycle mechanism, so the programmer does not have to concern about setting the correct toolbar action each time a new View is retrieved.

Managing a Statusbar

After thinking the GUI as a composition of different views, it should not be surprising to think of the statusbar as yet another view as well. And where is the respond sent to update this view. In the Controller of course. Here is a simple example how to implement a statusbar with swinglabs JXStatusBar.

se.msc.mvcframework.demo.view.StatusBarView
package se.msc.mvcframework.demo.view;

import javax.swing.JLabel;

import org.jdesktop.swingx.JXStatusBar;

import se.msc.mvcframework.AbstractFrame;
import se.msc.mvcframework.AbstractView;

public class StatusBarView extends AbstractView<jxstatusbar> {
    private JLabel statusLabel1;
    private JLabel statusLabel2;

    public StatusBarView(AbstractFrame mainFrame) {
        super(mainFrame);
    }

    @Override
    protected JXStatusBar layout() {
        statusLabel1 = new JLabel("Ready1");
        statusLabel2 = new JLabel("Ready2");

        JXStatusBar statusBar = new JXStatusBar();
        statusBar.add(new JLabel(), new JXStatusBar.Constraint(JXStatusBar.Constraint.ResizeBehavior.FILL));
        statusBar.add(statusLabel1, new JXStatusBar.Constraint(100));
        statusBar.add(statusLabel2, new JXStatusBar.Constraint(100));
        return statusBar;
    }

    // ---------- Request Code Goes Here

    // ---------- Response Code Goes Here

    public void setStatusText1(String statusText1) {
        statusLabel1.setText(statusText1);
    }

    public void setStatusText2(String statusText2) {
        statusLabel2.setText(statusText2);
    }
}


Managing Modular Popup Windows

The modular popup windows is also yet another view. The only difference it needs a parent JFrame to show from. And the solution to that is simple. Each View has a reference to the AbstractFrame that holds the JFrame via getFrame().

January 23, 2012

How to Merge PDF Files in Ubuntu

There are so many good web article that you would like to read and sometimes they even stretch over several web pages, but what if you are not online or like to concatenate several different article of your choosing?

One way to do it, it to use the build in print to PDF file in Ubuntu. But what if there are several article? Then you probably want to merge these PDF files. In Ubuntu that is an easy task.

First install pdftk:
$ sudo apt-get install pdftk


Then type the following in the the directory where all the pdf files are:
$ pdftk 1.pdf 2.pdf 3.pdf cat output merged.pdf


For a complete reference see http://ubuntuhowtos.com/howtos/merge_pdf_files.