SMTP Dummy 1.1 Released (NetBeans Plugin)

1

Written on July 10, 2009 by Allan Lykke Christensen

This evening I added a few features to the SMTP Dummy NetBeans Plugin. It is now possible to specif a folder where mails caught are stored. It is also possible to open each mail “in the system” directly from NetBeans. You can download the latest version from the Kenai project page: http://kenai.com/projects/smtp-dummy

Screenshot of SMTP Dummy 1.1

Screenshot of SMTP Dummy 1.1

Note: If you are installing the plug-in for the first time, don’t forget to also download and install the Mailster library (also located in the download section)

Comments are very welcome!

NTLM authentication for HTTP connections

3

Written on June 28, 2009 by Allan Lykke Christensen

I was recently tasked with integrating one of our products with an off-the-shelf case and document management system used by many organisations in the Danish public sector. The case and document management system allows for integration via RESTful-like HTTP calls to the core of the system. The RESTful-like interface is easy to use, but it was challenging to get through to the system in the first place. You see, it was developed on a Windows platform (dot net) and it relies solely on NTLM authentication provided by the operating system. Automating the NTLM authentication would have been easy if the code was done using a dot net technology, but since our product is Java-based it was causing a bit of a headache. I researched possible API’s (JCIFS and JESPA) for doing the authentication, but they didn’t seem to be straight forward. As I had a partial solution using the JCIFS API, I requested help on the SAMBA-JCIFS mailing list where I was informed that Java 5 and 6 had built-in support for NTLM and there was no need for an API. So, here is the code I ended up with for automating the NTLM authentication:

public static String getResponse(final ConnectionSettings settings, 
        String request) throws IOException {
 
    String url = settings.getUrl() + "/" + request;
 
    Authenticator.setDefault(new Authenticator() {
        @Override
        public PasswordAuthentication getPasswordAuthentication() {
            System.out.println(getRequestingScheme() + " authentication")
             // Remember to include the NT domain in the username
            return new PasswordAuthentication(settings.getDomain() + "\\" + 
                settings.getUsername(), settings.getPassword().toCharArray());
        }
    });
 
    URL urlRequest = new URL(url);
    HttpURLConnection conn = (HttpURLConnection) urlRequest.openConnection();
    conn.setDoOutput(true);
    conn.setDoInput(true);
    conn.setRequestMethod("GET");
 
    StringBuilder response = new StringBuilder();
    InputStream stream = conn.getInputStream();
    BufferedReader in = new BufferedReader(new InputStreamReader(stream));
    String str = "";
    while ((str = in.readLine()) != null) {
        response.append(str);
    }
    in.close();
 
    return response.toString();
}

That’s all. Thanks to the guys who helped out on the SAMBA-CIFS mailing list and StackOverflow.

References:

SMTP Dummy 1.0 for NetBeans released

4

Written on June 13, 2009 by Allan Lykke Christensen

The first release of SMTP Dummy for NetBeans has been released.

SMTP Dummy 1.0

SMTP Dummy 1.0

Installation

  1. Download SMTP Dummy 1.0
  2. Download Mailster 1.0.0-M2
  3. Launch NetBeans
  4. Click Tools -> Plugins
  5. Select the “Downloaded” tab
  6. Click “Add Plugins…”
  7. Select the two downloaded files from above
  8. Click “Install” and accept the licenses

Usage

  1. In the Services tab (CTRL-5) you’ll see a node named “SMTP Dummy Servers”
  2. Right click the node and select “New”
  3. Enter “Dummy” as the name
  4. Enter “1025″ as the port
  5. Click “Finish”
  6. Right click the added node and select “Start”. It will take a few seconds before the server is started (the icon will turn green when its ready)
  7. You can now start testing sending mail on port 1025. To see the mails caught open the “Mails Received” window from Window -> Output -> Mails Received
  8. To view the contents of a caught mail, right click the mail and select View

FileObject streams

0

Written on June 12, 2009 by Allan Lykke Christensen

As I’m still learning the NetBeans platform I was getting concerned about closing and opening streams when creating new FileObjects. I therefore posted a question on StackOverflow hoping that some NetBeans Guru would see. After posting I dug into the NetBeans API and source code and discovered how it all works. Here is the except from my self-answered question on StackOverflow:

Q: When creating modules on the NetBeans platform, the FileObject object represents a file in the virtual file system of the IDE. Creating new FileObjects is simple, but does NetBeans completely control the reference to the actual File, or should I close FileObject myself? My code is like this:

FileObject appRoot = FileUtil.getConfigRoot().getFileObject("myapp");
 
try {
    FileObject fo = servers.createData(filename);
    fo.setAttribute("name", "a name");
    fo.setAttribute("desc", "a description");
} catch (IOException ex) {
   throws new FileCreationException("Could not create file " + filename, ex);            
}

With the above code, am I leaving open some references to the actual file or should I obtains the OutputStream of the FileObject and close it manually?

Thanks.

Self-answer: After digging around in the NetBeans API and source code I believe I’ve found the answer to my own question.

Attributes as set above are stored in a special attributes file. Each folder in the virtual file system has a hidden attributes file (.nbattrs) which contains the attributes stored for each FileObject, e.g.

<!DOCTYPE attributes PUBLIC "-//NetBeans//DTD DefaultAttributes 1.0//EN"     
                            "http://www.netbeans.org/dtds/attributes-1_0.dtd">
<attributes version="1.0">
    <fileobject name="dk-i2m-netbeans-smtpdummyservice-mailserver-1244831819713">
        <attr name="name" stringvalue="My test"/>
        <attr name="desc" intvalue="Server for testing outgoing e-mails"/>
    </fileobject>
</attributes>

This file is completely controlled by NetBeans and no opening or closing of input/output streams are necessary.

If however, you want to add content to the FileObject and not mere attributes, you will have to do it the normal Java-way of using the InputStream and OutputStream of the FileObject (both have a getter and setter) and remember to close the streams accordingly. e.g.

FileObject appRoot = FileUtil.getConfigRoot().getFileObject("myapp");
 
try {
    FileObject fo = servers.createData(filename);
    fo.setAttribute("name", "a name");
    fo.setAttribute("desc", "a description");
 
    // Lock the FileObject before writing
    FileLock lock;
    try {
        lock = fo.lock();
    } catch (FileAlreadyLockedException ex) {
        Exceptions.printStackTrace(ex);
        return;
    }
 
    try {
        OutputStream out = fo.getOutputStream(lock);
        try {
            // Write into the output stream
        } finally {
            // Remember to close the stream
            out.close();
        }
    } finally {
        lock.releaseLock();
    }
} catch (IOException ex) {
    throws new FileCreationException("Could not create file " + filename, ex);            
}

SMTP Dummy plug-in almost done

0

Written on June 8, 2009 by Allan Lykke Christensen

This evening I added a few more features to the NetBeans SMTP Dummy plug-in:

  • Immediate update of the mails caught view upon catching a mail. The first version didn’t update automatically and the user would have to manually invoked the refresh command to check if any mails had been caught
  • Wizard for creating a new dummy service (See screenshot 2 below)
  • (Very basic) View the contents of a caught mail (See screenshot 1 below)

Before releasing the plug-in I want to improve the contents view of a caught mail.

P.S. I’ve also added a NetBeans Platform page to the blog where I’ll be posting links and references to NetBeans content that I’ve found helpful.

Screenshot 1: Caught mail

Screenshot 1: Caught mail

Screenshot 2: New SMTP service wizard

Screenshot 2: New SMTP service wizard

NetBeans Plug-in: SMTP Dummy

1

Written on June 7, 2009 by Allan Lykke Christensen

On Friday I went on-leave, and being a complete geek I quickly filled my time with some personal programming assignments. For a long time I’ve been wanting to look more into the NetBeans Platform and explore how to build stand-alone applications based on the platform. For the past ten years I’ve almost solely been developing enterprise applications (web/ejb), so jumping to GUI-based applications is quite a steep challenge for me. For me to get a gentle start I decided looking into creating a simple plug-in (also called module in NetBeans lingo). I call the plug-in SMTP Dummy. The plug-in allows for setting up dummy SMTP servers which will catch mail being sent to a given port on the local machine and display the mails within NetBeans. Previously I’ve been using DevNull SMTP and the Python SMTP daemon which, by the way, are both great tools!   Below are a few screenshots of the plug-in.  If you are interested in the project feel free to join it or download it on Kenai.com (http://kenai.com/projects/smtp-dummy).

SMTP dummy servers

SMTP dummy servers

Mails caught

Mails caught

Internet Explorer 8 + Ajax + Large page = Slownessssssss

0

Written on June 3, 2009 by Allan Lykke Christensen

The past few weeks I’ve heard a lot of people raving about the improvements brought by Internet Explorer 8 compared to its predecessors. So, when a client was having problems performance problems working on a large page containing multiple forms, I suggested that they upgrade from Internet Explorer 6 to 8. Normally, I’d suggest upgrading to Safari (my personal favourite) or Firefox (fantastic for development), however the client prefers to stick with what is provided by Microsoft (fair enough!). Anyway, after upgrading to IE 8 the client started complaining big time even slower response times. To test the claim I upgraded IE7 to IE8 on my VMWare virtual machine running Windows XP.  After the smooth installation of IE8 (and a restart) I launched the application and timed the performance. I was in shock! The action to be benchmarked was pretty simple. Open a modal dialogue box inside the webpage by the press of a button (Ajax), in the modal dialog text would be entered, a file would be attached and then saving the entered data and closing the modal dialogue box by pressing a save button (also Ajax). So the action is 100% Ajax. Below are my benchmarks:

Action / Browser Firefox 3 Internext Explorer 8
Opening the modal dialogue 323ms 3sec
Saving and closing the modal dialogue 5sec 15sec

After careful examination I found that on Firefox, once the Ajax response was returned to the browser from the server the output was almost rendered immediately (between 100 and 300 ms), where on Internet Explorer, it took between 5-10 seconds to render the output. I believe this is because the page is large (borderline huge), and for some reason IE is not optimised to quickly find the place of insertion for the Ajax response.

I haven’t tried out IE8 on small pages, but so far I’m not impressed unfortunately. On a positive note, IE8 is by far more standard complaint than IE6.

Back in the saddle

0

Written on June 1, 2009 by Allan Lykke Christensen

Once again summer has reached Denmark. A few weeks ago I got my old bike out of the store and had it serviced along with getting a baby chair fixed. I’ve been dreading trying to cycle with the baby as I always thought that Baby Nikh would struggle and try to get out. Man, was I in for a surprise. Nikh absolutely loved sitting in the chair and is completely calm while in traffic. So for the past two weeks I’ve been dropping Nikh at day care before going to work, something we have both enjoyed. This evening the weather was so nice that I decided to take Nikh for a ride. We went all the way down town and back.

To anyone considering getting on the bike instead of the car, don’t hesitate! Cycling is very nice and enjoyable – especially when the sun is shining. Take your time and don’t let all the “pros” scare you. I huff and I puff when I go up those hills, but I don’t care.. feels very good afterwards.

Sending files through action listeners

2

Written on March 16, 2009 by Allan Lykke Christensen

For this weeks JSF tip, I’ll show you how to send binary data (such as a file) to the user by way of an action handler or listener.

Say, you want to generate a custom PDF and send it to the user as he clicks a link. You need a JSF page, and a backing bean.

Your JSF page may look like this:

<h:form>
    <h:commandLink id="lnkDownload"
                   actionListener="#{myBean.onDownload}"
                   target="_blank"
                   value="Download PDF"  />
</h:form>

Your JSF backing bean may look like this:

public MyBean {
 
    public void onDownload(ActionEvent event) {
         try {
            // here you need to get the byte[] representation of 
            // the file you want to send
            byte[] binary_data = ;
            String filename = "generated_file.pdf”;
            FacesContext fctx = FacesContext.getCurrentInstance();   
            ExternalContext ectx = fctx.getExternalContext();
 
            HttpServletResponse response = (HttpServletResponse) ectx.getResponse();
            response.setHeader("Content-Disposition", "attachment; filename=\"" + filename + "\"");
            response.setHeader("Content-Transfer-Encoding", "Binary");
            response.setHeader("Pragma", "private");
            response.setHeader("cache-control", "private, must-revalidate");
 
            ServletOutputStream outs = response.getOutputStream();
            outs.write(binary_data);
            outs.flush();
            outs.close();
            response.flushBuffer();
 
            fctx.responseComplete();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
}

That’s it for today.

P.S. alternatively you can use this component which is less code intensive: http://kenai.com/projects/scales/pages/Download

JSF and I18N

8

Written on March 9, 2009 by Allan Lykke Christensen

It has been a busy year so far. Every year I start out thinking that I really need to relax because the previous year was too hectic, but every year it ends up being much more hectic. Anyway, I thought I’d post a JSF quick time that might shave some headache for people developing internationalised applications.

Most JSF developers are aware of the resource-bundle tag in faces-config. Using this tag you can specify a resource bundle that should be available to all your pages using a given variable. For example, the code below will make a variable, msgs, available in all your pages without having to use the loadBundle tag.

<faces-config version="1.2">
...
    <application>
        <resource-bundle>
            <base-name>my.class.path.Messages</base-name>
            <var>msgs</var>
        </resource-bundle>
    </application>
...
</faces-config>

So, say that Messages.properties contains the following:

HELLO_WHAT_IS_YOUR_NAME=Hello, what’s your name?

you can from any page reference this text by writing:

<h:outputText value=”#{mgs.HELLO_WHAT_IS_YOUR_NAME}/>

or

<h:outputText value=”#{mgs[‘HELLO_WHAT_IS_YOUR_NAME’]}/>

I prefer the former as my favourite IDE (NetBeans) support code completion for all the messages in a managed resource bundle.

So far so good. But what if you want to do something a bit more advanced, such as outputting “Hello Allan, welcome to my site. Your last visit was 7. February 2009 at 10:45”. You are not limited to static text in your resource bundle. You can provide placeholders for content that will be replaced at run-time. Let’s have a look at the Message.properties:

WELCOME_MESSAGE=Hello {0}, welcome to my site. Your last visit was {1,date,long} at {1,time,short}

You’ll notice that the message is parameterised using two parameters. The first parameter we are expecting a string containing the name of the user, the second parameter is a java.util.Date containing both the date and time when user last visited the site. Notice that I’ve reused the second paramenter ({1}), one time for the date and the other for the time. On your JSF page you would use the message as follows (imaging that you have a bean called welcome containing a property for getting the name of the user and last visit):

<h:outputFormat value=”#{msgs.WELCOME_MESSAGE}>
    <f:param value=”#{welcome.userName}/>
    <f:param value=”#{welcome.lastVisit}/>
</h:outputFormat>

Pretty neat, eh?

What about the classical case of singular and plural messages? Imagine that you want to display the number of records in a table “There are 10 records in the table”. If the Message.properties contained:

RECORDS_IN_TABLE=There are {0} records in the table

You’d end up an embarrassing problem if there was only one record in the table:

“There are 1 records in the table” (This sentence is grammatical incorrect)

Instead you would want it to output:

“There is 1 record in the table”

To do this, you have to use the choice pattern:

RECORDS_IN_TABLE=There {0, choice, 0#are|1#is|2#are} {0} {0, choice, 0#records|1#record|2#records}

The format might look a bit awkward, but once you have understood the pattern it is simple:

{0,choice means, taking the first parameter and base the output on a choice of formats
0#are if the first parameter contains 0 (or below), then it should print “are”
|1#is or, if the first parameter contain 1, then it should print “is”
|2#are} or, if the first parameter contains 2 (or above), then it should print “are”

Now, that is nice! So let’s examine the output of these examples:

<h:outputFormat value=”#{msgs.RECORDS_IN_TABLE}>
    <f:param value=”#{0}/>
</h:outputFormat>
There are 0 records in the table
<h:outputFormat value=”#{msgs.RECORDS_IN_TABLE}>
    <f:param value=”#{1}/>
</h:outputFormat>
There is 1 record in the table
<h:outputFormat value=”#{msgs.RECORDS_IN_TABLE}>
    <f:param value=”#{2}/>
</h:outputFormat>
There are 2 records in the table
<h:outputFormat value=”#{msgs.RECORDS_IN_TABLE}>
    <f:param value=”#{10}/>
</h:outputFormat>
There are 10 records in the table

Enjoy!