Category Archives: JavaScript

CORS Filter with improved performance

CORS FilterThe new 2.5 release of the CORS Filter for handling cross-domain requests offers improved performance. This benefits Java web servers that handle lots of traffic, particularly situations when a significant proportion of that is invalid or unauthorised CORS requests.

The improvement is achieved by using static (cached) exceptions within the filter. Here is an an informative discussion with metrics about Java exception handling and how it can be sped up.

The 2.5 release also fixes a NPE bug affecting Origin validation during configuration.

Released JsWorld 2.8.1 for currency, numeric and date/time formatting in JavaScript


The JsWorld library for JavaScript formatting and parsing of date/times, numeric and currency amounts received a fresh update for 2014. Written entirely in JavaScript, JsWorld takes a novel approach by enabling data localisation to be performed inside the browser, offloading the web server and offering unmatched flexibility for real-time applications.

What’s in the new 2.8.1 release of JsWorld?

  • The locale definitions were updated with the latests languages, countries and currency data obtained from Unicode. JsWorld has now support for 475 locales, including many new language / country combinations. As always, the locale definitions are available in three different formats – as JavaScript include files, as JSON files for dynamic loading as well as Mozilla property files if you intend to integrate JsWorld in a Firefox add-on.
  • The unique numeric / currency / date/time formatting engine was fine tuned for even greater performance. The JavaScript code has been stable for two years now and there have been no reported bugs since then.

Check out our live JavaScript number / currency / date formatting demo or proceed to the quick start guide. Comments and feedback are welcome as always.


CORS Filter 1.7 with more configuration options

CORS FilterThe Java servet filter for enabling CORS (cross-domain) web applications received a major upgrade today.

Up until now in order to change the out-of-the-box CORS configuration you had to add filter init-params in the web.xml descriptor of your application. A number of developers asked for alternative configuration means, such as specifying a properties file for the configuration. This is now supported.

The CORS Filter will now apply the following precedence when resolving the configuration:

  1. Checks for an environment variable “cors.configurationFile” pointing to a properties file with the CORS configuration.
  2. Checks for a servlet filter init-param “cors.configurationFile” pointing to a properties file with the CORS configuration.
  3. Checks for CORS params in filter init section, applies the default values if not found.

Another important configuration change is the ability to specify a general “allow-any-request-header” policy by setting the cors.supportedHeaders to an asterisk.

Handling of same-domain requests that carry a redundant Origin header (set by some Javascript frameworks) is fixed too.

Thanks to David Bellem, Stijn Cremers and Casey Lucas for initiating this new release of the CORS Filter. Also thanks to Anne van Kesteren for answering my CORS-related query on the W3C list.

JsWorld 2.7 with improved date/time parsing

JsWorld iconWith version 2.7 JsWorld received a small upgrade and a few small fixes to date, time and date/time parsing in JavaScript.

Case-insensitive parsing of dates

Weekday and months names, both in their full and abbreviated versions, are now parsed irrespective of case. This is done while taking care of world locales that don’t have the notion of case (quite many actually).

So, for example, if you have the en_GB locale and your date format pattern is set to

POSIX_LC.en_GB.d_fmt = "%d/%b/%Y"

then the following input will parse to the same date:

17/Apr/2010 -> 2010-04-17
17/apr/2012 -> 2012-04-17
17/APR/2012 -> 2012-04-17

Do write us when you wish to have such features added to JsWorld. This particular one was requested by a customer who wanted to have more flexible parsing of dates. I’m considering making the date/time parser even more flexible, while staying completely on the safe side.

Fixed bugs in %e, %k, %l parsing

JsWorld 2.7 also fixes a few bugs that may cause incorrect parsing of date/time values against format templates that use the %e (day of the month as a decimal number, space padded), %k (hour in 24-h clock as a decimal number) and the %l (hour in 12-h clock as a decimal number) patterns.

If you’re subscribed you should receive an email how to get this update shortly.

Browser-side JS numeric, currency and date/time formatting

JsWorld iconIt’s now four years since JsWorld‘s inception and today the JavaScript l10n library is used in a range of web applications, from international online retail to finance and enterprise SaaS.

What are the advantages of applying numeric, currency and date/time formatting on the browser-side?

1. Clean separation of data and presentation.

In the spirit of modern Ajax + Web 2.0 apps the web server can supply the raw numeric, currency or date/time values in raw JSON or HTML which the browser-side JavaScript then formats accoring to the current locale. You can then have your business logic focus on the raw data and services, while the front-end is taking care of the presentation.

Example of currency data supplied as JSON:

{ "amount":"1500000.99", "currency":"GBP", "locale":"en_GB" }

Which then JsWorld takes to format accordingly as British Pounds :


The data may alternatively be supplied as unformatted HTML elements which are then walked by a piece of JavaScript applying localised formatting according to their class (or some other attribute, e.g. “data-” in HTML5).

<span class="date">2012-01-09</span>

Which then if the current locale is set to Portuguese/Brazil (pt_BR) is converted to

9 de janeiro de 2012

JsWorld comes with a simple API which gives you plenty of flexibility in how the data is fed to the browser. It could arrive through JSON/XHR or XML or it could be static HTML.

2. Agile development

Now that you have clean separation between business data + logic and presentation layer your engineers can proceed with greater speed in developing and maintaining your applications. The back-end developers can concentrate on the data and the service process, your front-end developers on the user experience – without having to worry about intricacies of data l10n – this is JsWorld’s task.

3. Conserve server resources

The localisation of data, if done repeatedly or on large data sets, can consume quite a bit of CPU resources. If you do that in your PHP/Java servlet/Ruby/etc code on the server-side this will cost your own resources. So why not shift this load to the browser-side? The effects could be small or more significant, depending on your web app and the amount of traffic you serve.

JsWorld is now in its 2.5 release and supports over 300 languages, 200 countries and 100 currencies.

JsWorld 2.5 with updated locale definitions

JsWorld iconJust before going into the Christmas holidays we got out a new release of JsWorld, the most comprehensive JavaScript library for localised formatting and parsing of numbers, currency and date/times.

What is in the new release?

The locale definitions were updated to match the latest CLDR data from Unicode. JsWorld now supports 354 world locales, with some of them reflecting important recent changes, such as the new Indian Rupee sign which became official in 2011.

JsWorld 2.5 also fixes a bug which resulted in incorrect formatting of midnight time using AM/PM notation. Thanks to our customer who reported this problem.

The next locale updates are expected in the first half of 2012.

Merry Christmas to all of you 🙂

JsWorld 2.4.1 with automatic currency rounding

JsWorld iconToday saw the release of JsWorld 2.4.1, which remains the most comprehensive JavaScript library for localised formatting and parsing of numeric, monetary and date/time values in web applications. This is a minor update which introduces automatic rounding of formatted currency amounts.

Up to now the default behaviour was to leave the fraction part of the original input amount unchanged.

var lc = new jsworld.Locale(POSIX_LC.en_US);
var mf = new jsworld.MonetaryFormatter(lc);



To enforce rounding and display to a certain precision the optional ".n" argument can be used, where n is the number of desired fraction digits.

alert(mf.format(1500.005, ".2"));



Yesterday I received an email from a customer in the US from which it became apparent that the default non-rounding behaviour was not intuitive to developers. After some consideration I decided to patch the library code to round per default, based on the number of fraction digits for the selected currency. The optional “.n” facility remains the same.

So the above


will now instead result in


The patched version is now available as JsWorld 2.4.1.

JSON-RPC for Android apps

JSON-RPC 2.0 Thanks to user feedback I recently discovered that the JSON-RPC 2.0 Base and related libraries and JSON-RPC shell are finding increasing use in Android applications, mostly to hook to remote JSON-RPC services.

While I’m not really into mobile gadgets and don’t own a smart phone, I do sense there is usefulness in mobile apps to people. I’m now considering a mobile version of the Json2Ldap demo. The upcoming Transaction Company software will also certainly a boast a few mobile apps, to allow users to check their balance and pay co-workers while on the go. Application Craft‘s offering may be just the right mean to do that, as it provides both a development and hosting environment in one.

CORS requests and cookies

CORS FilterToday I received a question regarding the Java CORS Filter and browser cookies:

Does your filter take care about the sessions? For each CORS request I get a different JSESSIONID.

My response was that in order for the Java web application or service to get at a cookie, both the CORS Filter in front of it as well as the requesting JavaScript must explicitly allow this form of credential:

First, the JavaScript initiating the XHR call must set its “withCredentials” flag to true. Otherwise the browser will not allow any cookies to be passed during the cross-domain call.

var xhr = new XMLHttpRequest();
var url = 'http://bar.other/resources/credentialed-content/';'GET', url, true);
xhr.withCredentials = true;
xhr.onreadystatechange = handler;

Second, the CORS Filter must also expressly state to the browser that cookies are permitted. This is advertised during the so called “pre-flight” request that the browser makes before an actual request that may involve credentials, such as cookies. The CORS Filter ships with a default configuration where credentials, such as cookies, are flagged as allowed when responding to preflight requests. To restrict this edit the cors.supportsCredentials configuration parameter.

The Java CORS filter itself doesn’t access the cookie headers in any way, nor does it interface to the JSESSIONID.

So, to sum up, both the calling script on the browser side as well as the CORS Filter on the server side must expressly have the credentials flag enabled for cookies to pass through.

There is a snag however and it has to do with Internet Explorer. Its XDomainRequest implementation of CORS doesn’t allow cookies to be passed at all, for security reasons says Microsoft. Which is probably a good thing. So if you wish to achieve wider browser support for your cross-domain application or service you will have to use an alternative mean to cookies for storing session IDs, such as passing the token as an URL parameter.

Using data URIs with Json2Ldap

Json2Ldap iconPerson entries in a LDAP directory may contain photos. These are typically stored in a jpegPhoto attribute, defined in the standard inetOrgPerson schema. In this article I’ll show you how to display such JPEG images in the browser using Json2Ldap and a cool new HTML feature called data URIs.

Json2Ldap is a neat LDAP gateway software for web applications. It’s web API presents a set of JSON calls that JavaScript code running in a browser can address to access remote directory servers to perform tasks such as authenticating users, browsing their directory records, reading and updating attributes.

When Json2Ldap returns a directory entry it inspects the value of each attribute. If it is text, it passes it unmodified (save for escaping the special JSON chars). If the content is binary data, it encodes it into a Base64 string.

{ "DN" : "uid=alice,ou=people,dc=wonderland,dc=com",
  "cn"        : [ "Alice Wonderland" ],
  "mail"      : [ "" ],
  "mobile"    : [ "+1 382 077 4180" ],
  "jpegPhoto" : [ "yugEMFjdQyRoxCP2KaZ041BUSctnUgY5TS7PBg==" ]

Your client JavaScript application will have no problems displaying the text attributes inside a web page. But how to render the JPEG image which was received as a Base64 string? What to do with it?

In the pre HTML 5 days you would have had to produce a physical JPEG URL from the received Base64 string, for example as by uploading it to a web server and then linking to it.

Fortunately, work-arounds such as this are no longer necessary. The solution is called Data URIs, a feature which was originally specified in 1998 and is now finally implemented by the latest crop of HTML 5 browsers.

How do data URIs work?

They provide an option for image data to be “in-lined” within the HTML page, instead only being able to link to it.

Here is a standard img element where the src attribute is a typical URL pointing to a file on the web server:

<img src=""/>

And here is an img with a data URI, where the image content is pasted directly into the src attribute. So when a data URI aware browser reads it, it will fetch the JPEG data from the in-lined Base64 string:

<img src="data:image/jpeg;base64,yugEMFjdQyRoxCP2KaZ041BUSctnUgY5TS7PBg=="/>

I don’t know why it took over 10 years to implement support for data URIs in browsers, but this is now a powerful technique for Ajax apps to render images on the web page which content was received through a XHR call.

Data URIs can naturally be applied to Ajax apps that interface to an LDAP directory through Json2Ldap. Rendering jpegPhoto attributes is then as simple as setting the src attribute of the desired image element to a data URI and then appending the Base64 content to it:

// We're using jQuery and the user directory entry 
// resides in the 'user' variable
$("#user-photo").attr("src", "data:image/jpeg;base64," + user.jpegPhoto[0]);

The online Json2Ldap demo makes use of inline images too. You can check it out at

The online Json2Ldap featuring data URIs for JPEG image rendering

Things to bear in mind:

While data URIs are supported by all major browsers today, some may impose a limit on the content size. IE 8 for example has a limit of 32 KB. So this technique may not work well for large images. For avatars and photos in user profiles, where 10 to 20KB are sufficient, it is going to be just fine.