Recently in java Category

Pattern Reminder: Singleton

| | Comments (0) | TrackBacks (0)

Definition: The pattern is used to ensure that only one instance of an class is used. It offers a global point of access to this object. Before Java5 consider double checked locking to be thread-safe.

Example: Lets think of using only one connection to whatever throughout the program.

singleton.jpg

Connection:

public class Connection {
//volatile !!!!
private static volatile Connection connection;
//private Constructor
private Connection(){}
public static Connection getInstance(){
if (connection == null)//check first
{
synchronized(Connection.class) //one access per thread. sync only once
{
if (connection == null) //check again
return new Connection();
}
}
return connection;
}
}

Pattern Reminder: Command

| | Comments (0) | TrackBacks (0)

Definition: The Command pattern defines the concept of encapsulating an action as an object and lets you parameterize clients with different requests, queue requests, log requests or undo operations.

Java Example: A classic example for an implementation of the command pattern is a remote control which switches the light on and off. An example for an command queue would be a disco-lighting system.

commandpattern.jpg

ICommand:

public interface ICommand {
public void execute();
public void reset();
}

LightOnCommand (LightOffCommand would simply print out "light off") :


public class LightOnCommand implements ICommand {
public void execute() {
System.out.println("light on");
}
public void reset() {@TODO}
}

Remote Control:


public class RemoteControl {
ICommand SwitchOn;
public void setCommand(ICommand aCommand)
{
SwitchOn= aCommand;
SwitchOn.execute();
}
}

RemoteControlTest:


public static void main(String [] args)
{
RemoteControl remote = new RemoteControl();
remote.setCommand(new LightOnCommand());
remote.setCommand(new LightOffCommand());
}

And this is an implementation for a command queue. Let´s go to the discotheque....

LightingSystem:

public class LightingSystem implements ICommand {
ICommand[] commands;
public LightingSystem (ICommand[] c)
{ commands = c; }
public void execute()
{
for (int i = 0; i < commands.length; i++) {
commands[i].execute();
}
}
public void reset() {
for (int i = 0; i < commands.length; i++) {
commands[i].reset();
}
}
}

And the test:

public static void main(String[] args) {
LightOnCommand on = new LightOnCommand ();
LightOffCommand off= new LightOffCommand ();

ICommand[] techno= {on,off,on,off,on,off,on,off};
LightingSystem strobo= new LightingSystem (techno);
strobo.execute();
}

Pattern Reminder: Observer

| | Comments (0) | TrackBacks (0)

Definition: The Observer Pattern defines a One-to-Many dependency between objects in a way that all dependent objects get automatically notified und updated, if the state of an object changes. Subjects or Observables notify Observers over an defined interface. Observers do not get notified in a particular order. Swing, JavaBeans and RMI use the Pattern often.

Java Example: A client registers to a newsletter and gets notified for every new news.

observer.jpg

Subject:

public class Newsletter extends Observable
{
private String news;
public Newsletter(){}
public void setNewNews(String text)
{
this.news = text;
setChanged();
notifyObservers(this);
}
public String getNews()
{
return news;
}

Observer:

public class NewsReader implements Observer {
Observable observable;
public NewsReader(Observable ob)
{
this.observable = ob;
this.observable.addObserver(this);
}
public void update(Observable obs, Object obj) {
if (obs instanceof Newsletter) {
Newsletter newsletter = (Newsletter)obs;
System.out.println(newsletter.getNews());
}
}
}

Pattern Reminder: Strategy

| | Comments (0) | TrackBacks (0)

Starting a new series to remember the good old gof design patterns. The STRATEGY Pattern will be my first entry.

Definition: "Define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently from the clients that use it." [Gamma]

Java Example: The client uses a capsuled family of algorithms. In this case we encapsulate a behaviour.

strategy.jpg


Client:

public abstract class Fighter {
FightingBehaviour fightingBehaviour;
public Fighter(){ };
public void fight(){fightingBehaviour.fight(); }
public void setFightingBehaviour(FightingBehaviour fb) {fightingBehaviour = fb;}
}

Client Implementations:


public class Boxer extends Fighter
{
public Boxer()
{
fightingBehaviour = new BoxingBehaviour();
}
}

Algorithm:


public interface FightingBehaviour {
public void fight();
}

Algorithm Implementation:

public class BoxingBehaviour implements FightingBehaviour {
public void fight() {
System.out.println("Raise fist!");
}
}

Test it:


Fighter fighter = new Boxer();
fighter.fight();

Thats basically it. It is now very easy to add new behaviours or fighters and change their algorithms.

Web Services II

| | Comments (0) | TrackBacks (0)

leaving my work with this not very dynamic axis solution, i contuined experimenting with this topic.

WSDL4J and WSIF seemed to bring me to another stage.
my idea for experimenting was, to insert the url of a wsdl-file in a html-form, read its service-definitions and present the contents with the possibility of invoking single operations along with their parameters.

and this the result of my thoughts:

1. input.html: basic and uncomfortable form:

Enter URL to your favourite WSDL:

<input type="text" name="wsdluri" size="150 ″button type="submit">Explore it !

2. the requests finishes in the arms of a servlet. here the url-string is forwarded to some methods which use the wsdl4j-api.
basically this:

WSDLReader reader = WSDLFactory.newInstance().newWSDLReader();
Definition def = reader.readWSDL(wsdlurl);
session.setAttribute("services",def.getServices().values().iterator());
String target = response.encodeRedirectURL("listing.jsp");
response.sendRedirect(target);

3. the jsp processes the iterator and presents all available operations and so on.
this also implements wsdl4j-api. i moved code to a wsdl-helper class which i use on the jsp. i know... java code on jsp = bad style, but in experimental-mode, who cares

that is the main part without out.println´s of the listing.jsp:

Iterator iterator = (Iterator)session.getAttribute("services");
while (iterator.hasNext())
{
Service service = (Service)iterator.next();
QName qname = service.getQName();
Port[] ports = util.getPortsFromService(service);
for (int i = 0; i < ports.length; i++)
{
Port port = ports[i];
Operation [] ops = util.getOperationsForPort(port);
for (int j = 0; j < ops.length; j++)
{
Operation op = ops[j];
List order = op.getParameterOrdering();
if (order!=null && order.size()>0)
{
Iterator orderit = order.iterator();
while(orderit.hasNext())
{
String param = (String)orderit.next();
}
}
//here onclick: set hidden fields
document.forms[0].porttype.value='util.getPorttype(port).getQName().getLocalPart()';document.forms[0].porttypeNS.value='util.getPorttype(port).getQName().getNamespaceURI()';document.forms[0].service.value='qname.getLocalPart()';document.forms[0].serviceNS.value='qname.getNamespaceURI()';document.forms[0].operation.value='op.getName()';document.forms[0].actionparam.value='invoke';document.forms[0].submit();


the setting of some hidden fields is at the moment required for getting the proper ws.
this form also gets handled from the servlet mentioned above.

4. the servlet know calls the part with the wsif stuff

important code snips are:

create wsif-connection:


WSIFService wsifService = WSIFServiceFactory.newInstance().getService(def,serviceNS,service,porttypeNS,porttype);
WSIFPort wsifPort = wsifService.getPort();
WSIFOperation wsifOp = wsifPort.createOperation(operation,inputName,outputName);
WSIFMessage inMsg = wsifOp.createInputMessage();
WSIFMessage ouMsg = wsifOp.createOutputMessage();
WSIFMessage fault = wsifOp.createFaultMessage();

set parameters if needed

inMsg.setObjectPart(part.getName(),paramMap.get(part.getName()));

execute:


if (wsifOp.executeRequestResponseOperation(inMsg,ouMsg,fault))
{
java.util.Iterator iter = ouMsg.getPartNames();
while(iter.hasNext())
{
String name = (String)iter.next();
return (String)ouMsg.getObjectPart(name);
}
}

the returned string is presented on a jsp again.

Web Services I

| | Comments (0) | TrackBacks (0)

started some web services experience with axis, wsdl4j and wsif.
i decided to do some try and error on this topic after downloading the eclipse WTP project and clicking through the various wizards. generating a service and a serviceclient with axis and wtp was very easy, i just followed this !
this is the simple class i used to create a service.


public class Answer
{

public String getGoodbye()
{
return "So long and thanks for all the fish";
}

}

next step was to get the client working.i used wsdl2java wizard to created the client stubs. Then used the code on a jsp


AnswerProxy proxy = new AnswerProxy();
Answer answer = proxy.getAnswer();
out.println(answer.getGoodbye());

last step was to deploy both on tomcat5 and watch the output in the browser.
very easy so far. but not very dynamically.

About this Archive

This page is a archive of recent entries in the java category.

fun is the previous category.

javascript is the next category.

Find recent content on the main index or look in the archives to find all content.

java: Monthly Archives

Powered by Movable Type 4.0