ClassCastException on RemotePortableObject.narrow

Been working on EJB with JBoss and Eclipse. I must say the XDoclet (with Ant) was a greate help in generating beans and doing packaging. Despite great tools, I met with a major error that had me stumped for 4 hours.

InitialContext ic = new InitialContext();
Object obj = ic.lookup("...");
SomeHome home = (SomeHome)PortablRemoteObject.narrow(obj, SomeHome.class);

A simple lookup like this, with a ClassCastException on the 3rd line. A class cast means the lookup was successful, someHomeObj is not null, but is not of type SomeHome (which happens to be an interface).

It usually means you’re casting to the wrong type, probably a typo or type confusion. But for my case I checked and rechecked and it was no error. No matter what I did couldn’t make the exception go away. This includes reflecting on the class, superclass and the interfaces of the object, to convince myself the types were correct.

// prints $Proxy157
sop(obj.getClass());

// prints java.lang.reflect.Proxy
sop(obj.getClass().getSuperClass());

// prints SomeHome, Handle
for (Class c : obj.getClass().getInterfaces())
    sop(c);

!!! The class actually implements SomeHome!!! But fails the narrow!!! *fumes* I even tested each line inside the narrow() implementation, and despite having implemented SomeHome, it cannot be cast into or assigned as SomeHome. (instanceof SomeHome == false, isAssignableFrom(SomeHome.class) == false, instanceof org.omg.CORBA.Object == false)

After hours of twiddling I finally found out it was because there were TWO of this interfaces being deployed, one in my ejb .jar, the other in my .war classes. The lookup returned the interface from the ejbjar, and was trying to cast it into the war interface. Therefore even though they had the same interface name (from the same package), they were 2 different classes.

To fix this i adjusted my package build, to EXCLUDE the interface classes from my war. A simple rebuild and the narrow works.

Sun Java goes Open Source!

After 2 years of pressure from the open-source community, Sun has finally decided to open-source Java. Sun was previously worried about compatibility and forking, since people could make their own versions or move towards other goals, making Java lose focus. The prime example was Linux. Some say Sun was afraid of losing control of Java. Whether they are really convinced now that open source is the way to go, or to pull up their stagnant stock prices…

In one of the issues in 2004, the president of the Open Source Initiative (OSI) dropped an open letter to then Sun CEO Scott McNealy touting that Sun is just using open-source as marketing but not really supporting it [1]. He compared Java and Sun to Tiger Woods and his dad, who supported his child by recognizing and letting him achieve his full potential from an early age. He says Sun is restricting Java’s potential, and it would not help even if Sun releases it later, as Woods would not have done it too if he started only later.

The saga went on with Sun spokesman replying to the media (but not to the sender) rebutting each of his points in exact quotes, and OSI president writing a second open letter in response…

Sun have announced that they’re doing it for sure, but its CEO is seeking advice on HOW it should be done.

[1] http://www.catb.org/~esr/writings/let-java-go.html
[2] http://news.zdnet.com/2100-9593_22-6072760.html
[3] http://www.vnunet.com/vnunet/news/21562 … ource-java
[4] http://www.iht.com/articles/2006/05/17/business/sun.php

VS2005 – First Chance Exceptions

When running CF apps in debug mode using VS2005, I could always see messages like:

A first chance exception of type "System.FileNotFoundException" occured in mscorlib.dll

Why are the core libraries throwing exceptions and how to avoid them? It turns out that first chance exceptions occur whenever exceptions are thrown (duh). If they are caught (with a try/catch clause) the application continues to run normally, but the debugger will print that line into the output. If the exception is uncaught, the debugger is notified again and the application breaks into debug mode. This is known as “second chance exception”. So far from what I see, it means you cannot avoid getting the first chance exceptions.

According to the links below, VS can be configured to react differently at the chance exceptions. Different actions may be taken for different exceptions or exception groups (exceptions hierarchy).

http://blogs.msdn.com/davidklinems/arch … 38061.aspx
http://www.codeproject.com/useritems/Un … ptions.asp

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/

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

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

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/