Pages

Monday, March 12, 2012

Using the Fast Code Eclipse Plugin

I recently discovered an eclipse plugin that I've been needing since I started coding. On several occasions I started down the path of writing my own but quickly got lost in the world of eclipse and ran out of time. Out of the box, the fast code plugin generates many types of code/xml, but the part that I really like is its support for custom templates.

How to Write Your Own Template
Here are the steps that I used to create my own template which generates a spring RowMapper for a JdbcDaoSupport class.

Start with exporting templates using menu Fast Code | Templates | Export Templates:


Choosing templates-config.xml (or all) creates a new project in my workspace:

Next, I altered the exported templates-config.xml file and added my own custom template:
    <template type="Create Spring Detail Mapper">
        <description></description>
        <variation></variation>
        <class-pattern></class-pattern>
        <getter-setter>getter-setter</getter-setter>
        <allowed-file-extensions>java</allowed-file-extensions>
        <number-required-classes>1</number-required-classes>
        <allow-multiple-variation>false</allow-multiple-variation>
        <template-body>
            <![CDATA[
      private class ${class_name}Mapper implements RowMapper <${class_name}>{
          public ${class_name} mapRow(ResultSet rs, int line) throws SQLException {
              ${class_name} inst = new ${class_name}();

                #foreach ($field in ${fields})
                    #if (${field.type.endsWith("String")})
                        inst.${field.setter}(rs.getString(""));
                    #else                
                        inst.${field.setter}(rs.getInt("")); // type not String, assume int
                    #end
                #end
                    return inst;
          }
      }
              

            ]]>
        </template-body>
    </template>
To test the result I import the template back into fast code using menu Fast Code | Templates | Import Templates, then open up a java class that needs the mapper and execute the template using menu Fast Code | Templates | Create New Snippet. Pick my template, class, fields and presto:
    private class ContactBeanMapper implements RowMapper<ContactBean> {
        public ContactBean mapRow(ResultSet rs, int line) throws SQLException {
            ContactBean inst = new ContactBean();
            inst.setName(rs.getString(""));
            inst.setPhone(rs.getString(""));
            return inst;
        }
    }
This may not seem like a big deal because I only have two fields in class ContactBean. It really pays off when I have a dozen or more fields.
I did find a few quirks with the plugin - it looks like the custom templates need to be reloaded every time eclipse is restarted, and the import/export mechanism seems to make a service call to localhost so make sure that the eclipse network proxy preference is configured correctly.

In short - I can create a new template whenever I want to generate some code or configuration file based on the definition of a java class.  In another blog post, I use it to generate a javascript clone of a java bean.

Thursday, March 8, 2012

Debugging Dojo with Chrome

As a web developer I spend many hours working with javascript libraries like dojo. Unfortunately, in many cases the javascript in these libraries is compressed making it very difficult to trace in a debug session.

Chrome is Your New Best Friend
Google's chrome developer tools has many bells and whistles, some of which I've only discovered in the last week. One feature that I think is worthy of mention is the pretty print button, tucked away at the bottom of the page in the status bar.


Click on the button and dojo.js goes from this:


to this:


Some of the variables are still compressed, but now the code becomes legible and breakpoints can be added with ease.

Yes, it also works with JQuery.

Tuesday, January 17, 2012

XML to JSON Converter Builder

Today I had the opportunity to use the xml to json converter builder for a project I'm working on and found that the documentation was a little lacking. Searching google for help netted me next to nothing so I figured it was time for a blog entry.

Why is This Not Working?
The key to getting this feature working is to understand that the builder on its own doesn't really do anything useful. It just provides a method that must be invoked somewhere else, some code that produces the JSON notation. The callback builder input field is text which is prepended to the output of this method. For example if I have these values


with the following html in a page builder:
<html>
    <head><title>Default Test Page</title></head>
    <body>
   
        
    <script type="text/javascript">
    function dumpJson(json){
       console.log(json);
    }
    </script>
    
    <span name="script1"/>       
    </body>
</html>
all that's missing now (and this is important) is a call to the generated method, in my case using a client javascript builder:

The output html looks like this:
<html> 
<head>
<title>Default Test Page</title>
</head> 
<body> 
<script type="text/javascript"> 
function dumpJson(json){ 
   console.log(json); 
} 
</script> 
 
<script name="script1" type="text/javascript">dumpJson({"evaluationDetail":{....})</script>         
    
</body> 
</html>

Hopefully someone will stumble on this blog before they pull their hair out trying to figure out how to use this builder.

Tuesday, December 27, 2011

Using Fingerprint Scanner on Ubuntu

I recently acquired a new Lenovo W520 which included a biometric fingerprint scanner and since I generally shun windows in favor of Ubuntu 11.10, I really wanted to be able to use the scanner with Ubuntu.

Open Source Sweetness
Setting up the fingerprint reader on Ubuntu was a piece of cake. I just installed this fingerprint application and within seconds I was recording my index finger and using it to unlock my screen saver. It even works with sudo commands, kudos to the guys that put this together!

I think my only gripe, and this seems to be a popular one, is that the gui could use a little polish. So I decided to pull out my C++ skills of yore and see if I could make a few changes - this is open source after all and anyone brave enough can get the code and compile it.

Not So Easy
As with most open source bundles, I found a readme file with directions on how to build the package. Unfortunately that didn't work for me, I ran into a compile error:
In file included from ../../src/MainWindowImpl.cpp:46:0:
../../src/../include/UserSettings.h:30:20: fatal error: QtCrypto: No such file or directory
compilation terminated.
make[2]: *** [MainWindowImpl.o] Error 1
make[2]: Leaving directory `/home/dsixe/Downloads/fingerprint-gui-1.03/bin/fingerprint-gui'
make[1]: *** [sub-fingerprint-gui-make_default] Error 2
make[1]: Leaving directory `/home/dsixe/Downloads/fingerprint-gui-1.03/bin'
make: *** [sub-bin-make_default] Error 2

Taking a look at the makefile in /fingerprint-gui-1.03/bin/fingerprint-gui I found that a reference to QtCrypto was missing, so I added it:
INCPATH       = -I/usr/share/qt4/mkspecs/linux-g++-64 -I. -I/usr/include/QtCrypto -I/usr/include/qt4/QtCore -I/usr/include/qt4/QtGui -I/usr/include/qt4/QtXml -I/usr/include/qt4 -I. -I../../include -I../../upek/include -I. -I.
Note that for some reason QtCrypto doesn't live in qt4 like the other Qt libraries.

Recompile, now I see:
g++ -m64 -Wl,-O1 -o fingerprint-gui DeviceHandler.o PermissionHandler.o AboutImpl.o ExistDialogImpl.o Fingerprint.o FingerprintData.o UpekDevice.o GenericDevice.o FingerprintGUI.o MainWindowImpl.o SavedDialogImpl.o MessageDialogImpl.o PamTester.o xmlwriter.o UserSettings.o UsbDevice.o moc_DeviceHandler.o moc_AboutImpl.o moc_ExistDialogImpl.o moc_Fingerprint.o moc_FingerprintDevice.o moc_FingerprintData.o moc_MainWindowImpl.o moc_SavedDialogImpl.o moc_MessageDialogImpl.o moc_PamTester.o qrc_GUI-res.o qrc_About-res.o    -L/usr/lib/x86_64-linux-gnu -lusb-1.0 -lfprint -lpam -ldl -lpthread -lQtXml -lQtGui -lQtCore
UserSettings.o: In function `UserSettings::UserSettings(char*)':
UserSettings.cpp:(.text+0x1fcc): undefined reference to `QCA::Cipher::~Cipher()'
UserSettings.cpp:(.text+0x1fd4): undefined reference to `QCA::SecureArray::~SecureArray()'
UserSettings.cpp:(.text+0x1fe1): undefined reference to `QCA::SecureArray::~SecureArray()'
It took me a long time to figure out that it was failing to link in the QtCrypto library. Resolved by adding -lqca to the same makefile:
LIBS          = $(SUBLIBS)  -L/usr/lib/x86_64-linux-gnu -lusb-1.0 -lfprint -lpam -ldl -lpthread -lQtXml -lQtGui -lQtCore -lqca
Finally, a clean compile!

Changing the Image
Now that I could compile the code, I went about making a simple change which didn't really involve altering any code. I wanted to change the animated gif file fingerprint-gui-1.03/src/res/Animation.gif to something else, and this required recompiling. For testing purposes I just converted the existing Fingerprint.png file to a gif and renamed it Animation.gif.

Now all I had to do is run make install and it should work. Once again, not so fast, something wasn't working. I finally just reinstalled clean from the repository and manually copied the file myself:
sudo cp fingerprint-gui-1.03/bin/fingerprint-plugin/fingerprint-plugin /usr/lib/fingerprint-gui/fingerprint-plugin
And now this is what I see when prompted to scan my finger:

Thursday, October 20, 2011

Using Environment Entries with WebSphere

I just spent the last few days trying to find an easy way to configure my web services deployed as annotated POJOs and I think I've found it. The idea is to provide an easy mechanism to change values through the administration console and have the java code pick up those changes at run time without redeploying. I thought about using a property file but this is inconvenient because we have a clustered environment and editing files in a deployment directory isn't the best idea.

@Resource Saves the Day
Anybody who used JNDI before the days of annotations knows that old style lookups were a little bit of a pain, but maybe I’m just being difficult. Here’s how I got it working - first thing is to add the proper entries in my web.xml:
<web-app...> ... <env-entry> <env-entry-name>DsixE/SomeParameter</env-entry-name> <env-entry-type>java.lang.String</env-entry-type> <env-entry-value>This really rocks</env-entry-value> </env-entry> ... </web-app>
Next I add an annotation to my code:
    @Resource(name="DsixE/SomeParameter")
    private String someParamter;
I build a WAR, deploy it to WebSphere and notice that I have a new entry in the administration console:


…. which allows me to change the value at any time:


Now the container injects the value defined into member variable someParameter at run time. This is the first time I’ve really used an <env-entry> so I guess this old dog can still learn new tricks.


Tuesday, October 18, 2011

Using Browser Web Services with SSO


A while ago I discussed how web services can be invoked using javascript in a browser, but there was a nagging problem that prevented me from deploying it into a production environment - how do I prevent a hacker from manipulating the user identifier in a request? Suppose we have an application that displays an end user's payroll information. In this case we need web service operation will retrieve information specific to the user's ID. We can't just send the user's identifier in the request because that would allow spoofing the ID of another person resulting in a breach of privacy.

Retrieving the User's Identity from the Container
In a servlet, it is relatively easy to retrieve the user's identity from the request, but this presents a problem if we're using JAX-WS annotated POJOs which have no concept of HTTP or a request object. How the heck do I figure out what the user ID is? I spent many hours looking at WS-Security but I got lost in all the details about policy sets and bindings and I just couldn't get anything to work. Then I found this writeup on developerworks:
http://www.ibm.com/developerworks/websphere/library/techarticles/1001_chung/1001_chung.html?ca=drs-

It is very close to what I wanted to do, but it uses WS-Security and I was dead in the water. Instead, I fell back on servlet security configuration to get the container to use the SSO LTPA token originating from WebSeal. This is the same way I would handle the situation if I was coding a servlet, but again - I'm working with POJOs, so no request object available. The developerworks article revealed the missing piece:
@Resource WebServiceContext wsCtx;

Putting it all Together
I coded a POJO and added JAX-WS annotations to expose it as a web service, then I added an @Resource that tells the container to pass the context:
package com.dsixe;

import javax.annotation.Resource;
import javax.jws.WebService;
import javax.xml.ws.WebServiceContext;

@WebService
public class ContactsService {
    @Resource WebServiceContext wsCtx;

    public String getName() {
        String userID = wsCtx.getUserPrincipal().toString();
        
        if (userID.equals("cdomingue"))
            return "Carl";
        if (userID.equals("csmith"))
            return "Christine";
        
        return "unknown: " + userID;
    }
    
}
Until this point I had never even looked at the web.xml bundled with the annotated POJOs into the WAR that I deployed to Axis2 since there are no servlets in it. I added the following security constraints to the web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
  <display-name>Jax-wsPolicyTest</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
  </welcome-file-list>
  
  <security-constraint>
    <web-resource-collection>
      <web-resource-name>ContactsService</web-resource-name>
      <url-pattern>
        /*
      </url-pattern>
    </web-resource-collection>
    <auth-constraint>
      <description>
        Roles allowed to execute ContactsService
      </description>
      <role-name>AllAuthenticatedUsers</role-name>
    </auth-constraint>
  </security-constraint>
  
  <security-role>
    <description>All Authenticated Users Role</description>
    <role-name>AllAuthenticatedUsers</role-name>
  </security-role>  
</web-app>
I then deployed to the container and mapped the AllAuthenticatedUsers security role just like I would for any servlet. Protecting the resource caused the container to populate the WebServiceContext object and then I could retrieve the user ID.

Done!

EDIT: I was researching attachments with JAX-WS and found this very comprehensive writeup which I though would be good to read in this context.

EDIT: Here's another interesting read on this topic.

Monday, September 12, 2011

Can't Start Sametime

My current engagement uses the Lotus Sametime chat client and I use it on a daily (hourly) basis. Today, for no reason that I can discern, I was unable to start up the application after a computer reboot. The install creates a shortcut to C:\Program Files (x86)\IBM\Lotus\Sametime Connect\rcp\rcplauncher.exe and running that executable would do absolutely nothing.

After several attempts to figure out what was going on - including a failed attempt to reinstall the standard client - I found a lock file:
C:\Users\dsixe\AppData\Roaming\Lotus\Sametime\.rcp.lock
Delete the file, problem solved.