Archive for May, 2011

May 31st, 2011
6:42 pm
Iterating CDI Bean Types

Posted under CDI
Tags , , ,

When developing plugin architectures with IOC, it is useful to be able to iterate over the available beans of a given type which are known to the IO container.

In CDI, this is easy to do, but it is not obvious how from the Weld documentation unless you do a bit of digging and searching.

This post here gives a sample application which does it. The crucial code snippet which does the business is here:-

private @Named @Produces ArrayList<String> wilsons = new ArrayList<String>();
@Inject
void initWilsonRacquets(@Any Instance<WilsonType> racquets) {
    for (WilsonType racquet : racquets) {
        wilsons.add(racquet.getWilsonRacquetType());
    }
}

The intance keyword (used with @Any) exposes an iterator which lets you iterate the available beans. In the above sample they are added to a collection, but you could equally call methods on them as you iterate if you don’t need to keep them.

The Weld documentation describes this on page 25, with the following sample fragment:-

@Inject
void initServices(@Any Instance<Service> services) {
    for (Service service: services) {
        service.init();
    }
}

No Comments »

May 31st, 2011
4:35 pm
Partial Page Update Navigation, and View Expiry handling

Posted under JSF
Tags , , , ,

This is a set of loosely related posts which are of interest.

  • This post here on the Primefaces forum discusses partial Page update with view Expiry error handling using a generic Global Exception Handler. The idea can handle different scenarios generically, e.g. Ajax or not, and seems to have impressed Cagatay Civici so well worth a look!
  • This post on Stack Overflow discusses the desire for navigation during Partial Page Update. The simple conclusion is that basically you can’t, so don’t try it! This implies that if you code an application that uses PPU across a number of forms/conversations, then it all must be driven from a single URL.
  • Another important point which reinforces this is made on Primefaces FAQ #4, which states that forward navigation in Primefaces does not currently work with Ajax, although this may change at some point in the future.

No Comments »

May 31st, 2011
4:13 pm
Using CDI Conversation Scope

Posted under CDI
Tags , ,

This is an interesting  2 part article by Andy Gibson on how to use CDI conversations. Part 1 is here and Part 2 is here. Of particular interest is his discussion in part 2 about how to manage a collection of conversations and index them/return to them etc.

Another post here discusses the use of conversations and some custom reflection trickery to implement a generic CRUD application that only uses JSF view coding to implement a particular application.

No Comments »

May 31st, 2011
3:22 pm
Using Lists and Maps for JSF value binding

Posted under JSF
Tags ,

This article by Andreas Höhmann details how to do this. It uses the infamous map trick using a custom Map implementation to allow map based lookups, and also discusses list based index lookups.

This all needs to be weighed up with the ability of JSF2 to allow method expressions with parameters, but still a useful trick in some cases.

No Comments »

May 28th, 2011
11:19 am
Resign Patterns(!)

Posted under Design
Tags ,

This is a hugely funny take on design (anti) patterns – well worth a read, also available in Google Docs and as PDF download.

No Comments »

May 24th, 2011
8:05 am
Weld Debugging and performance issues

Posted under CDI
Tags ,

It seems to be that Weld:-

  • has error/log messages which are not as good as Spring
  • has a lot of magic going on compared with, say, Guice, and so more info is needed about what is going on under the hood.
  • Turning logging up to full is obviously a starter. I haven’t done this yet – need to look at weld log messages to see what to turn up. Note that Weld uses sls4J NOT java.util.logging, and the levels are therefore different – need to look at how they are mapped/how to turn it up.

You can find out more about Weld’s decision making when injecting beans by writing some code to listen to various weld events. You have to use Weld’s extension mechanism to do this but it is apparently very easy. Details of it in this post here on stackoverflow.

There are also some comments around about slow weld performance and memory usage, during startup. Performance is being improved and Weld 1.1 has these fixes in, but you need Glassfish 3.1 to use it which also opens up all the issues of Mojarra client state saving problems etc. which have prevented me moving to it.

There is some negative CDI/Weld comment about on the net, but as with any toolset there is no silver bullet. Any choice will have some downsides and our priorities should and will determine the best choice. Even with these issues, I cannot see a justification to move to Spring as whilst it is mature and very popular, it is a closed standard which is very XML heavy and does not do typesafe injection. Guice is closer in style to CDI, but both Guice and Spring are JSR330 implementations and so are not portable. Weld uses JSR299/CDI and is therefore an open portable (and the most recent) standard, and is built on input from both the Spring and Guice teams. If we can suffer some early adopter pain, I feel Weld will end up being the best choice.

By the time performance becomes a serious issue for this project, Weld will have moved on and these issues should have improved. Note also that there is already (at least) one alternative JSR299 implementation – Apache OpenWebBeans. This means that we can move to another CDI implementation if we have to, with minimum pain, in the same way that if Mojarra screws us we still have Apache Myfaces as a choice.

No Comments »

May 18th, 2011
3:12 pm
String.split–some simple regular expression (regex) examples

Posted under Java
Tags ,

String.split is now the preferred means of tokenising strings as java.util.StringTokeniser is now deprecated. String.split returns a string array containing the split strings. Using String.split requires some understanding of regular expressions, so I have included a couple of simple examples here.

String[] output = input.split(“[,\\s]+”);

This example takes string input and splits it on any white space (including newlines) or commas. Multiple white space and/or multiple comma characters are treated as a single delimiter. The regex string operates as follows:-

  • []+ matches any of the characters/constructs in the brackets, and matches 1-n times via the plus character. Multiples are treated as a single match.
  • , matches the comma character.
  • \\s matches any white space. The double backslash is needed as both Java and Regex use it as an escape character, so it is needed twice.

String[] output = input.split(“\\s*,\\s*”);

This example takes string input and splits it on commas only. Each comma may be preceeded or followed with zero or more white space characters (and newlines), which are also matched and therefore are stripped from the output. Multiple commas will result in empty strings in the output array, as there must always be exactly one comma as a delimiter. The regex string operates as follows:-

  • \\s* matches zero or many white space characters, and is placed both before and after the comma. This means that white space is swallowed up and not returned if present (as it is part of the delimiter), but it is not required to be present i.e. is not mandatory for the delimiter.
  • ,  matches a single comma character. This means that a delimiter must have one and only one comma. Multiple commas are treated as multiple delimiters.

 

Some points about string splitting in general:-

  • Any leading or trailing white space on the input string needs careful handling. In the first case above,  leading white space will cause an empty first output string to be part of the array. In the second example, leading white space will precede the first output string, and trailing white space will be left appended to the last output string. To avoid these problems, it is a good idea to trim the input string before splitting it, e.g.:-

String[] output = input.trim().split(“[,\\s]+”);
String[] output = input.trim().split(“\\s*,\\s*”);

  • Any characters which are matched as part of the delimiter are swallowed up and not returned in the output array. This gives an opportunity to clean up the string as I have done in the second example here, by making other characters (in this case white space) an optional part of the delimiter, so that they are removed if present.
  • You can compile the regular expression string into a pattern, which is efficient if the same pattern will be reused a number of times. You then perform the split via the pattern, so that our second example above would then be:-

Pattern pattern = Pattern.compile((“\\s*,\\s*”);
String[] output = pattern.split(input);

 

The Sun Java tutorial on regular expressions may be found here. There are many other sites with examples as well, as for example this google search shows.

No Comments »

May 10th, 2011
1:24 pm
Using Namespaces in Javascript to avoid naming collisions

Posted under Javascript
Tags , ,

Update 15/9/2011

Here is an example of my initial implementation, similar to the corejsf example above, but using a shorthand syntax to avoid the ifs. This only requires the 2 additional lines in front to declare the namespace. This can be done with global ‘register’ functions, but these in turn have namespacing issues and seem overly complex compared to the code below. Note also that this uses Javascript Object literal syntax to declare the functions (the ‘colon operator’ below, which is also used in JSON). This syntax in Javascript is a concise notation for name value pairs.

This implementation needs rolling out across all the other Javascript – this still needs doing.

var uk=uk||{}; uk.co=uk.co||{}; uk.co.salientsoft=uk.co.salientsoft||{};
uk.co.salientsoft.util= {
 clearElement: function(elementId) {
  var escapedId = ‘#’ + elementId.replace(/:/g, ‘\\3A ‘);
  jQuery(escapedId).val(”);
 }
};

Original Post

It is important to avoid collisions between Javascript function/variable names used by different objects – it is all too easy for entirely different pieces of code to be used in the same application and result in a name collision.

A good mechanism to avoid this for both functions and data is detailed in Core JavaServer Faces Edition 3, page 399. An excerpt from this page detailing how this is done is shown below.

 JavaScript Namespaces

In “The f:ajax Tag” on page 389, we implemented a JavaScript function—showProgress()—that uses Prototype to show and hide a DOM element. That method is fragile, however, because it can be overwritten by another JavaScript method of the same name.

It sounds plausible that someone might implement another JavaScript function named showProgress(), thereby replacing your version of the method with theirs. To prevent that replacement from happening, you could name your function something more unique, such as com.corejsf.showProgress(). With that strategy in mind for protecting our JavaScript method from being overwritten, we implement a simple map that serves as a namespace, and we define functions in that map**:

if (!com) var com = {}
if (!com.corejsf) {
    com.corejsf = {
        showProgress: function(data) {
            var inputId = data.source.id
            var progressbarId = inputId.substring(0, inputId.length – “name”.length) + “pole”;
            if (data.status == “begin”)
                Element.show(progressbarId);
            else if (data.status == “success”)
                Element.hide(progressbarId);
        }
    }
}

So now the caller accesses the function through the namespace, like this:

<f:ajax event=”blur” render=”nameError” onevent=”com.corejsf.showProgress”/>

JavaScript namespacing not only prevents others from overwriting your functions, but it also indicates to readers of your code that you are a JavaScript coder of some substance.

NOTE: Besides creating an ad-hoc namespace by putting JavaScript functions in a map, you can also put data in a map. Namespacing data is a consideration when you implement custom components that maintain data on the client. If you have multiple instances of the component, they will overwrite each other’s data. Putting the data in a map, keyed by the client identifier of the component to which the data is associated, is a way to ensure that multiple Ajax-based custom components of the same type that store data on the client, can co-exist in a single page.

** The map is actually an object literal—JavaScript does not have a map data structure—but semantically a JavaScript object literal is similar to a map.

No Comments »

May 9th, 2011
4:24 pm
Installing MantisBT for Issue Tracking

Posted under Hosting
Tags , ,

I was looking into a suitable tool for software issue/bug tracking. The following were my main goals:-

  1. I wanted access via the internet from anywhere as a prime requirement, so I needed a hosted application.
  2. I did not want to be forced to get custom hosting for it, and already use cpanel hosting extensively as it is readily available and cheap, so ideally I would need a PHP application which was easy to run and install on cpanel.
  3. I wanted Open source/community software if possible.
  4. I did not have much in the way of a feature shopping list, but ideally wanted a stable and feature rich package that could also be customised as required. My initial requirements would be fairly basic but I wanted a package that would accommodate growing needs in the future, such as multiuser features for a software development team, reporting etc.

 

Possible Contenders

  • Jira is very feature rich and is used by a number of major Java projects such as Java.net, Primefaces etc. However it needs Java hosting as it is a Java application, so for me that knocked it out of the frame.
  • Bugzilla was also a possible contender, being written in Perl it might run under cpanel, but having seen a post attempting this it looked a nightmare to install, and it was not clear that it would work under cpanel without elevated permissions which I did not have. I wanted a simple solution not another project!
  • Finally, I looked at MantisBT, and this appeared to tick all the boxes. It is highly feature rich, stable, and easy to install under cpanel. It lacks some nice to have features, such as text formatting for the issues – all the issue text and notes in Mantis are plain text, whereas with other packages, rich text is used so text formatting such as bold, underline etc. can be used. However, the one vital thing I needed was easy/automatic hyperlinking of URLs in the issue text, and fortunately Mantis does this very well and fully automatically. The hyperlinking is basic, just giving you the actual URL as the hyperlink description, but it works perfectly well. Also, whilst nice formatting is icing on the cake, it is important to remember that this is after all an issue/bug reporting tool for use by developers, so sexy formatting is not a primary concern. As I have used it further, I have been very impressed with the feature set. It allows full relationship definition between issues, supports multiple/hierachical projects, and supports both categories for issues and tagging in blog fashion. It also has full notification email support and this may be configured as desired. It is highly customisable, and has many more features than I would need initially.

 

MantisBT Installation and Configuration Notes

The documentation is very comprehensive and installation is straightforward. Basically it is a case of unzipping the kit on the server, creating a MySQL database and associated accounts via cpanel, and editing config_inc.php to put the database/login and other details in. Note the following points :-

  1. You need to pull the database settings out of config_inc.php, merge them with config_inc.php.sample, and create a new version of config_inc.php.
  2. I changed the file upload method from DATABASE to FILE. After doing so, I tested file upload and it was fine. You can leave the upload path blank in the config file. If you then set the upload folder for a project to ‘uploads/xxx/’ this will go to <mantis install directory>/uploads/xxx/, exactly as you would expect.
  3. As long as you set the folder permissions to 755 for the top level mantis folder you will be fine, the install and the file upload will both work. Prior to copying the sample config file, I got file path errors on a file upload (when it was set to the default of DATABASE), but after setting it to FILE it all worked fine.
  4. Note that email notifications work fine, but when testing, you DON’T get notified of your own changes by default (see config file), so you need to make changes using a second account to test email notify. Also, the default for a user is not to receive emails on a status change, so you need to change this as well.

 

Issue Tag Plugin

By default, Mantis supports tagging but does not make the feature very visible – you cannot see tags on the issue list screen by default. An excellent Tag plugin is available here. Having installed this, you can configure a column to display the tags and place it where you like (full instructions on the plugin web site). I placed the tags next to the categories. The plugin gives Mantis comprehensive tag support; you can see all the tags in the issue lists and the tags are clickable links. I highly recommend this plugin and having used it for a while I would not use Mantis without it.

No Comments »