Archive for the ‘Java’ Category

blog moved to blog.aujava.com

April 24, 2007

Recently I have moved the blog to better place 🙂  Please update your bookmarks.  blog.aujava.com

Generic OGNL Controller without Spring WebFlow

January 22, 2007

While working on various web projects many times I felt guilty for writing controllers that perform one-two rows of the code.
It must be easier way! And when I read and tried Spring WebFlow I really liked their approach for defining how to call methods on any exposed bean.
It is what I was looking for. Simple things made easy inside the xml config:

 <bean-action bean="cartController" method="changeQuantities">

 	<method-arguments><argument expression="flowScope.viewCommand"/></method-arguments>

 	<method-result name="viewCommand" scope="flow"/>

 </bean-action>

However Spring WebFlow has many aspects that would stop you from using it for entire site. Click-around navigation and SWF do not play well together.
So what I need is ability to define OGNL expression in Spring coonfig without using SWF. What looked scarry on first sight turned to be extremely easy task.
I did some prototyping of idea and here is what I got in spring config file:

 <bean id="profileView" class="com.cochlear.mcc.web.GenericFormController">

 	<property name="formView" value="profileView"/>

 	<property name="manager"><ref bean="profileManager"/></property>

 	<property name="viewScript"><value>manager.getProfile()</value></property>

 </bean>

 <bean id="profileForm" class="com.cochlear.mcc.web.GenericFormController">

 	<property name="formView" value="profileForm"/>

 	<property name="manager"><ref bean="profileManager"/></property>

 	<property name="modelClass"><value>com.cochlear.mcc.profile.model.ProfileDTO</value></property>

 	<property name="viewScript"><value>manager.getProfile()</value></property>

 	<property name="postScript"><value>manager.updateProfile(#object)</value></property>

 	<property name="successView" value="redirect:profile.view"/>

 </bean>

Not as clear as in SWF maybe but enough to prove the idea. It is concise, it does the job. You do not have to write FormActions for trivial things.
Here is what I have in GenericFormController:

public class GenericFormController extends SimpleFormController{

 protected Object manager;

 protected String viewScript;

 protected String postScript;

protected Object formBackingObject(HttpServletRequest request) throws ServletException, InstantiationException, IllegalAccessException {

 	try {

     	if(StringUtils.hasText(viewScript)){

 			OgnlContext context= new OgnlContext();

 			populateOgnlContextCommon(context, request);

 			Object expr = Ognl.parseExpression(viewScript);

 			Object res=Ognl.getValue(expr, context, this);

 			return res;

     	}else{

     		return getCommandClass().newInstance();

     	}

 	} catch (OgnlException e) {

 		e.printStackTrace();

 		throw new ServletException(e);

 	}

    }

protected ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response,

                                    Object commandObject, BindException errors) throws Exception {

Object command = getCommandClass().cast(commandObject);

 	try {

     	if(StringUtils.hasText(postScript)){

 			OgnlContext context= new OgnlContext();

 			context.put("command", command);

 			populateOgnlContextCommon(context, request);

 			Object expr = Ognl.parseExpression(postScript);

 			Ognl.getValue(expr, context, this);

     	}else{

     		throw new ServletException("No postScript specified");

     	}

 	} catch (Exception e) {

 		errors.reject(null, "Error:"+e.getMessage());

 		return showForm(request, errors, getFormView());

 	}

return new ModelAndView(getSuccessView());

    }

protected void populateOgnlContextCommon(OgnlContext context, HttpServletRequest request){

 	  context.put("request", request);

 	  context.put("session", request.getSession());

 	  context.put("user", SecurityContextHolder.getContext().getAuthentication().getPrincipal());

    }

// Getters and Setters here ..

 // ...

}

When I have time I will do something more production grade. For now I just glad to know that it is achievable and quite simple actualy.

DiggIt | del.icio.us

POSTable HTML links

January 17, 2007

When building web sites you often have to produce POST request on user’s actions. Many times without having user – editable form fields. Server just expects you to send POST. The standard solution is to make hidden form, hardcode some fields value and dynamically populate other values when user presses submit button. It does the job. But the code is spoiled with these pseudo forms and, I believe, you never gonna like it.

There is other approach that is much more concise and programmer friendly (tm:) . The trick is to construct and submit form on-the-fly. Let’s start with JavaScript function that exploits Prototype:
(more…)

Discovering Spring MVC

August 28, 2006

Spring MVC is not taken seriously jet because of almost absent documentation. For 2.0 version they wrote couple more paragraphs. But still only pages 214-250 devoted to Spring MVC itself. Many features left undocumented.

For my recent project I had to build a form having 6 different sets of fields. Depending on selected value in combo-box I process specific set. The rest of fields are ignored. That was easy to decide but how to tell Spring no to bind some fields?

One approach is to process input manually disabling automatic binding by overriding supressBinding function:

protected boolean suppressBinding(HttpServletRequest request) {
  return false;
}

Will work but leaves whole burden of binding on your shoulders. You do not want that. The other approach is letting Spring know which fields you want to process and which not. Take a look:
(more…)

Improvement of JSON to JAVA marshalling with JSON-RPC

August 16, 2006

During debugging one of my porjects I’ve spoted the following code in BeanSerializer.java from JSON-RPC library:


public Object unmarshall(SerializerState state, Class clazz, Object o)
...
Method setMethod = (Method)bd.writableProps.get(field);
if(setMethod != null) {
    ...
    setMethod.invoke(instance, invokeArgs);
    ...
}

The class is responsible of transforming Json notation to your Java Bean. Looking at code I realised that when no setter is present for field(or you mistyped field name in JSON) nothing happens. Nothing is set on the Bean obviously and no exception is thrown! Is some situation it makes sence. Silently dropping of absent fields is nice feature when you write backward compatible code or similar. But in most cases you want to rise an exception when field name does not match to Java bean fields. So I suggest to modify this code like following:
(more…)

Java technologies popularity in Sydney

August 13, 2006

AuJava logo

Here is just some numbers from jobserve.com.au. All keywords were prefixed with Sydney AND Java AND statement. The search for Sydney AND Java only gives 500 matching jobs.
AppServer:

  1. WebSphere – 56
  2. WebLogic – 47
  3. Tomcat – 41
  4. JBoss – 32
  5. Sun -21
  6. JRun – 3
  7. GlassFish – 0
  8. Geronimo – 0

(more…)

Generic DAO and more

August 9, 2006

Since Java 5 introduced new generics feature many aspects of our Java coding has changed. DRY approach to many tiers in J2EE soared and become common place. Even such a conservative monsters as IBM come up with nice generic-based patterns. Have a look at this really good article Dont repeat the DAO. They did not invent something new but rather summarised bit and pieces in pretty well done generic DAO. However if you have simple web-based CRUD project you can go even further and generify your managers. Most of the time managers do exactly the same job providing additional wrapper around DAO. So it is the same CRUD as we had in DAO but DataBase -agnostic. So lets have a look at our DAO:
(more…)

Job interview question 1

August 7, 2006

Q: Write equation function for class

public class Customer {
private int id;
private String name;
private float balance;
}

A1: What for? It is already implemented in Object class.
A2: Why me? My favourite IDE generates such staff for me.
A3: You think for a while and write classical equation code with null-checking, casting and equation of values of all fields.
A4: Easy job. Just put inside

return EqualsBuilder.reflectionEquals(this, other);

A5: Look mait! It seems to be a Business object! And field “id” looks like primary key for me! So it should be something like:

public boolean equals(Object other) {
if(this.id==null)
return false;
if (other==null)
return false;
if( !(other.getClass().equals(this.getClass())))
return false;
return id.equals((Customer)other.id);
}

Java: most wanted

July 27, 2006

javapic  -I know Java.
-Wonderful! It is exactly what we need! When you can start?

Funny job interview? It was like that in nineties but not anymore. Now Java is so broad that two experienced Java programmers that develop similar(from user’s point of view) applications may not know any of tools, frameworks, IDEs, AppServers that other is using. Sometimes bunch of technologies is chosen based on company’s budget, sometimes it depends on vendors support, sometimes it just because of historical reasons.
Whatever was the cause it is the fact that Java-flavour in Australia is significantly different to European. So my “Europe-tailored” skill set become slightly “out of fashion” and need some altering according to local preferences. That is why I decided to start new project that exploits all modern Australian java technologies, tools, etc. As an architect I have to sacrifice some good practices and even common sense as it would never allow me … let say use 1.4 -based things in the middle of 2006.
What am I building? It is n-tiered webapp that allows me to manage simple schedule and TODO list and receive voice remainders over the phone. I will add whatever I want to it as soon as I feel like it.
Let the show begin! I introduce java buzz-words in Australian IT market.
1. Oracle. Nobody cares about postgres, mysql, derby and other open-sourced rdbms.
2. Hibernate. No surprises here.
3. Spring. It is extremely popular all around the world.
4. Struts. Still alive. Bit outdated technology that is demanded 5 times more than Spring MVC or JSF.
5. AJAX. It is rarely used but people like this word. So do I.
6. SOA! WebServices, SOAP, BPEL and all other SOA-related terms.
7. WebSphere + WSAD(RAD). WebSphere beats WebLogic, JBoss, Tomcat, GlassFish altogether.
The first release will comprise whatever is ready scheduled to 1 September 2006. Will keep you informed how the project goes. By the way. The name is Ascon.

Java trivia

July 18, 2006

JavaSketchWe all know core java very well. But there is always something to be curious about. Or be surprised. Take a look

  Object objectA = ObjectB.new ObjectC();

Something is wrong with that. Tell me what.