Friday, May 7, 2010

Custom Event Handler in Java

An Event Class which will be produced by producers and listened by listeners.
public class CustomEvent implements java.io.Serializable{

private int eventType = 0;
private String eventDetail = "";

public String getEventDetail () {
return eventDetail;
}

public int getEventType () {
return eventType;
}

public void setEventDetail (String eventDetail) {
this.eventDetail = eventDetail;
}

public void setEventType (int eventType) {
this.eventType = eventType;
}
}
An Interface which is a contract between event producers and listeners.
public interface EventListenerIntf {
public void handleEvent (CustomEvent event) throws Exception;
}

An Event Listener
public class EventListener implements EventListenerIntf{
public EventListener () {
EventProducer.addListener (this);
}

private String name = null;

public void handleEvent (CustomEvent event) {
System.out.println ("Event handled by "+ this.name+" : EventType: "+event.getEventType()+" EventDetail :"+event.getEventDetail());
}

public String getName () {
return name;
}

public void setName (String name) {
this.name = name;
}

}
A Producer which produces events and have its listener list.
public class EventProducer {
private static List listenerList = new java.util.ArrayList ();

public static synchronized void addListener (EventListener listener) {
listenerList.add (listener);
}

public static synchronized void produceEvents () {
CustomEvent event1 = new CustomEvent ();
event1.setEventType (1);
event1.setEventDetail ("event1 detail");
notifyEventListeners (event1);

CustomEvent event2 = new CustomEvent ();
event2.setEventType (2);
event2.setEventDetail ("event2 detail");
notifyEventListeners (event2);

CustomEvent event3 = new CustomEvent ();
event3.setEventType (3);
event3.setEventDetail ("event3 detail");
notifyEventListeners (event3);

CustomEvent event4 = new CustomEvent ();
event4.setEventType (4);
event4.setEventDetail ("event4 detail");
notifyEventListeners (event4);
}

public static void notifyEventListeners (CustomEvent event) {
for (EventListener listener : listenerList) {
listener.handleEvent (event);
}
}
}

Lets make a simple test these with a simple scenario.

public class Test {
public static void main (String[] args) {
//Listeners getting up !
EventListener amy = new EventListener ();
amy.setName ("Amy");
EventListener april = new EventListener ();
april.setName ("April");
EventListener eli = new EventListener ();
eli.setName ("Eli");

// Producer will create some events
EventProducer.produceEvents();

System.out.println (" good bye");
System.exit (0);
}
}


And out output is :

Event handled by Amy : EventType: 1 EventDetail :event1 detail
Event handled by April : EventType: 1 EventDetail :event1 detail
Event handled by Eli : EventType: 1 EventDetail :event1 detail
Event handled by Amy : EventType: 2 EventDetail :event2 detail
Event handled by April : EventType: 2 EventDetail :event2 detail
Event handled by Eli : EventType: 2 EventDetail :event2 detail
Event handled by Amy : EventType: 3 EventDetail :event3 detail
Event handled by April : EventType: 3 EventDetail :event3 detail
Event handled by Eli : EventType: 3 EventDetail :event3 detail
Event handled by Amy : EventType: 4 EventDetail :event4 detail
Event handled by April : EventType: 4 EventDetail :event4 detail
Event handled by Eli : EventType: 4 EventDetail :event4 detail
good bye

Thursday, May 6, 2010

Java WebService Example : JAXWS

A Class which is a web service
package jaxws;
import javax.jws.WebMethod;
import javax.jws.WebService;

@WebService
public class Hello {
private String message = "Hello, ";

public void Hello() {}

@WebMethod
public String sayHello(String name) {
return message + name + ".";
}
}
A Class which exposes this web service

package jaxws;
import javax.xml.ws.Endpoint;

public class Server {

protected Server () throws Exception {
System.out.println ("Starting Server");
Object implementor = new Hello ();
String address = "http://localhost:9000/SoapContext/SoapPort";
Endpoint.publish (address, implementor);
}

public static void main (String args[]) throws Exception {
new Server ();
System.out.println ("Server ready...");
System.out.println (" -- Press any key to exit...");
System.in.read ();
System.out.println ("Server exiting");
System.exit (0);
}
}


Get the WSDL from Server : Open the url with your internet browser : http://localhost:9000/SoapContext/SoapPort?wsdl



Create a project for this wsdl via SOAPUI and send requests.So simple!

Monday, May 3, 2010

Sample DateTimeFormatter with locale

Do not change locale system wide , do not disturb others!
Create different locales and formatters with given locale and use them.

import java.text.*;
import java.util.*;

public class DateTimeFormatter {

private static final Locale ukrainianLocale = new Locale ("uk", "UA");
private static final Locale russianLocale = new Locale ("ru", "RU");
private static final Locale englishLocale = new Locale ("en", "EN");

public static DateFormat ukranianDateFormatter;
public static DateFormat russianDateFormatter;
public static DateFormat englishDateFormatter;

public DateTimeFormatter (String dateFormatPattern) {
ukranianDateFormatter = new SimpleDateFormat (dateFormatPattern, ukrainianLocale);
russianDateFormatter = new SimpleDateFormat (dateFormatPattern, russianLocale);
englishDateFormatter = new SimpleDateFormat (dateFormatPattern, englishLocale);
}

public static String format (Date date, String lang) {
String formattedDateTime;
if ("ru".equalsIgnoreCase (lang)) {
formattedDateTime = russianDateFormatter.format (date);
} else if ("en".equalsIgnoreCase (lang)) {
formattedDateTime = englishDateFormatter.format (date);
} else {
formattedDateTime = ukranianDateFormatter.format (date);
}
return formattedDateTime;
}

public static void main (String[] args) {
DateTimeFormatter df = new DateTimeFormatter ("dd/MMM/yy HH:mm");
Date now = new Date ();
System.out.println ("uk date:" + df.format (now, "uk"));
System.out.println ("en date:" + df.format (now, "EN"));
System.out.println ("ru date:" + df.format (now, "ru"));
}
}

uk date:03/трав/10 16:17
en date:03/May/10 16:17
ru date:03/май/10 16:17

Thursday, April 29, 2010

Talk to friends, not to strangers.

There is a well-known heuristic called the Law of Demeter .

Law of Demeter says that a method f of a class C should only call the methods of these:
• C
• An object created by f
• An object passed as an argument to f
• An object held in an instance variable of C

The method should not invoke methods on objects that are returned by any of the
allowed functions. In other words, talk to friends, not to strangers

Sample Violation : final String outputDir = ctxt.getOptions().getScratchDir().getAbsolutePath();

If the code had been written as follows, then we probably wouldn’t be asking about Demeter violations.

final String outputDir = ctxt.options.scratchDir.absolutePath;

This issue would be a lot less confusing if data structures simply had public variables
and no functions, whereas objects had private variables and public functions

-- Clean Code by Robert Martin

Wednesday, April 28, 2010

Data Abstraction

Concrete Vehicle
public interface Vehicle {
double getFuelTankCapacityInGallons();
double getGallonsOfGasoline();
}

Abstract Vehicle
public interface Vehicle {
double getPercentFuelRemaining();
}

In both of the above cases the second option is preferable. We do not want to expose
the details of our data. Rather we want to express our data in abstract terms. This is not
merely accomplished by using interfaces and/or getters and setters. Serious thought needs
to be put into the best way to represent the data that an object contains. The worst option is
to blithely add getters and setters.



-- Robert Martin / Clean Code