Pages

Thursday, December 1, 2016

What is a Java Lambda Expression?

A lambda expression is a shortcut notation for an anonymous class implementation of an interface.


Which Interface? Where is the Type Definition...?

A lambda expression is used in the context of a target method signature. For example the following method signature

     public String doSomething(String s, MyInterface mi){...}

could be invoked with the following code using an anonymous class:

     doSomething("hello", new MyInterface(){
          public void myMethod() { 
               System.out.println("goodbye");}
          });

it can also be invoked with the following lambda expression:

     doSomething("hello", ()->{ System.out.println("goodbye");});



The target method doSomething is expecting two parameters - a String and an instance of MyInterface. The String value is clearly "hello", but the other is not so obvious. What happens here is the compiler sees that an instance of MyInterface needs to be somehow created from this expression and passed as the second parameter:

     ()->{ System.out.println("goodbye");}

To understand how this takes place we need to look at MyInterface

     interface MyInterface {
          public void myMethod();
     }


So what's so special about that interface?

The key characteristic of this interface is that it contains exactly one method definition. This makes it a functional interface, and it could be annotated with @FunctionalInterface for clarity although this is not necessary. Lamba expressions only work with functional interfaces.

Since the compiler needs to create an instance of MyInterface which it can pass to doSomething, it needs an implementation of myMethod.


Where is the compiler going to find an implementation of myMethod?

This is where the lambda expression comes into the picture. A lambda is a shortened syntax for an anonymous class definition, but since the interface contains only one method definition, the compiler can easily fill in the blanks. The left side of the lambda expression is a placeholder for the interface method signature parameters. Without this left side, the implementation would have no point of reference for these parameters.

For example if we change the signature to

     interface MyInterface {
          public void myMethod(int myNum);
     }

Then our lambda would look like this

     (i)->{ System.out.println("goodbye");}

Note that the simple implementation doesn't use the int value (which is ok).


Recap

Take an anonymous class implementation, strike out the unnecessary syntax which the compiler can figure out because there's only one method in the interface, then add a -> 

     doSomething("hello", new MyInterface(){
          public void myMethod()->{ 
               System.out.println("goodbye");}
          });

What's left is a lambda expression!

Tuesday, November 10, 2015

Making HTML readonly Attribute Look Like Disabled

A quick entry in case anybody else runs into this scenario. I have a form with some text boxes which need to display as disabled, but the values aren't being submitted with the form. As it turns out, this is native behavior for the 'disabled' attribute.

The workaround is to use the 'readonly' attribute instead, but the problem with that is it doesn't render with a grayed out background. After fiddling for a while I came up with the following script:


dojo.ready(function(){
    dojo.query("[readonly]").forEach(function(node, index, arr){   
 dojo.attr(node.parentNode,"style", "background-color: #efefef !important");   
    });
 });

Maybe someone else will find this useful.

Thursday, April 30, 2015

Adding a Log4j Console to a Web Application

There's a popular open source jsp that allows changing the log4j levels for a web application called log4jAdmin.jsp that I've been wanting to use for troubleshooting, but using it poses a problem. Typically, deployable artifacts are built by an automated process and are not altered as they make their way through the different environments (development/integration/quality assurance/production). I definitely don't want a log4j administration console finding its way into a production environment as this would allow end users to access it.

So the ideal situation would be to add the jsp to the application after it has been deployed. I could have the system administrators add the file to the WebSphere installedApps directory, but this isn't recommended (and they would likely not agree to do this anyways).

A proper alternative is to use WebSphere's deployment process. Instead of updating an application using the default option, look further below on the page:



The contents of the zip should mirror the exploded folder structure in installedApps. In this case the zip contains a single JSP:



Any number of files can be injected into a deployed application using this technique, but in this particular instance I use it to manage Log4j log levels.

Thursday, February 26, 2015

Error Running wsadmin.sh

I've been making extensive use of wsadmin.sh as part of scripted WebSphere application installs to virtual machines, and today a script which I had written a long time ago started to throw the following error:

com.ibm.websphere.management.exception.AdminException: ADMA0043E: /tmp/app9215861615159415312.ear does not exist for installation.

I didn't find any conclusive solution to the error on the web although some suggested there was a mismatch in the location of the temp folder. I changed the websphere variable (Environment > Websphere variables) from

WAS_TEMP_DIR = ${USER_INSTALL_ROOT}/temp

to

WAS_TEMP_DIR = /tmp

Restarted the server and the problem went away. I have no idea why this worked before, but I guess it's fixed now.

Thursday, July 31, 2014

Error Messages using the WEF JAXB Plugin

I just resolved an issue related to my plugin for WEF which generates JAXB code for easy conversion to/from IXML and I thought I'd write it up before I forget.

The error message looks something like this:

java.lang.ClassCastException: javax.xml.bind.JAXBElement incompatible with com.dsixe.jaxbgen....

This seems to be caused by a variance in the schema generated by the SQL Call builder where the topmost wrapper element is not annotated as root element by JAXB. The problem is solved by using code which looks like this:


javax.xml.bind.JAXBElement jaxbElement = (javax.xml.bind.JAXBElement)Transform.convertToObject(available, "http://com/dsixe/Roles", com.dsixe.jaxbgen.rolesTransformSchema.RowSetType.class);

com.dsixe.jaxbgen.rolesTransformSchema.RowSetType iAvailable = (com.dsixe.jaxbgen.rolesTransformSchema.RowSetType) jaxbElement.getValue(); 
We need to initially cast to JAXBElement and then use getValue() to retrieve the object. One more line of code fixes the problem.

Friday, April 18, 2014

Defaulting WEF Builder Input Groups as Expanded

A little used WEF feature is the comments builder input which appears on all builder editors. The input always displays at the very top under the collapsed group header "Properties" along with the builder enable/disable input. The primary reason it is little used is because the "Properties" group is collapsed by default and therefore not immediately visible. This can be easily changed through these steps:

1) Extract the Base.bdef file from \WebContent\WEB-INF\builders\corebuilders.zip
2) Copy the file to \WebContent\WEB-INF\builders\com\bowstreet\core
3) Edit the highlighted element from true to false



Restart your eclipse workspace and the comments builder input should now be visible by default.


Remember to restart this process when you upgrade to a new version of WEF since this effectively overrides the designer's defaults.

Tuesday, March 4, 2014

REST vs SOAP

For some reason people who work in technology seem to have well defined opinions about matters and will often go to great lengths to defend those opinions. Think about the unix vi editor (I dislike), windows vs unix, windows vs apple. These topics will often lead to flame wars. Today I'm going to weigh in on web service transports and hope I don't light up a wildfire.

Early Binding vs Late Binding

I'm a supporter of the SOAP protocol for most cases unless the service is to be consumed by a javascript application. I've been thinking about why it is that I have this preference and I think I know exactly why. It comes down to early (or design time) binding of an external component vs late (or runtime) binding. This concept has been around since the early days of computer science, the idea being that a sub component can declare ahead of time what kind of operation signatures it supports so that these can be confirmed by the compiler. If a piece of code which has been bound at compile time fails at run time then we immediately know there is a conflict in versions. A similar concept is found in strongly typed languages. I can think of a few examples of this:
  • java interfaces
  • C/C++ header files
  • WSDL - web service definition language
The bad part of using SOAP is that it requires additional overhead, but in simple cases this is little more that a message envelope.

The other side of the argument is run time binding where we find out about the operation signatures when the code is actually executed. Now this isn't as bad as one thinks because the component owner will always provide details about the shape of the data and what is expected so the consumer that write appropriate code. The bad part of this is that the service provider can change anything at any time without notifying the consumers, resulting in an error when the consumer attempts to invoke an operation. There is a similar concept in weakly typed languages:
  • javascript
  • visual basic
  • assembly language

How to Choose?

The short answer is that this whole argument is moot if the software is well designed and written. All the valuable business logic should reside in java bean POJOs and then combined with a runtime container such as an enterprise service bus (ESB) or a service component architecture (SCA). The container manages exposing the POJO business logic using any number of transport protocols and can be configured at time of deployment. If an ESB or SCA is not available, then a similar result can be attained by coding a thin delegate using JAX-RS or JAX-WS.

Why do I prefer early binding? I don't like doing emergency production troubleshooting and with early binding I can eliminate one more point of failure.

Tuesday, January 21, 2014

Transform IXml with JAXB


This posting simply redirects to an article I've added to IBM's community.

http://www-10.lotus.com/ldd/pfwiki.nsf/dx/Transform_IXml_with_JAXB

Saturday, November 2, 2013

Building Reusable Web Services

I've worked on many projects for various organizations, both large and small, during my career in IT, and it's sad to say that reusability of web services is something that is very difficult to attain. We all learn about good design and coding practices, and agree that reusability is cornerstone to building great applications, so why do so many organizations get it wrong?

Qualities of a Good Web Service

Let's start by identifying what can be considered to be traits of a good web service
  • encapsulation of knowledge
  • fine and coarse grained operations
  • self documenting
  • application agnostic
  • ease of use
There are other traits such as security, but these are more technical aspects that are well described through the WS-* specifications. Most concepts are easier explained through an example, and in the context of this article I'll use an automobile's construction process as a guide. If we consider a web service that provides operations to assemble a car, what would that service look like?

Fine and Coarse Grained Operations

Every good developer understands the advantage of breaking up their code into reusable parts that can be invoked from different sources. Somehow this approach never translates itself into web services. It seems that developers are so focused on reaching the next milestone that they don't take the time to ask a very basic question.

Can this operation be broken up into useful parts?

Agile methodology involves delivering functionality with short development cycles, and this makes it easy to forget about the larger context. Developers may be focused on writing a service operation to deliver a car's door, that they don't think how a door is composed of many pieces. What happens if in the next development cycle there's a need for an operation to deliver a door mirror or a window control switch (these are parts of a car's door)? Instead of writing a coarse grained operation that looks like this:

CarDoor getCarDoor(){
}

it can be broken up into several fine grained operations

DoorMirror getMirror(){
}

DoorSwitch[] getSwitches(){
}

CarDoor getCarDoor(){
   CarDoor = getMirror() + getSwitches();
}


With little additional work, the service is now much more useful and can handle future requests that may not have been anticipated.

 

Encapsulation of Knowledge

A big reason organizations decide to develop web services is not only to expose back end systems, but also to encapsulate/hide the complexity of those systems. Software applications have a way of far outliving their original lifespan due to embedded business logic or the cost of rewriting them. A web service can be written that leaks the internal workings of the system it is exposing.

This is bad. How do these leaks happen?

Let's take the car example which is manufactured by the fictitious Acme car company. As is the case for most industries, Acme uses an internal vocabulary to describe parts of their cars (I'm making these up):
  • windows are called "clear silica substrate" (or CSS)
  • door switches are called by their product codes such as D39's
Everybody working at Acme knows what that a car door has two D39's and a CSS, but these terms should not be exposed in a service operation. What's more, if the manufacturer of the D39's goes out of business (or the underlying software system is replaced) any references to these terms suddenly don't make sense. Instead of exposing this object:

CarDoor {
    CSS cssItemNumber;
    D39[] switches;
}

use something that is agnostic of the underlying system but supports the business objects:

CarDoor{
    Window windowID;
    Switch[] doorSwitchID; 
}

This approach makes the operations easy to understand, and cuts down on the need to document.


Self Documenting

The bane of all software development is documentation. Nobody likes to do it, and when done, it gets misplaced or quickly falls out of date with the implementation. I can write about how developers need to get their act together, but the truth is that it just doesn't happen that way. They can be coaxed into writing a few lines to describe their functions but formal documentation is not realistic. An alternative way to handle this situation is to write a service interface that uses business terms instead of technical ones and exposes explicit, fine grained operations. The following is an example of a poor interface to handle seats in a car:

handleSeat(String operation, Seat newSeat, Seat oldSeat, String seatID){
    if operation = "add" then ....
    if operation = "remove" then ...
    if operation = "replace" then ...
}

The above operation requires documentation that describes the options for "add", "remove" and "replace". It is impossible that a consumer of the service will be able to guess the values without referring to some documentation (which is probably non existent or out of date). What's more is that because the operation requires a "Seat" object for "add", the consumer also needs to pass one for "remove", even though it is not necessary for that particular operation. A better interface looks like this:

addSeat(Seat seat){
}

removeSeat(String seatID){
}

replaceSeat(Seat newSeat, Seat oldSeat){
}

Again, just a little more effort makes the service infinitely more usable. A business subject matter expert (SME) should be able to understand the interface.

Application Agnostic

In summary, don't create services for a specific application, instead code generic operations that can be used by any application. Acme needs a service that supplies wheels for it's latest model, the XJ2000. The immediate thought is to create operation like so:

Wheel[] getXJ200Wheels(){
}

Six months later management decides that the web service has worked out so well, they want to leverage their investment to provide wheels for an older model, the FRT3000. The FRT3000 is a sport model which has two kinds of wheels, 18 inch alloys as well as 16 inch standard. Unfortunately the existing operation cannot be reused because it doesn't take into consideration that wheels come in different sizes and will have to be rewritten.

Operations should reflect the business knowledge domain (in this case, the auto industry), not the application's.

 

 Ease of Use

Here's a common scenario that unfolds when a developer begins to work on a new feature. They look at a document from the design team and are made aware of some existing service operations that should be leveraged to accelerate their work. They pull up the service with a testing tool and attempt to make use of it. If
  • they can't find the WSDL document 
  • the service is not well documented
  • they can't find the correct parameters to invoke the service operations
  • the operations are too difficult to understand or are perceived to be inadequate
  • they have an alternative way to get their work completed
they won't use it and will write their own code. The developer is on a tight deadline to deliver and will avoid something that's difficult to use.

So what's the answer?

A simple guiding principal I try to follow is this - write the service as if it was exposed to the real world instead of some internal team. Would Bob at Universal Motor Co understand my service? The great appeal of a service oriented architecture (SOA) is writing once and reusing throughout the organization, unfortunately the investment doesn't pay off it it is not done right.


Thursday, August 8, 2013

Logging SOAP Requests in WEF

Some of my projects make extensive use of the web service call builder and I often need to look at the outgoing SOAP requests when a problem crops up. This is easy by turning on logging in the advanced section of the builder, but doing this on every instance of the builder is tedious.


JAX-WS SOAP Handler
I stumbled on this article where Rob Flynn describes a technique to handle SOAP requests from a central point using the bowstreet.serviceCall.jaxwsHandler override. I used this approach to add some log4j logging statements, this way I don't have to go into each builder and tweak the input and redeploy, I can just change the log4j.properties. Unbelievably, a google search shows that there are no other references to this override - not even in IBM's documentation. I have to wonder how many other awesome WEF features lay undocumented (ask me about pageprocessors.properties).

public class SoapHandler extends BaseJaxWsHandler {

    static Logger logger = Logger.getLogger(SoapHandler.class);
    
    /* 
     * Populate the user's identity into the SOAP request.
     */
    public boolean handleOutboundMessage(SOAPMessageContext context) {
        // bail if logging not enabled  
        if (!logger.isInfoEnabled())
            return;
         logMessage(context);
        
        return true;
    }
    
    
    /**
     * Log the SOAP message.
     * @param context
     */
    private void logMessage(SOAPMessageContext context) {

        // bail if logging not enabled  
        if (!logger.isInfoEnabled())
            return;
        
        try {
            HashMap hm = (HashMap) context.get(com.ibm.websphere.webservices.Constants.REQUEST_TRANSPORT_PROPERTIES);
            Set keys = hm.keySet();
            
            logger.info(">> Start SOAP message log");
            logger.info("calling Model=" + getWebappAccess().getModelName());
            logger.info(this.getEndPointUrl(context));

            for (Object key : keys){
                logger.info("HTTP header -> " + key + "=" + hm.get(key));
            }
            
            logger.info(context.getMessage().getSOAPPart().getEnvelope());
            logger.info(">> End SOAP message log\n");
        } catch (SOAPException e) {
            // we're just logging, not sure we care that an exception is thrown
        }
    }


}

The parent class BaseJaxWsHandler can be found on Rob's entry mentioned above.

Friday, May 31, 2013

Product Codes for IBM Software

In many past instances I've been really confused by the download process for IBM Passport. Searching for the correct download package is like trying to find a needle in a haystack.

This week I stumbled on a page I had been looking for, here is a link to the product codes for WebSphere Portal 8:

http://www-10.lotus.com/ldd/portalwiki.nsf/xpDocViewer.xsp?lookupName=IBM WebSphere Portal 8 Product Documentation#action=openDocument&res_title=Electronic_images_wp8&content=pdcontent

Tuesday, April 30, 2013

Using the Localized Resource Builder

Last week I had to use the localized resource builder for localizing an application for one of my clients. After searching a while I did find an article about the topic, and although it didn't meet my needs, it did point me in the right direction.

Localize with the Data Page Builder
Here's the scenario - I have a custom HTML page that has descriptive text to be localized. This is easily accomplished by adding a second data page builder (the first is for the data on the page) that points to the variable created by the localized resource builder.

Here's the HTML I used for page1:
<html>
    <head><title>Default Test Page</title></head>
    <body>
            <div name="contact">
              <span name="name_label"/>
              <span name="name"></span>
<br>
              <span name="phone_label"/>
              <span name="phone"></span>
            </div>
            
            <span name="btn"/>
    </body>
</html>

and here's the default resource bundle:
button_label=click me
phone_label=Phone number:
name_label=Name:
I create a data page builder and point to the variable Variables/LocaleData created by the local resource builder:


When I run the model I get this output:

To test for French language I add a new resource bundle:
button_label=clique moi
phone_label=Numero de telephone:
name_label=Nom:

and change the language to fr:
resulting in this output:

Monday, April 1, 2013

Deploying WARs With a Script

I've wanted to figure this out for a long time and yesterday I finally put together a script that updates a WAR to WebSphere. I have WebSphere Portal running locally on my development box and running the following command will use wsadmin to update a freshly built WAR to the server:

sudo /opt/IBM/WPS8/WebSphere/wp_profile/bin/wsadmin.sh -conntype SOAP -user wpsadmin -password wpsadmin -c "\$AdminApp update POC_WS_war app {-operation update -contents /home/dsixe/WEF/POC_WS.war}"

It took me a while to find out why my script wasn't working, the $AdminApp command requires a \ prefix on non-windows platforms. I initially thought that somebody else would have published a clear example of how to deploy with a script, but I just couldn't find one with repeated google searches (at least none that had the \ prefix).

Monday, December 31, 2012

Documenting WEF Models

Web Experience Factory is a pretty good tool for rapid development, but its designer lacks automated documentation that can be used to explain an application to a new developer. Models can get extremely complicated, especially when they're assembled by developers who are just starting to use the tool. This article describes how graphs can be generated using eclipse.

Using an Eclipse Plugin to Generate Graphs
I've worked with projects that, in some cases, imported dozens of other models, making it quite challenging to follow a sequence of events. About a year ago I had the idea of generating a graph showing how models are imported into each other, but quickly got lost in the details of graphing within eclipse.
I recently stumbled on an open source application named Graphviz, and when I saw the simplicity of using a DOT file to describe a graph, I was able to quickly develop a plugin to inspect a WEF model and produce a graph of it.

An easy candidate for a graph is tracing how models import other models. The plugin does this by recursively traversing the import builders in each model, producing a graph similar to this example.


Once I figured that out, I was able to add some more to the plugin, producing a graph of service consumer operation calls like the one below. This graph indicates that model_4 contains an action list builder named alTest that invokes the doSomeOperation operation exposed by the service consumer builder named svcConsumer.

The graph of action list calls (builders which invoke action lists) is very similar to the one above, except the target node is an action list instead of a service operation.
After the plugin is installed by following these instructions, you will see the following submenu when right clicking on a model.


Just select the graph you wish to generate and it will appear in an eclipse browser window. Although I developed this tool for my own use, I'm making it available free of charge to anyone.

If the tool doesn't work for you, then please leave me a message on this blog (or email me).


References: Download plugin from http://www.dsixe.com/eclipse

Tuesday, December 4, 2012

Using com.bowstreet.builders.webapp.api.Method

I've been writing some more custom builders recently and had a hard time figuring out how to generate a method with arguments.

Below is an example:

        Method method = new Method(builderCall, genContext);
        method.setName("myMethod");
        IXml args = null;
        
        try {
           args = XmlUtil.parseXml("<top><Argument><Name>msgValue</Name><Type>String</Type></Argument></top>");
        } catch (IOException e) {
           e.printStackTrace();
        }
        
        method.setArguments(args);
        StringBuffer sb = new StringBuffer("{ \n");
        sb.append("    webAppAccess.getVariables().getVariable(\"myVar\").setValue(msgValue); \n");
        sb.append("}");
        method.setBody(sb.toString());
        method.invokeBuilder();

and here's the code added to the model on regen:

/**
 * Generated Method [myMethod]
 */
public void myMethod(WebAppAccess webAppAccess, String msgValue)
{ 
    webAppAccess.getVariables().getVariable("myVar").setValue(msgValue); 
}
I figured out the magic XML for method.setArguments() by looking at the model XML for a standard method builder.

Wednesday, November 28, 2012

WEF Profiling Explained

Profiling is a frequently misunderstood concept in web experience factory. This blog entry describes profiling by comparing it to java code, something that more developers are familiar with.

Comparing Profiles to Java Code
Many people struggle with the concept of profiling and profile sets, but it can be closely compared to a conditional statement in java. Suppose that we have a button that needs to be displayed if the application is accessed from an android device. Coding this using java would look something like this (depending on the framework):
if (request.getHeader("User-Agent") == "android"){
   button.visible = true;
}

The same can be accomplished with WEF profiling except we don't have any code to work with, only a button builder with inputs. Ideally, we would want to apply the results of profiling to the builder enable input, setting it to true or false which would effectively replicate what the java code above does.

Think of a profile set as a collection of profiles and the selection of a given profile is the result of a conditional statement. That conditional statement is controlled by a selection handler. Let's look at the code above again from this perspective
if (profileset.selectionHandler.result == "android"){
   button.enable = true;
}

The profile set selection handler is the engine that controls which profile is selected. In this particular case, we're using the mobile selection handler which contains logic that looks at the HTTP request user agent header to determine which profile is selected. Moving one step further, the selection handler doesn't really return a value like "android" per se, it chooses a profile.

Suppose we not only want to control the visibility of a button, but we also want to execute a call to a service provider operation when the application is accessed from an android device. In java, we would add some logic
if (profileset.selectionHandler.profile.name == "android"){
   button.enable = true;
   invokeSomeOperation();
}

For the sake of making this explanation clearer, let's also add some code to handle iPhones as well as a handler for the default case
if (profileset.selectionHandler.profile.name == "android"){
   button.enable = true;
   invokeSomeOperation();
}
else if (profileset.selectionHandler.profile.name == "iphone"){
   button.enable = false;
   invokeSomeOperationIPhone();
}
else{
   button.enable = false;
   // do nothing
}

That all seems very obvious if we were using java, but how is it implemented in WEF using profiling?


Here is the detailed profile entry for the button


Similarly, the action list is profiled



and below is the detailed profile entry


Only one profile in any profile set can be active at one time, and profiling is applied when the user session is first initiated. It is not possible to use two different profiles from the same profile set or switch profiles in the same session.





Wednesday, November 7, 2012

WEF and Custom HTML

Working with custom HTML is probably one of the most common patterns I've seen when building an application with web experience factory (WEF). Typically this is a situation where I'm given a really nice HTML stub from a professional web designer and I need to build an application around it.

Don't Fight with WEF
A common mistake I see all the time is a web developer trying to untangle or intercept the code generated by WEF. Don't do it, you're going to lose your mind or create an unmaintainable mess (or both). Here are a few tips that should help:

1 - Turn off the theme
2 - Don't let the data page builder create the UI
3 - Learn how to exploit page automation

Turn off the Theme
There are two ways to accomplish this, adding a theme builder to your model and selecting the individual components, or blanking out the theme file name in the project's override.properties.



The theme is great when using WEF's default user interface, but it just gets in the way of custom HTML.

Dumb Down the Data Page Builder
The data page builder is the heart of page automation in WEF, but sometimes it wants to do too much, and again, gets in the way of custom HTML. We want dumb it down a little by turning off the option to make the UI from data.

In many cases we'll also want to set the page type to view only if we're only displaying data, but this depends on the use case.

Exploit Page Automation
Now that we've turned off some of the noise that we don't need, how do we tell the page automation to place data on our custom HTML? This is easily done by adding our own name attributes to the HTML elements. Whenever page automation finds a value for the name attribute that matches the data specified in the data page variable, it inserts a data value. Take for example the following XML data
<contacts>
   <contact>
      <name>n1</name>
      <phone>p1</phone>
   </contact>
   <contact>
      <name>n2</name>
      <phone>p2</phone>
   </contact>
</contacts>

We can ask page automation to take this custom HTML
<html>
<head>
<title>Default Test Page</title>
</head>
<body>

    <table name="contacts" width="50%">

        <tr align="center">
            <th><span name="nameHeader">Name</span></th>
            <th>Click to update</th>
            <th><span name="phoneHeader">Phone</span></th>
        </tr>

        <tr name="contact" align="center">
            <td><span name="name"></span></td>
            <td><span name="btn"></span></td>
            <td><span name="phone"></span></td>
        </tr>

    </table>

</body>
</html>
to produce a user interface, and this is what we see in the browser when we launch the application







This is how page automation sees the HTML name attributes that we added


You may have noticed that we added sorting capability to the first column, this is standard practice using a data column modifier (DCM) builder. The DCM builder needs to be able to identify the location of the table headers, and since we have custom HTML, we have to do this ourselves by adding a suffix Header to the name attribute in the table header rows.

Also note that the table row identified with the name attribute contact refers to the repeating XML data element contact. Page automation will create a new HTML row for each contact element in our data.

The edit button is there to demonstrate that we can easily add builders that refer to named locations in our HTML, just as if the data page builder had done all the work for us.

More information about manually marking up HTML for page automation can be found here.


Sunday, July 29, 2012

What's in a Portal URL?

I've been working with WebSphere Portal for many years and I always wondered about the format of the URL, but never took the time to track it down. Last week I stumbled on this interesting document that laid it all out.

The short if it is that the typical URL
http://localhost:10039/wps/portal/!ut/p/b0/04_Sj9CPykssy0xPLMnMz0vMAfGjzOKd3R09TMx9DAwsTC0MDTwdPULNzYJdjAxczfXD9aPwKnE0hiowwAEcDfT9fPLT01NT_EtL9Auys9McHRUVAdjo3OY!
is an XML representation of the portal page compressed and encoded with a proprietary algorithm. It turns out there are several alternate URL schemes for WPS, but this one is the most common variation that everyone is familiar with.

No need for me to go into details - the document explains it quite well.


EDIT 09/30/2013: Here's a URL that describes REST services which will encode/decode portal URLs:

http://www-10.lotus.com/ldd/portalwiki.nsf/dx/IBM_WebSphere_Portal_Remote_State_Service_and_Fragment_Service

Tuesday, July 24, 2012

A Lotus Notes Calendar Widget

Most of my blog entries reflect some challenging task that I helped my client complete, this latest one was particularly interesting because there was little documentation to guide us. In fact I'm going to blog about something that I wouldn't recommend to anyone but sometimes there are no easy ways out.

The Requirement for a Calendar
My client wanted to expose their user's lotus notes calendar entries into a JSR 286 portlet but we couldn't find any easy out of the box solutions for this. Since I don't know anything (at all) about lotus domino I turned to a resident expert for advice on how to get my hands on the calendar data. We appeared to have two options:

  • Develop a custom lotus form that would require replicating every user's mailbox
  • Re-purpose an existing form to suit our needs

After much discussion we decided to pursue the second option since we had little time to roll out the portlet and we didn't want to alter the mailbox database of thousands of users.

Tapping into ReadViewEntries
The domino mailbox supports a URL command named ReadViewEntries that can be used to retrieve calendar entries as JSON data. The URL looks something like this
http://yourbox.com/mailServer/mailbox.nsf/Calendar?ReadViewEntries&outputformat=JSON
This request returns calendar entries for a given date range, more details can be found on this cheat sheet. Unfortunately we quickly realized that ReadViewEntries is not really designed for retrieving calendar entries formatted the way we needed. I'm not sure about the real purpose of this form, but I had to reverse engineer the results by creating a test sampling of all the different types of calendar entries (anniversary/meeting/reminder/repeated entries....) and then looking at the result set. Below is the javascript that I created to parse out the data feed
function populateCalendarData(viewentries) {

 var jqueryData = [];

 for ( var x = 0; x < viewentries.viewentry.length; x++) {
     var entry = {};
        entry.type = "meeting";

  var cday = null;
        if (viewentries.viewentry[x].entrydata[0].datetime != undefined){
            cday = viewentries.viewentry[x].entrydata[0].datetime[0];
        }
        else {
            // repeating item shows up with datetimelist
            cday = viewentries.viewentry[x].entrydata[0].datetimelist.datetime[0][0];
        }

  var sd = cday;

  // all day events don't have start dates
        if (viewentries.viewentry[x].entrydata[2].datetime != undefined){
            sd = viewentries.viewentry[x].entrydata[2].datetime[0];
        }
        else {
            entry.type = "all-day";
        }

        var ed = sd;

  if (viewentries.viewentry[x].entrydata[4].datetime != undefined){
      ed = viewentries.viewentry[x].entrydata[4].datetime[0];
  }
  else {
         // appointments don't have end dates
            entry.type = "appointment";
  }

  var startDate = getDate(sd);
  var endDate = getDate(ed);
  var moderator = "";
  var subject = "";
  var location = "";
  
  if (viewentries.viewentry[x].entrydata[5].textlist == undefined){
       // not a meeting type entry. This could be reminder or appointment
      subject = viewentries.viewentry[x].entrydata[5].text[0];
  }
  else{
      // check if a location was provided
      if (viewentries.viewentry[x].entrydata[5].textlist.text.length > 2){
          subject = viewentries.viewentry[x].entrydata[5].textlist.text[0][0];
          location = viewentries.viewentry[x].entrydata[5].textlist.text[1][0];
          moderator = viewentries.viewentry[x].entrydata[5].textlist.text[2][0];
      }
      else {
          subject = viewentries.viewentry[x].entrydata[5].textlist.text[0][0];
          moderator = viewentries.viewentry[x].entrydata[5].textlist.text[1][0];
      }
  }

  // create jquery calendar entry

  entry.date = startDate.getTime().toString();
  entry.title = subject;
  entry.description = "no description available at this time";
  entry.url = "no url";
  entry.end = endDate.getTime().toString();
  entry.location = location;
  
  jqueryData.push(entry);
 }
 
 return jqueryData;
    
}
The result is neatly populated into an array of javascript objects with the following structure
{"type":"meeting","date":"1343138400000","title":"Project A meeting","description":"no description available at this time","url":"no url","end":"1343142000000","location":"Huddle room 5"}
This data construct was then fed into a jquery widget to produce this interface


The result looks pretty good - thanks to Rick Taylor for helping me out with the lotus domino stuff.

Wednesday, May 2, 2012

Integrating Sametime into Portal

I recently worked with a client that wished to integrate Sametime instant messaging into WebSphere Portal. After evaluating the options available, I found that although IBM provides a Sametime portlet, it has one big drawback in that it takes so much space on the screen. User interfaces are already limited by screen size and resolution, it makes sense to use this space well.

Using a Tooltip Dialog
Most native instant messaging clients hide their user interfaces until they're needed - either to send a message or to handle an incoming message. The remainder of the time it just provides a status indicator on a tray at the bottom of the screen. This same concept can be applied to a web interface using a dojo tooltip dialog. Suppose that we've identified a location in the HTML where we want to show the Sametime status:
<div id="myClient2" onclick="ShowSTClientInFloatingPane()">Show tooltip dialog</div>
Now we can programmatically create a sametime.WebClient dojo widget using javascript:
var dsixe = {};
var tooltipDialog = null;

dojo.ready(function() {

  // Instantiate the sametime client widget
  dsixe.ST_Client = new sametime.WebClient({
      style : "width:200px;height:300px;border:1px solid black;"
  });

  dojo.require("dijit.TooltipDialog");
  
  tooltipDialog = new dijit.TooltipDialog({
    content : dsixe.ST_Client,
    onBlur : function() {
        dijit.popup.close(tooltipDialog);
    }
  });
});

and add a script to handle the onClick event that will display the Sametime buddy list:
function ShowSTClientInFloatingPane() {
   var node = dojo.byId("myClient2");
   var coords = dojo.coords("myClient2");
   var x = coords.x + 15;
   var y = coords.y + (coords.h / 2) + 5;

   dijit.popup.open({
       popup : tooltipDialog,
       x : x,
       y : y
   });

   dsixe.ST_Client.main.initLayout();
}
When we put this all together in a proper HTML page, we get something that looks like this:

Conclusion
Using this technique I was able to provide an instant messaging experience that is familiar to the end user while consuming very little screen space.