Pages

Wednesday, June 30, 2010

DOM

The DOM is a programmable representation of a document or web page. While we see each page as a visual construct, the browser recognises it as a tree structure of elements and properties. In the DOM, every part of the document is a note, which is text, and element, an attribute, etc. The DOM provides methods to reach all these notes and to add, remove, and modify them.

DOM scripting therefore refers to programatically accessing the DOM. In common usage, DOM scripting implies JavaScript.

The advantages/features of the DOM model include:
  • progressive enhancement (ie: enhancing the page increasingly with the support of the client, as opposed to graceful degradation)
  • separation of presentation and behaviour
  • maintainability
  • separation of structure and behaviour
  • event handling

Advantages and Disadvantages of Javascript

Created by Netscape in 1996, JavaScript has little to do with Java (confusing as the naming is) except for the fact that some of the syntax looks similar. Javascript is a browser-based programming language that runs client-side.

Advantages:
  • Enables data validation on the client side resulting in a smoother user experience and less load on the server
  • It is supported by most browsers due to its popularity. No extra downloads are required to view JavaScript
  • It does not require any special compilers or editors
  • JavaScript excels in the creation of dynamic effects (eg: rollover images)
  • JavaScript load time is faster than some other front-end technologies (eg: Flash, Java Applets)
Disadvantages:
  • Not all browsers support JavaScript consistently and to the same version.
  • If JavaScript is not stored separately it makes it difficult for search engine crawlers to find keywords and content in web pages.

Advantages of JSP

 JSP is a Java-based technology for creating dynamic web pages.

The following are some of the disadvantages of client-side scripting compared to JSP:
  • The user's browser must have scripting enabled, which is not always the case
  • The client-side code can only  be guaranteed to work for all the brower types it has been tested against. It can be a pain to code for multiple browsers
  • Client-side scripts have limited access to server-side resources (eg: databases)
  • Client-side scripting languages are less versatile than Java.
Some of the advantages of JSP over client-side scripting are as follows:
  • JSP enables clean separation of business logic from presentation
  • JSP is not limited to a specific platform, being Java-based and compiled into bytecode.
  • As JSP pages execute on the server it does not matter what browser or configuration the client has.
  • JSP has full access to server-side resources.
For all intents and purposes JSP is a sohpisticated Java Servlet. The main advantage of JSP over Java Servlets is the ease of coding - static text is achieved using HTML tags as opposed to a multitude of println statements.

Tuesday, June 29, 2010

Simple EJB3 Example

This post provides instructions on creating a simple Stateless Session Bean and a test client to see it working. It assumes Eclipase IDE and JBoss.

Create a new EJB project in Eclipse, called EJB3SessionBeanExample. Accept all project defaults.

Create 2 packages under the ejbModule directory: "bean" and "client"

Create the following classes under the bean folder:

IHelloBean

package bean;

import java.io.Serializable;

public interface IHelloBean extends Serializable {
  public void doSomething();
}

HelloBeanRemote

package bean;
import javax.ejb.Remote;

@Remote
public interface HelloBeanRemote extends IHelloBean {

}

HelloBeanLocal

package bean;
import javax.ejb.Local;

@Local
public interface HelloBeanLocal extends IHelloBean {

}

HelloBean

package bean;

import javax.ejb.Stateless;

/**
* Session Bean implementation class
*/
@Stateless
public class HelloBean implements HelloBeanRemote, HelloBeanLocal {

  private static final long serialVersionUID = 9184424076718418234L;
  public void doSomething() {
    System.out.println("Hello World!");
  }
}

Create the HelloBeanClient under the client folder:

package client;

import java.util.Properties;
import javax.naming.InitialContext;
import javax.naming.NamingException;

public class HelloBeanClient {
  public static void main(String[] args) {
    try {
      Properties props = new Properties();
      props.setProperty("java.naming.factory.initial",
          "org.jnp.interfaces.NamingContextFactory");
      props.setProperty("java.naming.factory.url.pkgs",           "org.jboss.naming");
      props.setProperty("java.naming.provider.url",
"127.0.0.1:1099");

      InitialContext ctx = new InitialContext(props);
      MyBeanRemote bean = (MyBeanRemote) ctx.lookup("MyBean/remote");

      bean.doSomething();
    } catch (NamingException e) {
      e.printStackTrace();
    }
  }
}

Right click on the EJB3SessionBeanExample project and select Run As -> Run on Server to publish to the server.

Once it is successfully deployed, right click on the HelloBeanClient class and select Run As -> Java Application. Accept any defaults and run it. You should see Hello World! printed to the console (or log C:\Apps\JBoss\jboss-5.1.0.GA\server\default\log depending on setup).

Simple JSP Example

The following post provides an example of a simple JSP page and instructions on how to deploy and view it. It assumes the use of Eclipse and JBoss.

Create a new Dynamic Web Project in Eclipse called HelloWorld.You can accept the defaults, such as "WebContent" for the web root.

Create the file HelloWorld.jsp under the WebContent directory and paste the following code in:

<%@ page language="java" %>
<html>
<body>
<%
  for (int counter = 1; counter <= 10; counter++) {
%>
    Hello World!<br>
<%
  }
%>
</body>
</html>

Create a file called web.xml under the WEB-INF directory (which should have been automatically created under the WebContent directory) and paste in the following:

<?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE web-app
    PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.2//EN"
    "http://java.sun.com/j2ee/dtds/web-app_2_2.dtd">
<web-app>
</web-app>


Right-click the HelloWorld project folder and select Run As -&gt; Run on Server. Accept any defaults and run it on your local server. This should put a war file in C:\Apps\JBoss\jboss-5.1.0.GA\server\default\deploy (or equivalent).

Now go to http://localhost:8080/HelloWorld/HelloWorld.jsp and you should see:

Hello World!
Hello World!
Hello World!
Hello World!
Hello World!
Hello World!
Hello World!
Hello World!
Hello World!
Hello World!

Simple.

Thursday, June 24, 2010

Retarded IE javascript error messages

Error: Expected ';'
Code: 0

Could well mean that you have capitalised the first letter of a variable declaration (Var instead of var) in error, as javascript is case-sensitive, and IE is retarded.

Tuesday, June 22, 2010

Perhaps JAVA_HOME does not point to the JDK...

Buildfile: C:\dev\EJB3Tutorial\EJB3JSPExample\ejbModule\build.xml
init:
build:
[javac] Compiling 2 source files to C:\dev\EJB3Tutorial\EJB3JSPExample\ejbModule\build\classes

BUILD FAILED
C:\dev\EJB3Tutorial\EJB3JSPExample\ejbModule\build.xml:41: Unable to find a javac compiler;
com.sun.tools.javac.Main is not on the classpath.
Perhaps JAVA_HOME does not point to the JDK.
It is currently set to "C:\Program Files\Java\jre6"

Total time: 219 milliseconds

A solution to this in Eclipse is to edit Ant's runtime properties (Window > Preferences > Ant > Runtime). Select the Global Properties node in the Classpath tab and click Add External Jars. Select tools.jar from your JDK directory (e.g., C:\Program Files\Java\jdk1.6.0_20\lib\tools.jar).

EJB Web Service Frustrations

It always amazes me how much time can be wasted trying to get some simple framework/middleware up and running. There is no actual coding involved, only googling error messages, substituting various pieces, plugging, patching, copying and pasting, etc, etc. And sadly today I am no where near as close to getting EJB3 web services working as I would like.

I wanted to get this working as there are a number of advantages to using EJBs as web services instead of POJOs:
  • A richer set of protocols are available
  • Gain access to framework like declarative security and transactions

So I began by googling to find a simple example that I could copy and paste into a few beans/classes and see some results without too much hassle. This was not a problem and I'd created a Remote Interface @WebService using @SOAPBinding(style=Style.RPC), declaring a couple of @WebMethod s, a stateless session bean implementing those methods, and a Client to test it within 10 minutes.

And then the fun began. It deployed with no problems but when I ran the client it crashed with some error about not being able to find some Xerces class. I googled that message and soon figured out that for some reason JBoss was not looking at the .../lib/endorsed/ folder where xercesImpl.jar was. Neither could I figure out how to make it look there so I just added the xercesImpl.jar as an external library. And that fixed that.

Running the client once more resulted in:

Exception in thread "main" java.lang.reflect.UndeclaredThrowableException at $Proxy0.add(Unknown Source) at org.jboss.tutorial.webservice.client.Client.main(Client.java:45)Caused by: java.rmi.RemoteException: Call invocation failed; nested exception is: java.lang.UnsupportedOperationException: setProperty must be overridden by all subclasses of SOAPMessage at org.jboss.ws.core.jaxrpc.client.CallImpl.invokeInternal(CallImpl.java:535) at org.jboss.ws.core.jaxrpc.client.CallImpl.invoke(CallImpl.java:275) at org.jboss.ws.core.jaxrpc.client.PortProxy.invoke(PortProxy.java:154) ... 2 moreCaused by: java.lang.UnsupportedOperationException: setProperty must be overridden by all subclasses of SOAPMessage at javax.xml.soap.SOAPMessage.setProperty(Unknown Source) at org.jboss.ws.core.soap.SOAPMessageImpl.(SOAPMessageImpl.java:87) at org.jboss.ws.core.soap.MessageFactoryImpl.createMessage(MessageFactoryImpl.java:169) at org.jboss.ws.core.CommonSOAP11Binding.createMessage(CommonSOAP11Binding.java:57) at org.jboss.ws.core.CommonSOAPBinding.bindRequestMessage(CommonSOAPBinding.java:157) at org.jboss.ws.core.CommonClient.invoke(CommonClient.java:290) at org.jboss.ws.core.jaxrpc.client.CallImpl.invokeInternal(CallImpl.java:516) ... 4 more

This after much googling I concluded to be a SOAPMessage implementation bug, where the setProperty() method has been overridden in the abstract SOAPMessage class instead of the SOAPMessageImpl subclass where it should have been. The SOAPMessageImpl class is being loaded from rt.jar (Java 1.6) in the classpath instead of the JBoss one, and it calls the setProperty() method of the parent, which throws the UnsupportedOperationException. Hmmm... I'm not even sure if that makes sense as I have not looked into the source of the implementations but taken the explaination from another site. Note to self, check this.

I then proceeded to attempt to make JBoss look at the right jars by placing jbossws-native-core.jar and various other jbossws jars in the /lib/endorsed directory, adding them as external jars directly, and even taking some users' suggestions and using Java 5 instead of 6. Sadly none of this worked for me and I by the time I have given up for the day and set about documenting my experiences I have worked almost an 8 hour day (with liberal breaks for morning tea, lunch, a run, and a shower). I am no Eclipse guru and just switching to Java 5 took enough time by the time I figured out that I should really set the version of Java via the Project Properties -> Project Facets panel to make it take effect on the "java facet" version as well as the compiler compliance level. If it isn't set here the following error results:

"Java compiler level does not match the version of the installed Java project facet"

So a whole day has gone by and I have not managed to get a simple EJB3 web service example working. This is one thing that continues to frustrate me about software development - the amount of wasted time spent googling errors and trying random fixes in order to get something so simple working. Hopefully my next post will be an update on how I finally got a simple EJB3 web service working!

Software Design Patterns - Overview and Rant

General reusable solutions to commonly occurring problems in software design, made popular by the 1994 book by the "Gang of four". Lately I am leaning towards dismissing them as buzz-words that wanna-be l33t hax0rs use to impress/confuse and a favourite question of interviewers. More and more patterns that I come across in reading seem to be post-hoc descriptions of designs that I or other developers have used frequently without attributing a spiffy name to. For example, the Strategy pattern - a design pattern whereby algorithms can be selected at runtime, implemented using concrete strategy classes implementing a strategy interface. How is that different from polymorphism? If anything it is a subset of polymorphism and adds nothing new. And the Iterator pattern??

I admit I do find some pattern identification useful. For example, the Facade - exactly what it sounds like, defines a higher-level interface that makes a subsystem easier to use.

Although the Singleton is still often identified as a pattern, there is growing belief that it should really be classed as an anti-pattern. Some of the drawbacks identified include the following:
  • The limitations it introduces may be unnecessary, ie: a sole instance may not actually be required in a given situation. Additionally these limitations may cause threading issues.
  • Singletons introduce global state into applications resulting in dependencies in the design being hidden inside the code, rather than obvious dependencies highlighted by method parameters for example.
  • For purists, Singletons mix two different responsibilities in the same class, one of them being the control over the number of instances of itself. This may be better handled using a Factory to encapsulate creation and limit instances.
In short, although I think the study of design patterns (and anti-patterns) is great for building up a budding developer's abilities, I am somewhat sceptical about 1) the introduction of new terminology to describe existing simple solutions to a problem, that really don't require another name, and 2) the proliferation of patterns in areas where something simpler and more customised would be a lot easier to understand and maintain.
 
Powered by Blogger