Java Puzzles

Nothing new for a week, but saw a set of puzzles which attempt to promote “good” programming and awareness of bugs that may crop up when bad programming practices are applied.

Some of the morals in the 8 puzzles include:

  • Avoid mixed-arithmetic computation
  • Use parenthesis to make clear your comparison intention
  • Use .equals() for object comparison instead of ==
  • Do not depend on interned string for program correctness
  • Do not assign to a single variable twice in a single statement
  • The postfix ++ operator increments the value, but returns the old value.
  • Document your intention when using & and |. Usually && and || should be used.
  • Never use exceptions for normal flow.
  • Avoid complicated initialization sequences, choose EITHER lazy or eager init, but never both.
  • int arithmetic overflows silently.
  • Math.abs(Integer.MIN_VALUE) == Integer.MIN_VALUE
  • If you can’t see a method, you cannot override it.
  • Don’t use background threads in initialization – leads to lock-free deadlock!

http://www.javalobby.org/eps/more-puzzlers/

OpenID

I tried OpenID last month if i remember correctly, after I saw it in LiveJournal. Basically I searched for a PHP OpenID server solution and “installed” it on my server, and set up an identity for myself. I tested the identity by using it on LiveJournal comments. LiveJournal is the main website that supports OpenID, though some other sites are beginning to offer OpenID as an alternative authentication mechanism.

OpenID asserts that you own a particular URL, meaning it authenticates your identity. It does not provide trust or authorisation. It is advertised as a true decentralized authentication system, as opposed to other central authentication system like Microsoft Passport. We’ll look at how it works, and followed by all the other benefits that OpenID says it achieves.

From the user point-of-view, he accesses a web site which requires his identity. An OpenID logo is available with a textbox for him to type his OpenID identity. He submits his identity URL and his identity server login is displayed. Once he logs in using his identity server’s id/password, he is returned to the original web site and he is authenticated with the identity.

Behind the scenes, once the original web site picks up the identity URL, it accesses that URL to pick up the identity server location inside the URL’s header. The site redirects the user to the identity server site, along with the URL that the identity server is supposed to return to after authentication. The identity server takes over, authenticates the user, and redirects the user back to the URL given by the original website, along with a “key”. The user submits this key to the orignal website, and the web site verifies this with the identity server, to check if the key is valid. The original web site is then satisfied that the identity URL provided belongs to the user.

The good things about this are:
(warning: example URLs are ficitious, they may not represent actual web sites)

1. Only HTML required for identity URL.
Any web page can be your identity URL, you need not have PHP or ASP running, just HTML. This is because you just need to insert a special tag in the HTML section, which points to your identity server. The identity server can be total different from your identity URL.

E.g. your identity is http://sned.blogserver.com/ where you can only put HTML pages, and you registered your OpenID with http://www.openid.net/

2. Single ID
The OpenID can be used on any site that supports OpenID, it does not require you to have an account with the site you are visiting. You do not have to sign up or remember multiple passwords. You just need one OpenID identity.

E.g. You leave comments at LiveJournal.com using you OpenID registered at http://www.openid.net/, without a livejournal account.

3. Decentralized autentication, Freedom to choose identity server
There is no central OpenID server that stores all your login information. All of it is in your identity server, which can be run by any company. Even if your identity server goes out of business, or turns evil and start charging $, you can switch to another OpenID server, but preserve your identity URL by just changing the tag in you to point to the new server.

E.g. You identity is http://sned.blogserver.com/ and you use http://openid.microsoft.com/ as your identity server. Later you change your server to http://www.openid.net, but still use http://sned.blogserver.com/ as your identity.

Yet with all these benefits, adoption is slow. Use of OpenID is now still only seen in blog comments. This is because while OpenID can establish you own that identity, the web site has to TRUST the identity server. I can easily set up my own identity server, which authenticates myself irregardless of the id/password I use. (tried and tested). However, once a trusted network of OpenIDs is set up and used by popular web sites, it may be possible to become a widespread identity system.

Microsoft Enterprise Library DAAB (Data Access Application Block)

For introduction sake, the Microsoft Enterprise Library is a set of open-source libraries that developers can freely use, extend, and modify to build better “enterprise” applications [1]. (weird isn’t it? Microsoft — Open Source, they probably realized that few MS developers really knew how to code properly) The library contains a suite of classes (known as application blocks) for the following areas:

  • Caching
  • Configuration
  • Data Access- Cryptography
  • Exception Handling
  • Logging and Instrumentation
  • Security

The DAAB is one of the blocks, and supposedly simplify database code by abstracting it from

SqlConnection myConnection = new SqlConnection("..");
myConnection.Open();
SqlCommand myCommand = new SqlCommand("..", myConnection);
SqlDataReader reader = myCommand.ExecuteReader();

to

Database db = DatabaseFactory.CreateDatabase();
IDataReader reader = db.ExecuteReader(CommandType.Text, "..");

Not much of a difference, the important thing is that the implementation is now more database independant, and configuration of using which database are stored in complex XML files (using the Configuration Application Block).

The old syntax was inherited all the way from DAO days, and I’m expecting they’ll be shifting this Object Oriented Enterprise way like DAAB into Vista next time. Performance-wise, this blog says DAAB vs DataAdapters give identical results [2]… anyone else ran different tests?

Java developers have absolutely no problem with this, because from Day one they were taught to use DriverManager.getConnection() and the Connection, Statement, ResultSet interface instead of ODBCResultSet or OracleResultSet.? 🙂

Connection conn = DriverManager.getConnection("...");
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("...");

[1] http://aspnet.4guysfromrolla.com/articles/030905-1.aspx
[2] http://www.alternex.net/philippe/PermaL … e75d1.aspx

AJAX – Asynchronous Javascript And XML

A discussion on using AJAX instead of traditional binding to build datagrids prompted me to write this. AJAX, still considered new technology, is being tried out by many developers, but sadly in more wrong ways than one.

Since AJAX involves Javascript and XML, it can be used in most web-based projects, including Java (servlets), PHP, .Net, etc. AJAX allows creating a XMLHttpRequest using Javascript and call server-side functions and returning XML responses. The response can be used to update the GUI using DHTML without refreshing the whole page.

So far the most common example I’ve seen is free-text auto-completion, such as sending a web-based email. The user types a few letters and a combo-box like list appears below, allowing the user to select a completed email address retrieved from the user address book in the server.

Other valid uses I’ve seen is using AJAX to update RSS tickers (starbean forum), and using AJAX to update dependant combo-boxes (selecting category updates list of products). Generally I feel that use of AJAX should be for a updating information on a page that otherwise required a “postback” type of update in Web 1.0. (btw if you’re not sure about Web2.0 or Web1.0 go google it up)

Talking about all these good points, here comes the bads, and WHY I personally think it’s bad:

1. Using AJAX to emulate server-side include (eg separate menu.html and use AJAX to load menu.html on every page)

AJAX is aimed at updating the UI after it has been displayed. To use AJAX to load another page during onLoad is making the client-side browser make another server request, during the server request. The code required (at the moment) is also much more complicated and bug-prone. If the server software (such as IIS/Tomcat/Apache) supports server side includes (SSI), PLUS most of the time the page already requires generation by the server, why not use it? Using SSI causes the page to be created completely on the server side and sent to the client directly.

2. ELIMINATE page refresh by loading all links using AJAX (eg. all links and form submits are AJAX calls that rewrites the current page)

For what? Don’t like the “Loading …” in the status bar? Maybe you shouldn’t be using web then. This requires the entire site’s logic to be embedded in one single page. You get the idea.

3. Databinding using AJAX

This point is arguable, it depends on the implementation. If the purpose is to update the table after it is displayed, it may still be justifiable. But if the binding is done during onLoad, it violates the same purpose as point 1. BTW I don’t think it should be directly binded. Instead AJAX can be used to download updates of the table periodically.

4. Server-side client-side validation

OK this came from thedailywtf, but this guy really doesn’t know what he was doing. He somehow felt the client side date validation was so difficult, that he wrote his Javascript validation function to make an AJAX call to the server, which implemented a Web Service that accepts a String and returns whether the input was a valid date. This could have been accomplished by using CLIENT-SIDE javascript, and various FREE ready scripts are available for download. For one good thing, AJAX works well with web services as they communicate in the same language – XML, but one bad thing is enough to kill many other goods.

If you think otherwise, drop me a comment.

SWT & JFace – Standard Widget Toolkit

SWT is an alternative to AWT and Swing, supported by the Eclipse community. Together with JFace it can be used to build RICH clients. SWT use native widgets, yet code is portable to other platforms. This is achieved by a JNI call-through to the OS library [1]. Widgets are simply Components and JComponents in AWT/Swing, which includes text boxes, push buttons, etc.

JFace provides a higher-level API for SWT widgets, such as an ApplicationWindow or Tables and Trees backed with a data model. JFace also allows direct access to the underneath SWT widgets, so that developers can easily change whats beneath. The whole API is very exposed, in fact, even the threading model and event loop is totally exposed. Whatever thread that created the display becomes the GUI thread, and other resource extensive tasks have to be thread-spawned by the programmer hiimself. The good thing is SWTException is thrown if UI manipulation was not done in the GUI thread.

For existing Swing developers, [2] provides an extremely simple introduction, with several tables to show the relationship between Swing components and SWT Widgets. Also see [3] for a nice list of widget screenshots.

[1] http://www.eclipse.org/articles/Article … ign-1.html
[2] http://www.javaworld.com/javaworld/jw-0 … jface.html
[3] http://www.eclipse.org/swt/widgets/

WinFX

Today’s topic is on WinFX, the “core” managed API in the to-be-released Windows Vista. WinFX consists of 3 frameworks [1]:

* Windows Presentation Foundation (WPF/Avalon) – GUI APIs
* Windows Communication Foundation (WCF/Indigo) – Messaging API for inter-process / inter-machine
* Windows Workflow Foundation (WF)

WPF is straightfoward that it encompasses all the Windows Forms and drawing API. WCF is more interesting because the new API uses an SOA to locate both local or remote processes in the same way and communicate using SOAP. From [2] inter-WCF communcations will be performed using an optimized binary SOAP format, while non WCF will be standard SOAP. Hopefully the non-WCF protocol will be well-documented so that other technologies can communicate with WCF processes easily. I can forsee projects starting to build non-Microsoft adapters to communicate in WCF SOAP formats.

[3] shows some seasoned Windows Developers arguing that WinFX will never take over Win32, since all managed calls have to end up calling some Win32 functions. However the author explains that although WinFX functions are expected to be just wrappers to Win32 DLLs, the situation may be reversed in the future. Core Win32 DLLs now do little but to call pentium instructions to perform their task. The situation may later be reversed such that Win32 dlls become wrappers to WinFX functions as Win32 reduce in favour of WinFX. The same situation has happened to Win32 and Win16, where Win32 now takes over Win16 as the core API for the OS.

From what happened between Win32 and Win16, I believe that the same will happen to WinFX and Win32, as Win32 gets phased out. In the end, does that mean that future Java bytecode will be interpreted into WinFX calls by the Java interpreter and then interpreted into CIL by WinFX and then interpreted by the CLR before becoming machine code? Hmm…

[1] http://en.wikipedia.org/wiki/WinFX
[2] http://en.wikipedia.org/wiki/Windows_Co … Foundation
[3] http://www.ondotnet.com/pub/a/dotnet/20 … orn_01.htm

RSS – Really Simple Syndication

Just to fill in the “missing” entry on 9 May, I’m gonna talk about RSS. Many sites offer RSS, but I’ve been slow to catch up on whats that. It simply stands for Really Simple Syndication, which is a way of staying updated with the new stuff on a web site.

The best use is on News and Blogs websites, where the headlines of the updated news are published on RSS. RSS clients then regularly check for updates and the user is informed of any new things on the site (either manually or automatically).

Basically, the server-side (news/blog website) publishes a RSS feed, which is a small XML file containing a list of the updated items. Each item contains a title, a URL link, date and a text description. RSS clients, known as aggregators, regularly poll the XML file to download any updates for the user. The updates may be in a link form where the user can click back to access the website. This greatly increases the traffic for the news site, and allows users to stay updated with site content.

Aggregators come in a few forms:
* standalone applications – which a user must keep running in the background;
* plug-ins – such as a Mozilla or email client plug-in that shows as an icon in the host program;
* websites – a web application that does aggregation
* scripts – PHP, ASP or other web-based scripts, dedicates a small space on the site to display the updated content.

Each type has its advantages – standalone apps usually support notification such as a sound or popup when news arrive; plug-ins reduce the number of running applications you have; websites allow you to see what news you’ve already seen irregardless of the machine you use; scripts allow you integrate RSS into any of your website.

I have tried RSS and installed one custom PHP/AJAX RSS script into the starbean forum. I modified the script to do a nicer fade in/out to swap the news from CNA.

Competing technologies to RSS include Atom and RDF, which are also XML formats for online syndication.

RCP – Rich Client Platform

Thats the new kid on the block… RCP is a framework that allows developers to quickly assemble rich client components like menus, toolbars, drag/drop functionality, etc into a client application. Currently the most popular RCP platforms are Eclipse and Netbeans.

Basically the IDEs allow developers to build application much like the same way in the old VB4/VB6 days. They still lose to VS.Net when it comes to ease of development. However, consider that a step forward for the Java community.

The idea sounds good as a big picture, but it’s going to be a big headache for those implementing it. These real developers are stepping into the same (dung) as Microsoft programmers. For one, performing tasks are not so straightforward. To get a button on the screen to display a tab becomes a wild-goose chase in the API for which is the correct function to call. More spaghetti code. Second, debugging becomes just like Microsoft: developers don’t know what’s going on behind the scenes and those chain of method calls. Only one in a thousand will have the curiousity (and TIME) to really figure out how things run behind. That leaves the other 999 using trial and error to fix bugs, ugly workarounds as long it works… pastamania code.

Rich clients are not to be confused with thin/thick clients. Before 2003 [1], rich clients meant a thick or fat client. But now a client may be thin AND rich at the same time — having the interactive features of a rich client, yet processing and business logic are handled in a remote server.

[1] http://en.wikipedia.org/wiki/Rich_client

JACOB – Call COM objects from Java

backdating this to when i spoke to KK. He was trying to call an obsolete COM component from Java, and was using JACOB [1]. I’ve not used it myself, but it sounds like a good way if you REALLY REALLY REALLY need to call COM. I hate it, cos once you have JNI with COM, you can’t really run it on non-Windows platform without a change.

If REALLY necessary, eg. interacting with a hardware device, I recommend building an adapter interface (pattern) for the component, so that another adapter implementation can be written when you port it to another OS, and a driver for that OS exists.

[1] http://danadler.com/jacob/