Tuesday, 11 May 2010

Design Patterns

I am thinking to do the SCEA exam, so first started preparing the design patterns.

In day-to-day design/development many places we need to use the patterns, but most of the times we just write the code without knowing the exact patterns.

Patterns can make the system robust and can re-use it.

I share my experience with the design patterns.

Startegy Pattern

In Strategy Pattern, the algorithms(behavior) can be selected at run time.




The strategy pattern is intended to provide a means to define a family of algorithms, encapsulate each one as an object, and make them interchangeable. The strategy pattern lets the algorithms vary independently from clients that use them.



Example code:

Following program add/subtract/multiply/divide(s) the two numbers and this add/subtract/multiply/divide behavior(strategy) has been extracted out defined as a interface.

This strategy has been referenced in the context class and it can be changed dynamically using the constructor/setter method.





//StrategyPatternSample

class StrategySample {

public static void main(String[] args) {

Context context;

context = new Context(new StrategyAdd());
System.out.println(context.executeStrategy(12,3));

context = new Context(new StrategySubtract());
System.out.println(context.executeStrategy(12,3));

context = new Context(new StrategyMultiply());
System.out.println(context.executeStrategy(12,3));

context = new Context(new StrategyDivide());
System.out.println(context.executeStrategy(12,3));

}

}


// The strategy interface
interface IStrategy {

int run(int a, int b);

}

// Implements the algorithm using the strategy interface
class StrategyAdd implements IStrategy {

public int execute(int a, int b) {
System.out.println("add");
return a + b;
}

}

class StrategySubtract implements IStrategy {

public int execute(int a, int b) {
System.out.println("subtract");
return a - b;
}

}

class StrategyMultiply implements IStrategy {

public int execute(int a, int b) {
System.out.println("multiply");
return a * b;
}

}

class StrategyDivide implements IStrategy {

public int execute(int a, int b) {
System.out.println("divide");
return a / b;
}



// Configured with a ConcreteStrategy object and maintains a reference to a Strategy object
class Context {

private IStrategy strategy;

// Constructor
public Context(IStrategy strategy) {
this.strategy = strategy;
}

public int executeStrategy(int a, int b) {
return strategy.execute(a, b);
}

//setter method for strategy
public void setStrategy(IStrategy strategy) {
this.strategy = strategy;
}


}

Monday, 10 May 2010

Refactoring

What is Refactoring
Refactoring is the process of changing the source code alterning the internal structure without changing the external behavior of the code.

Before refactoring the code, complete set of unit-test cases are required. After refactoring the small piece of code then run the test suite to make sure that the code is not broken.

Advantages:
- Readability
- Maintainability
- Extendability

Refactoring Techniques:
o Encapsulate Field – force code to access the field with getter and setter methods
o Generalize Type – create more general types to allow for more code sharing
o Extract Method, to turn part of a larger method into a new method. By breaking down code in smaller pieces, it is more easily understandable. This is also applicable to functions.
o Extract Class moves part of the code from an existing class into a new class.
o Move Method or Move Field – move to a more appropriate Class or source file
o Rename Method or Rename Field – changing the name into a new one that better reveals its purpose
o Pull Up – in OOP, move to a superclass
o Push Down – in OOP, move to a subclass

Martin Fowler explains the refactoring techniques with the diagrams and is really good.

Refactoring Techniques by Martin Fowler

Friday, 7 May 2010

Composition / Inheritence

inheritance models the is-a relationship




class Fruit {

public String taste() {

System.out.println("It is sweet.");
return "Sweet";
}
}

class Orange extends Fruit {

//...
}




composition models the has-a relationship




class Fruit {

//...
}

class Orange {

private Fruit fruit = new Fruit();

public String taste() {
return fruit.taste();
}

}





* Composition allows you to delay the creation of back-end objects until (and unless) they are needed, as well as changing the back-end objects dynamically throughout the lifetime of the front-end object.

* With inheritance, you get the image of the superclass in your subclass object image as soon as the subclass is created, and it remains part of the subclass object throughout the lifetime of the subclass.

* It is easier to add new subclasses (inheritance) than it is to add new front-end classes (composition), because inheritance comes with polymorphism.

* The explicit method-invocation forwarding (or delegation) approach of composition will often have a performance cost as compared to inheritance's single invocation of an inherited superclass method implementation.

Wednesday, 17 December 2008

JAXWS - Create Web Service Client

i) install SOAP UI Plugin for Eclipise
http://www.soapui.org/eclipse/update/site.xml

ii) Create a new project for the HelloSeriveClient (Java Project)

iii) Select the project and Right Click->Soap UI->Add SOAPUI Nature, SOAP UI WebService item will be added

iv) Select SOAP UI perspective
Right click on Projects->hellowworlclient->Add WSDL from URL, enter the deployed service URL: http://localhost:8080/HelloService/Hello?wsdl. This will import the wsdl and you will see HelloPortBinding

v)Select HelloPortBinding and Right Click->GenerateCode->JAX-WS Artifacts
Enter the appropriate info in the JAX-WS Artifacts window

vi) Click Tools and enter the location of JAX-WS Wsimport.bat file.
* if you are using Java6 create the wsimport.bat file (only wsimport.exe file is available in Java 6, but soapUI plugin expects wsimport.bat file)
@echo off
setlocal
call wsimport.exe %1 %2 %3 %4 %5 %6 %7 %8 %9"
endlocal

vii) Click OK

viii) Then click Generate on JAX-WS Artifacts window, it will display dialog box the operation was successful. Switch back to Java Perspective, then refresh the src folder and you can see the wsimport generated classes.

ix) Now you implement HelloServiceClient code.

package test;

import mypackage.Hello;
import mypackage.HelloService;

public class TestHelloService {

/**
* @param args
*/
public static void main(String[] args) {
// Create Service
HelloService service = new HelloService();
//create proxy
Hello proxy = service.getHelloPort();
//invoke
System.out.println(proxy.sayHello("srini"));
}

}

Friday, 12 December 2008

Create your First Web Service Application using JAXWS

NetBeans Environment:
i) Create a new java Web Project name it "HelloService"
ii) create a new java class "Hello.java" and Add "@WebService" annotation at the top of the class
@WebService
public class Hello {
public String sayHello(String name) {
return "Hello " + name ;
}
}

iii) Deploy your application
right click the project and Deploy


That's it.. Your first web service application is ready.

Eclipse Evnironment:

i)Create the Dynamic Web Project "HelloService"
ii) web.xml
------------
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<listener>
<listener-class>
com.sun.xml.ws.transport.http.servlet.WSServletContextListener</listener-class>
</listener>
<servlet>
<servlet-name>Hello</servlet-name>
<servlet-class>com.sun.xml.ws.transport.http.servlet.WSServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Hello</servlet-name>
<url-pattern>/Hello</url-pattern>
</servlet-mapping>
</web-app>

iii) sun-jaxws.xml (create under WEB-INF folder )

<?xml version="1.0" encoding="UTF-8"?>
<endpoints version="2.0"
xmlns="http://java.sun.com/xml/ns/jax-ws/ri/runtime">
<endpoint implementation="mypackage.Hello" name="Hello"
url-pattern="/Hello" />
</endpoints>

iv) Copy all the jaxws api files into the WEB-INF\lib folder
v) Create the same Hello.java file (copy the code from step ii - webservices - netbeans setup)
vi) Run this application from Eclipise
Now you can view your service from the following url.
http://localhost:8080/HelloService/Hello