Saturday, December 29, 2007

Google Interview Question - Part 7

Here is another question:

Write a function f(a, b) which takes two character string arguments and returns a string containing only the characters found in both strings in the order of a. Write a version which is order N-squared and one which is order N.

And here is the answer:

A:

private static String match(String a, String b)

{

String result = "";

Set lettersSet = new HashSet(26);

for (int i=0; i

lettersSet.add(new Character(b.charAt(i)));

}

for (int i=0; i

if (lettersSet.contains(new Character(a.charAt(i)))) {

result=result+a.charAt(i);

}

}

return result;

}

Thursday, December 27, 2007

Hibernate .vs. Pure JDBC

There is a wrong assumption that Hibernate is slower then JDBC, this is not true.
For the tests that I have done I had found that Hibernate performance are not less then Pure JDBC.

I had compared the performance between Hibernate and Pure JDBC for writing 10,000 rows to the DB table, The results are really surprising.

The test run on a single thread which write in a loop the rows in bulk update, the JDBC used batch update processing with prepared statement, the Hibernate run on a single session which flush the inserts to the DB every 100 rows (Bulk Updates).

I had worked with Hibernate 3.0 on a regular Pentium Pentium 4 2.66GHz with 2GB RAM, The DB was remote Oracle 9 DB.

Well are are the surprising, Hibernate and Pure JDBC results are completely the same !!!
Hibernate doesn't have a huge overhead as you expect it to have.

For the results I manage to write 10,000 rows to the DB in 1.5 Seconds !!!

Here are some tips for improve your Hibernate performance are:

  • Try to reduce the number of open and close of hibernate sessions
  • Using Hibernate bulk updates were possible
  • When using Hibernate bulk updates try to separate the SQL Insert/Update/Delete statements to groups, the DB would process this groups faster (For example 20 SQL inserts then 40 SQL updates and then 25 SQL delete statements)

Wednesday, December 26, 2007

SAP licenses NetWeaver to developers

I found this nice article which says that SAP netweaver can be now used by individuals:
http://www.regdeveloper.co.uk/2007/10/03/sap_netweaver_developer_license/

As I had experience working the the SAP netweaver J2EE Engine - AS (Application Server), I can tell you about my impressions.

The disadvantages are:

  • It take a lot of time to startup the server and to deploy applications (depend on the application size)
  • There are a lot of missing infrastructures which exists in other application servers (such as inline scheduler, cluster singleton, hot deployment) and many open source frameworks wouldn't work properly with the server.
  • All the infrastructures in the server a propriety of SAP (Logging, Security etc')
  • Except SDN there isn't huge community which can help with the development, Other J2EE Engines like JBoss has a lot of forums with questions and answers inside them.

The advantages are:

  • There is a good administrator GUI to manage the server.
  • It is possible to deploy several applications with references between them
  • There is a good JCA, JCO, Web Services infrastructure to connect to the ABAP world.

Again this list are from my personal experience.

Sunday, December 23, 2007

Build Web Application

The big question is the technology is ready to build web application, there are many web applications out there, word processing, spreadsheet, CRM, mail reading and more...



Until now the only application that really succeed running in web is mail reading like http://www.gmail.com/ and CRM application like http://www.salesforce.com/ why is that?



GMail succeed because you want to read you mail from anywhere in world, It has a very good spam filter which and it run pretty fast on the web, the disadvantages which it has are:

  • It is limited in storage space
  • It can't run offline and the data is not private.
  • Download/upload huge file can take a lot of time

So what the the characteristics which are require by a good web application:

  • It should run offline, so if the connection to the Internet is closed it would be possible to keep working on the application, This can be done by using Google Gear technology for example.
  • It should be able to synchronise the files on the local machine with the server if the user wants to share his own local private data with other users.
  • The Application would be able to know that there is a new software release on the server and upgrade to the new release offline.
  • The initialize of the web application would take long time only on the first time accessing the application, since then it should cache on the browser cache directory and run locally.
  • The user would be able to save his own private work data locally on the machine, the web application would know to synchronize it with the server in asynchronise way.

Saturday, December 22, 2007

XA Two Phase Transactions doesn't work

When you use XA or in it's second name Two Phase Commit Transaction and the transaction doesn't work it can be cause by one of the following reasons:

  • You didn't declare transaction manager in your application server or in your spring XML configuration file
  • You declared transaction manager but no annotation was defined for the EJB or the annotation was defined NOT_SUPPORTED
  • There is annotation but if you call from some method in the EJB to another method in the same EJB the second method can't open transaction since it is a local call which doesn't execute through the j2ee engine interpreter and therefore not transaction is opened. A Possible solution for that is to use UserTransaction and open the transaction pragmatically or to move the second method to another EJB.

Google Interview Question - Part 6

Continue with the question in the previous post:
http://j2ee-now.blogspot.com/2007/12/google-interview-questions-part-5.html

Here is the answer to the question,
If two threads would run in parallel and call this method with values 10 and 7,
The first thread would create the array with size 10 and then thread 2 would re-initialize the same static array with size 7, then the fist thread would run on the array from 0 to 9 and would put values inside however the array size is now 7 so on list[7] it would throw the exception.

Wednesday, December 19, 2007

Runtime Exception or Regular Exception

This is the question that asked often, when should I throw RuntimeException and where should I throw regular Exception, this is the answer:

  • If you exception which is thrown is pure technical exception from which the client can't recover from then throw RunTime Exception in case you run in J2EE server with Transaction Manager set then it would also rollback the transaction. Even that this exception doesn't have to be declared as part of the function exception signature it is advice to declare it so the client would be aware for this exception.
  • If your exception is pure business applicative exception then this exception should be regular not RunTime exception so this exception would be displayed for the user in the end and he would be able to change something to fix it, when throwing this exception in J2EE server with Transaction Manager the transaction doesn't rollback.

Google Interview Questions Part 5

Here is a snippest of code, how it is possible that the code would throw ArrayIndexOutOfBoundsException ?

private static String[] list = null;

public static String[] getArray(size) {
list= new String[size];
for (int i = 0; i < size; i++) {
list[i] = "a" + i
}
return list;
}

This question is a bit tricky

Tuesday, December 18, 2007

Google Interview Questions Part 4

Here are some other questions and solutions

Q: N threads .. n resources .. what protocol do you use to ensure no deadlocks occur?
A1: Avoiding Deadlocks with Lock Leveling, each thread would have different level, thread with high level would be able to lock thread with lower level but not contrary.
A2: Avoid acquiring more then one lock at a time.
A3: Acquire the lock always in the same order. A4: Shrink synchronized blocks.

Q: You are given a the source to a application which is crashing when run. After running it 10 times in a debugger, you find it never crashes in the same place. The application is single threaded, and uses only the C standard library. What programming errors could be causing this crash? How would you test each one?
A1: It might be using time, or perhaps random numbers. Or it does nasty things with memory. Or it could be running under windows.
A2: There might be multiple recursions in the code which are causing a stack overflow, cause "Out Of Memory" exception
A3: A probable cause would be an uninitialized pointer/variable being used

Monday, December 17, 2007

Google Interview Questions Part 3

Q: Here are some more questions and answers:
Which bits are on in the three packets of the handshake?

A: it’s SYN, SYN+ACK, ACK, The source want to send data to he destination, In first step it sends SYN to ask the desination if he is ready to receive data, then the destination wants to answer that he is ready for receiving bits
so he sends SYN+ACK, then the source need to confirm to the destination that he got is request so he send back ACK.

TCP is connection oriented while UDP is not.
TCP: connection establishment -> data transfer -> connection termination

1. The initiating host (client) sends a synchronization (SYN flag set) packet to initiate a connection. Any SYN packet holds a Sequence Number. The Sequence Number is a 32-bit field in TCP segment header. For example let the Sequence Number value for this session be x.
2. The other host receives the packet, records the Sequence Number of x from the client, and replies with an acknowledgment and synchronization (SYN-ACK). The Acknowledgment Number is a 32-bit field in TCP segment header. It contains the next sequence number that this host is expecting to receive (x + 1). The host also initiates a return session. This includes a TCP segment with its own initial Sequence Number value of y.
3. The initiating host responds with a next Sequence Number (x+1) and a simple Acknowledgment Number value of y + 1, which is the Sequence Number value of the other host + 1.



Q: What is Karatsuba algorithm?
A: It's algorithm to do mulipilacation of two large positive numbers with n digits in the complexity of O(n^2)


Q: Tell me what happens when you type www.google.com into a web browser
A1: Explaining that DNS operates via UDP, port 53, and so forth …, the ip address is returned from the DNS
(Sometimes the ISP cache this URL->IP mapping and this save the time of accessing the DNS).
and HTTP GET request is send to google.com server, which return the HTML of the google.com homepage.
A2: Google's DNS servers perform load balancing to allow the user to access Google's content most rapidly. This is done by sending the user the IP address of a cluster that is not under heavy load, and is geographically proximate to them. Each cluster has a few thousand servers, and upon connection to a cluster further load balancing is performed by hardware in the cluster, in order to send the queries to the least loaded Web Server

Google Interview Questions Part 2

Well here is the solution for the question from

http://j2ee-now.blogspot.com/2007/12/google-interview-questions-part-1.html

First you should pass on the list and create a new list with the summary of the numbers till now, for example if the list is:

-7 12 -5 13 -2

Then the new list would be:

-7 5 0 13 11

The subset with holds the largest sequential sum is the subset from the lowest number in the new list plus index 1 (In our case -7 (index 0) is the lowest so we start from 5 (index 1)) till the highest number in the list which is 13 (index 3) so the result is (12, -5, 13) which it's sum is 20.

Why does it work? because if we went from he lowest sum till now to the highest sum till now this is the biggest different of the numbers in the summary therefore this numbers sum would be the largest in the list.



You can find more Google Interview Questions here:

Google Interview Questions Part 3
Google Interview Questions Part 4
Google Interview Questions Part 5
Google Interview Questions Part 6
Google Interview Questions Part 7

Sunday, December 16, 2007

Google Interview Questions Part 1

A friend of mine was interview for a position in Google, he got this hard question asked:

"You have a list of numbers which some of them are negative and some of them are positive, find out the largest sum of sequential subset of numbers from this list."

For example:

-5, 20, -4, 10, -18

The solution is the subset [20, -4, 10] which its sum is 26

The solution for this question is not summary the positive numbers or sort the list because the subset needs to be sequential.

A possible not efficient answer would be to to calculate the summary of all the possible subsets in the list but the complexity of this solution is O(N^2)

However the interviewer wanted a solution of O(N) !!!

Let see you solve this problem in few minutes...

In the next post I would publish the solution

Saturday, December 15, 2007

GWT Instnace Messaging 2

In the previous post I described a simple way to implement instant messaging using GWT, the technique was to use polling which every few seconds look for a new chat message.

However this technique is not efficient, I had found a better implementation which use "push" from the server to the client to implement the instant messaging.
You can read more about it at:

http://code.google.com/p/google-web-toolkit-incubator/wiki/ServerPushFAQ

Friday, December 14, 2007

Eclipse Debugger Influence

Here is a nice example of how debugging in eclipse would ruin your application flow.

Suppose you add the following varilable watch: "iterator.next()" because you want to see the value of the list.

After each time you would press "step into" or "step over" in the debugger the iterator would advance to the next element beacuse the debugger invoke next() method.

In this case with debugger it wouldn't run right, but without debugger it would run fine.

Thursday, December 13, 2007

Google Maps using GWT

There is a nice project which allow to use google maps in GWT,
You can download it from:

http://sourceforge.net/projects/gwt/

This project is really great, hoever The API allow you to convert Location to Lat/Lng coords, but it doesn't allow to convert Lat/Lng coords to Location.

So the solution here is to use SOA, there is a nice WebService which allow you to convert Lat/Lng to Location, it can be download from:

http://www.geonames.org/source-code/

After installing it you can write this code to convert Lat/Lng to Location/Country:

List places = WebService.findNearbyPlaceName(lat, lng);

if (!places.isEmpty()) {
Toponym toponym = (Toponym) places.iterator().next();
String countryName = toponym.getCountryName();
}

Wednesday, December 12, 2007

Mapping Hibernate to DB View

There is a problem to map POJO to DB View using Hibernate if you are using also HBM2DLL.
In this case the HBM2DLL would create for each HBM mapping a corresponsing DB table.

To solve the problem -

  • Write HBM as usual
  • Add deletion of the DB table as follow:


DROP TABLE MY_TABLE;


  • Create the view as follow (also in databse object tag)
CREATE VIEW MY_VIEW AS SELECT ....;

Hibernate would write data and read data now with the DB view.

Tuesday, December 11, 2007

Free Chat Implementation in GWT

I want to share my chat implementation for GWT, this is a pretty simple code which demonstrate how to write an Instand Messaging system inside the browser using AJAX and GWT technology.

The idea is simple, we have a chat factory in which each client can subscribe, There is a Chat Panel in which the user can send messages to the sever in async way. In the server there is a List which holds all the messages which all the clients sent.

There is a polling mechanism which run every few seconds and check if there are new chat messages to display.

The implementation is not state of the art but it works and it can be improved to work better.

Enjoy the implementation:


public class MyChatFactory {

private static final MyChatFactory instance = new MyChatFactory();
private static final int DELAY = 10000;

private MyChatFactory() {
}

public static MyChatFactory getInstance() {
return instance;
}

public void subscribeToEvent(final String queueName, final ChatCallback callback) {
ClientUtil.log("start subscribeToEvent");

Timer eventsTimer = new Timer() {
public void run() {
ChatProxy.getEvents(queueName, callback);
schedule(DELAY);
}
};

eventsTimer.schedule(DELAY);
}

public void sendMessage(String queueName, ChatMessage message) {
ChatProxy.sendMessage(queueName, message);
}

public void sendMessageToAll(ChatMessage message) {
ChatProxy.sendMessage(null, message);
}
}

public class ChatCallback extends GeneralCallback {

public ChatCallback() {
}

public void onSuccess(Object result) {
//ClientUtil.log("start ChatCallback.onSuccess");
if (result!=null) {
ChatMessage chatMessage = (ChatMessage) result;

if (chatMessage.isLogin()) {
ChatPanel.getInstance().addUser(chatMessage.getMessage());
} else {
ChatPanel.getInstance().addText(chatMessage.getMessage());
}
}
//ClientUtil.log("finish ChatCallback.onSuccess");
}

public void onFailure(Throwable caught) {
ClientUtil.log(caught.getMessage());
}
}

public class ChatMessage implements IsSerializable{

private String message;
private boolean isLogin;

public ChatMessage() {
}

public ChatMessage(String message, boolean isLogin) {
this.message=message;
this.isLogin=isLogin;
}


public boolean isLogin() {
return isLogin;
}
public void setLogin(boolean isLogin) {
this.isLogin = isLogin;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}

public class ChatProxy {

private static ChatServiceAsync chatService = (ChatServiceAsync) GWT.create(ChatService.class);

static {
ClientUtil.setEndpointForService(chatService, "chat");
}

public static void getEvents(String queueName, ChatCallback callback) {
chatService.getEvents(queueName, callback);

}

public static void sendMessage(String queueName, ChatMessage message) {
VoidCallback callback = new VoidCallback();
chatService.sendMessage(queueName, message, callback);
}

}

public interface ChatService extends RemoteService {

public ChatMessage getEvents(String queueName);

public void sendMessage(String queueName, ChatMessage chatMessage);
}

public class ChatServiceImpl extends RemoteServiceServlet implements ChatService {

private static final long serialVersionUID = 1L;

private static Map subscribers = new HashMap();
//private static final long INTERVAL = 200000-1000;

public ChatMessage getEvents(String queueName) {
List list = null;

if (!subscribers.containsKey(queueName)) {
list = new ArrayList();
subscribers.put(queueName, list);
} else {
list = (List) subscribers.get(queueName);
}

if (!list.isEmpty()) {
ChatMessage message = (ChatMessage) list.get(0);
list.remove(0);
return message;
}

return null;
}

public void sendMessage(String queueName, ChatMessage chatMessage) {

if (queueName!=null) {
if (subscribers.containsKey(queueName)) {
List list = (List) subscribers.get(queueName);
list.add(chatMessage);
}
} else { // If null then send to all
Iterator subscribeIter = subscribers.values().iterator();

while (subscribeIter.hasNext()) {
List list = (List) subscribeIter.next();
list.add(chatMessage);
// list.notify();
}
}
}

}

ClassCastException Solution

The obvious cause for ClassCastException is that you try to cast from one class to another class but the other class is not a parent of the class you try to cast, but there are other cases in which ClassCastException can happen:

AClass aObject = (AClass) bObject;

- bObject doesn't inherit from AClass or it doesn't AClass instance.

- bObject inherit from AClass or it is AClass instance, however bObject was loaded by a different class loader, In this case the JVM consider bObject as a different class, the solution is to load AClass only in one of the class loaders, the same class shouldn't be loaded by two different class loaders.

For example:
Object a1 = new A(); // Load by classLoader x
Object a2 = new A(); // Load by classLoader y

a1 = (A) a2; // Would throw ClassCastException

ClassNotFoundException Solution

Here is a list of possible problems which would may case ClassNotFoundException and the solution for this problems

  1. The class doesn't exists in the classpath, You can add it to your classpath by either click on properties of the project and add it to the java build path or you can choose run->classpath->and add the jar.
  2. The class exists in the classpath, but it has a static section in the beginning of the class which throws an exception in this case the class doesn't create by the classloader, the solution is to fix the exception thrown in the static section or add try catch.
  3. The class exists but it is loaded by a different classloader, for example you have two EAR files in which one need to access another one, The solution is to add reference between this two EAR files, or making one of the class loaders be the parent of the other class loader

Monday, December 10, 2007

Resource Bundle Surprise

Not many people knows but Resource Bundle which used to read properties files actually cache the property file content in memory, those changing the content of the properties file at run time wouldn't influence on the application.

The question is how to cause the application to reload the properties file without the need to restart the application server?

The answer is a bit tricky since the resource bundle doesn't expose an API to refresh the cache of the properties file, there is a need to write an MBean which would invoke by the JMX console and this MBean would refresh the properties file content, here is the code for that:

Class aClass = ResourceBundle.getBundle(PROPERTIES_FILE).getClass().getSuperclass();
Field field = aClass.getDeclaredField("cacheList");
field.setAccessible(true);
sun.misc.SoftCache cache = (sun.misc.SoftCache) field.get(null);
cache.clear();


First we get the class of the resource bundle, then we change the cacheList field from private to public (Yes it is possible to change using reflection private memebers to public members) and then get invoke clear method on the cache field.

JMS Helper

In many application there is a need to send asynchronise messages, The right solutions is usually to use JMS Api, however the JMS Api is not trivial to use, and in many cases the user may forget to close the session or the publisher or it does it but not in finanlly block.

A good solution is to build a light framework above the JMS API which would take care for all this issues.

Here is the code implentation for the JMS Helper which take care for all the JMS issues as opening and closing the sessoins, and it prove a simple easy to use API:

public class JMSHelper
{
private static final Logger logger = Logger.getInstance();

/**
* Publish notification to a specific topic (topicRef) with a message, the notification is sent using

* the publish/subscribe mechanism of the JMS.
*
* @param jmsFactory
* @param topicRef the topic jndi name to reference to
* @param message the message to deliver, if the message is null then empty message is publish
* @param isTransacted indicates whether the publish is transacted
* @param properties the properties on the message, the properties used by the selector, if this value is null then no properites are transferred
* @throws JmsException
*/
public static void publish(String jmsFactory, String topicRef, Serializable message, boolean isTransacted, HashMap properties) throws JmsException
{
TopicConnection topicConnection = null;
Topic topic = null;
TopicSession topicSession = null;
TopicPublisher topicPublisher = null;
TopicConnectionFactory topicConnectionFactory = null;

try
{
// get the topic connection factory from JNDI
topicConnectionFactory = (TopicConnectionFactory) ServiceLocator.getInstance().getService(jmsFactory);

// create topic connection
topicConnection = topicConnectionFactory.createTopicConnection();

// get the topic from JNDI
topic = (Topic) ServiceLocator.getInstance().getService(topicRef);

// create topic session
topicSession = topicConnection.createTopicSession(isTransacted, Session.AUTO_ACKNOWLEDGE);

// create sender
topicPublisher = topicSession.createPublisher(topic);

// publish
ObjectMessage objectMessage = topicSession.createObjectMessage();

// Set the message properties (selectors)
if (properties!=null)
{
Map.Entry element = null;
Iterator propertyIterator = properties.entrySet().iterator();

while (propertyIterator.hasNext())
{
element = (Map.Entry) propertyIterator.next();
objectMessage.setObjectProperty((String) element.getKey(), element.getValue());

}
}

// Set the message text
if (message!=null)
{
objectMessage.setObject(message);
}

// Publish
topicPublisher.publish(objectMessage);
}
catch (Exception exception)
{
logger.error(exception,"Failed to publish JMS message");
throw new JmsException(exception);
}
finally
{
try
{

// clos es the jms topic session
if (topicSession!=null)
{
topicSession.close();
}

// closes the topic publisher
if (topicPublisher!=null)
{
topicPublisher.close();
}

}
catch (Exception exception)
{
logger.error(exception,"Failed closing the jms connection");
throw new JmsException(exception);
}
}
}

}

Improve Hibernate performance using Bulk

If your application needs to run under heavy stress you can improve a lot the performance using hibernate by using bulk updates.

Hibernate allow you to to write bulk of several SQL insert statements at one time,
To do it you need to open an hibernate session, write a set of sql insert statements or a set of sql update statements (don't mix the insert and the update statements togther), and call session.flush() this would use the DB capabilities to write bulk of sql statments in efficent way.

Hibernate underneath use something like JDBC Batch to implement the bulk updates.

I succeed to write in this way 10,000 rows in 1.5 seconds in Oracle DB Table on a simple Pentium machine.

Sunday, December 9, 2007

Is Hibernate Portable?

Hibernate is considered to be portable framework in which you can move from one databse to another database without the need to change the code at all, Does is it true?

It is true that most of the code and the HBM files (or anotations) would remain the same when moving from one database to another database, however there are some exceptional cases.

For example consider the following simple HQL query:
select from USERS where NAME=?

If the column NAME is nullable in the databse and you would pass null value as parameter then in MySQL it would return all the rows where NAME is NULL, However in Oracle it wouldn't return any row at all, the reason for it is that in Oracle
NULL==NULL is false.

There are other much more exceptional cases, please comment if you need other examples.

So the answer for the question is Hibernate Portable is Yes for 90% of code but No for 10% other perecent of code.

Generic equal and toString

When writing unit tests in many cases it's required to implement toString to display the DTO (Data Transfer Object) in the log file or in the console for debugging.

In this case a good solution is to use generic DTO implementaion which implement "toString" method in a generic way using reflection, The method pass on all the getters methods recusivly and print the fields values, If a new field is added or removed the toString code doesn't need to be change.

In the same way it can be also used to implement generic "equals" method which compare each two getters of two objects recusevly.

This implementaion is also suitable for tests and I don't recommened to use that where performance issues are important since it use reflection.

Here is the implementation code

/**
* Generic DTO class

* Implements a functionality such as toString(), equals() , etc.
*/
public abstract class GenericDTO implements Serializable
{

private static final Logger logger = Logger.getInstance();

/**
* A String representation of all the get methods.
*
* @return A String concatenations toString of the returned values of all the get methods.

* The get methods do not have parameters
*/
public String toString()
{
Method[] methods = this.getClass().getMethods();
StringBuffer result = new StringBuffer();
boolean comma = false;
try
{
int length = methods.length;
result.append("[");
for (int i = 0; i < length; i++)
{
String methodName = methods[i].getName();
if (methodName.startsWith("get") && !methodName.startsWith("getClass"))
{
if (comma)
{
result.append(", ");
}
else
{
comma = true;
}

Object o = methods[i].invoke(this, null);
result.append(methodName.substring(3)); //after the get
result.append("():");
if (o==null)
{
result.append("null");
}
else
{
result.append(o.toString());
}
}

}
result.append("]");
}
catch (IllegalArgumentException e)
{
logger.error("toString()", e);
}
catch (IllegalAccessException e)
{
logger.error("toString()", e);
}
catch (InvocationTargetException e)
{
logger.error("toString()", e);
}
return result.toString();
}

/**
* Indicates whether some other object is "equal to" this one

* An AbstractDTO is equal to another if and only if it is the same class and have

* the same values of the get methods.
*
* @return true if it the same class and the returned values of the get methods are equal
* false otherwise
*/
public boolean equals(Object obj)
{
if (this == obj)
{
return true;
}
boolean result = false;
try
{
if (obj.getClass() == this.getClass())
{
result = true;
Method[] objMethods = obj.getClass().getMethods();
int methodsLength = objMethods.length;

int i = 0;
while (i < methodsLength && result)
{
String methodName = objMethods[i].getName();
if (methodName.startsWith("get"))
{
// invoke on my object
Object objReturnedObject = objMethods[i].invoke(this, null);
// invoke on the parameter object
Object myReturnedObject = objMethods[i].invoke(obj, null);

if (objReturnedObject==null)
{
if (myReturnedObject!=null)
{
result = false;
}
}
else
{
if (!objReturnedObject.equals(myReturnedObject))
{
result = false;
}
}
}
i++;
}
}
}
catch (IllegalArgumentException e)
{
logger.error("equals()", e);
return false;
}
catch (IllegalAccessException e)
{
logger.error("equals()", e);
return false;
}
catch (InvocationTargetException e)
{
logger.error("equals()", e);
return false;
}

return result;
}

}

JSF Unit Testing

There is a new framework for sdoing JSF Unit Testing, this is part of JBoss Unit testing tools: http://labs.jboss.com/jsfunit/

Untill now it was very hard to write unit tests for JSF, This framework can increase the quality of the product by running daily unit tests on the UI screens, it seems that the framework is pretty easy to use and simple.

Saturday, December 8, 2007

When to flush session in hibernate?

I heard once an hibernate expert says that there is no need in any way to flush the hibernate session, According to this expert the hibernate knows better then the developer when to flush the session and when not, For example if the developer insert data to the DB several times and then read select the same row from the DB then Hibernate would just flush before the select statement.

However this is not true, there are cases when flush the session is mandatory.

For example consider the following case: In a method you insert some data to a DB table, then you send a JMS message (asynchronously) which invoke MDB which need to select the same data (in a different hibernate session) which was insert to the DB just before the JMS message,

In this case the data my not flush yet by the hibernate before the MDB select the same data,
In this case it is required to flush the session before sending the JMS message.

Will SOA Succeed?

SOA is hot buzzword in the development community, all the major software companies adopt this buzzword and develop infrastructure to implement it but is SOA is reality or fiction.

The Idea behind SOA (Service Oriented Architecture) is that different services are exposed using Web Services with a specific API, in this development of a new application would just need to write a workflow with steps in which each step would access a different Web Service.

There are several major problems with this SOA idea:

  • Web Service API needs to be appropriate for each client/application which access it, and API can't be appropriate for each client/application.
  • If the Client/Application needs to access several times the Web Service API to complete the task then there are several round-trips with XML-Soap parsing/de-parsing which take a lot of time
  • Performance - Calling an EJB in RMI is much faster then calling Service using Web Service which need to translate objects to XML and XML to objects
  • There is a problem to expose API in Web Service for example an API which get List of Objects and in which each application can be a Polymorphic of another Object, this can't be describe in WSDL file

XML Workflow Engine

There are many frameworks (i.e JBPM etc') which allow to create workflows in XML files and then run this workflows on the Application server.

I think that this frameworks are useless and not necessery the feature which they provide are usually are:

- UI to change the process steps ar run-time
- stateful context to store data for the current process

The reason which this frameworks are useless is because if a workflow process needs to be changes for a specific customer then you can't just change the XML file where the process definition is stored, you usually need to also add new classes for new steps or you need to change the UI.

Regard the stateful context you can just store it in session cache or in a stateful bean.

The maintenance of this XML is very complicated and if writing the steps in a single POJO class would be much more easy for maintenance.

J2EE Rapid Development

Developing in J2EE environment should be fast and rapid, I have been working with all this J2Ee Servers - WebSphere, WebLogic, Netweaver, JBoss. All this application servers except JBoss take a lot of time to finish their startup, some of them take few minutes and some more then 10 minuets, this is pretty frustrating making some small change in the code and then wait more then 10 minutes for the server to start and then to wait some more minutes for the deploy to finish.

In JBoss it is pretty fast it take about one minute for the startup to finish, and about two minutes for the deploy to finish, This may save a lot of time to develop in J2EE Environment,

Not to mention the great feature of hot-deployment in which the code inside the method can be change without the need to restart the application server.

Many development managers doesn't take in consideration this thing when choosing application server, In my opinion this can save a lot of time and improve the development speed.

Links

 
RSS Feeds Submission Directory