10 Ağustos 2007 Cuma

Core Design Patterns: Abstract Factory Pattern

Abstract Factory Pattern: Bu paternin yaptığı iş bir çok değişik factory objesini encapsule etmekdir. Creation ile ilgili bir patterndir. Kullanımı şöyledir. Client uygulama abstract factory classından somut bir obje yaratır. Ve bu objenin genel methodlarını kullanır. Client uygulama alt seviyede yaratılan objenin hangi obje olduğunu bilmez. Bu pattern bir obje kümesinin implementasyon ayrıntıları ile genel kullanımını birbirinden ayırır.

Örnek Kod:

Button.java

package factory;
abstract class Button
{
public abstract void paint();
}

OSXButton.java
package factory;
class OSXButton extends Button
{
public void paint()
{
System.out.println("I'm an OSXButton: ");
}
}

WinButton.java
package factory;
class WinButton extends Button
{
public void paint()
{
System.out.println("I'm a WinButton: ");
}
}

GUIFactory.java
package factory;
abstract class GUIFactory
{
public static GUIFactory getFactory()
{
//int sys = readFromConfigFile("OS_TYPE");
int sys=1;
if (sys == 0)
{
return new WinFactory();
}
else
{
return new OSXFactory();
}
}

public abstract Button createButton();
}

OSXFactory.java
package factory;
class OSXFactory extends GUIFactory
{
public Button createButton()
{
return new OSXButton();
}
}

WinFactory.java
package factory;
class WinFactory extends GUIFactory
{
public Button createButton()
{
return new WinButton();
}
}

Application.java
package factory;
public class Application
{
public static void main(String[] args)
{
//GUIFactory içindeki int sys=1 satırı int sys=0 yapılırsa winButton üretilir.
GUIFactory factory = GUIFactory.getFactory();
Button button = factory.createButton();
button.paint();
}
// Output is either:
// "I'm a WinButton:"
// or:
// "I'm an OSXButton:"
}

UML Of Abstract Factory Pattern

Core Design Patterns: Decorator Pattern

Decorator Pattern: run time da var olan obje yada objelere yeni davranış şekilleri eklemek için kullanılır. Bu pattern bir tür subclass işlemidir ancak extend işlemi compile time da değil runtime da yapılmaktadır. Bu da ekstra flexibility kazandırır.

Decorator pattern bir decorator objesinin diğer bir objeyi wrap etmesi şeklinde yapılır. Ve bu genelde decorator objesinin constructorına diğer objenin parametre olarak girmesi ile sağlanır.

Örnek Kod:

DecoratedWindowTest.java
package decoratorPattern;

public class DecoratedWindowTest {
public static void main(String[] args) {
// create a decorated Window with horizontal and vertical scrollbars
Window decoratedWindow = new HorizontalScrollBarDecorator (
new VerticalScrollBarDecorator(new SimpleWindow()));

// print the Window's description
System.out.println(decoratedWindow.getDescription());
}
}

HorizontalScrollBarDecorator.java
package decoratorPattern;
// the second concrete decorator which adds horizontal scrollbar functionality
class HorizontalScrollBarDecorator extends WindowDecorator {
public HorizontalScrollBarDecorator(Window decoratedWindow) {
super(decoratedWindow);
}

public void draw() {
drawHorizontalScrollBar();
decoratedWindow.draw();
}

private void drawHorizontalScrollBar() {
// draw the horizontal scrollbar
}

public String getDescription() {
return decoratedWindow.getDescription()
+ ", including horizontal scrollbars";
}
}

SimpleWindow.java
package decoratorPattern;

// implementation of a simple Window without any scrollbars
class SimpleWindow implements Window {
public void draw() {
// draw window
}

public String getDescription() {
return "simple window";
}
}

VerticalScrollBarDecorator.java
package decoratorPattern;

// the first concrete decorator which adds vertical scrollbar functionality
class VerticalScrollBarDecorator extends WindowDecorator {
public VerticalScrollBarDecorator(Window decoratedWindow) {
super(decoratedWindow);
}

public void draw() {
drawVerticalScrollBar();
decoratedWindow.draw();
}

private void drawVerticalScrollBar() {
// draw the vertical scrollbar
}

public String getDescription() {
return decoratedWindow.getDescription()
+ ", including vertical scrollbars";
}
}

Window.java
package decoratorPattern;

// the Window interface
interface Window {
public void draw(); // draws the Window
public String getDescription(); // returns a description of the Window
}


WindowDecorator.java
package decoratorPattern;

// abstract decorator class - note that it implements Window
abstract class WindowDecorator implements Window {
protected Window decoratedWindow; // the Window being decorated

public WindowDecorator(Window decoratedWindow) {
this.decoratedWindow = decoratedWindow;
}
}

UML Of Decorator Pattern

Core Design Patterns: Command Pattern

Command Pattern: Actionları objeye encapsule etme yönteminin adıdır. Her bir action bir object olarak düşünülür. Bu sayede yeniden kullanabilme, loglayabilme, undo v.s. bir çok vantaj sağlamaktadır.

Örnek Kod:
/*
The Design Patterns Java Companion

Copyright (C) 1998, by James W. Cooper

IBM Thomas J. Watson Research Center

*/

package CommandPattern;

import java.awt.Button;
import java.awt.Color;
import java.awt.FileDialog;
import java.awt.Frame;
import java.awt.Menu;
import java.awt.MenuBar;
import java.awt.MenuItem;
import java.awt.Panel;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class ActionCommand extends Frame {
Menu mnuFile;

MenuItem mnuOpen, mnuExit;

Button btnRed;

Panel p;

Frame fr;

//-----------------------------------------
public ActionCommand() {
super("Frame without commands");
fr = this; //sae cop of this frame
MenuBar mbar = new MenuBar();
setMenuBar(mbar);

mnuFile = new Menu("File", true);
mbar.add(mnuFile);

mnuOpen = new MenuItem("Open...");
mnuFile.add(mnuOpen);
mnuExit = new MenuItem("Exit");
mnuFile.add(mnuExit);

mnuOpen.addActionListener(new fileOpen());
mnuExit.addActionListener(new fileExit());

btnRed = new Button("Red");
p = new Panel();
add(p);
p.add(btnRed);

btnRed.addActionListener(new btnRed());
setBounds(100, 100, 200, 100);
setVisible(true);
}

//-----------------------------------------
private void exitClicked() {
System.exit(0);
}

//-----------------------------------------
static public void main(String argv[]) {
new ActionCommand();
}

//=====----====--inner classes---=====----
class fileOpen implements ActionListener {
public void actionPerformed(ActionEvent e) {
FileDialog fDlg = new FileDialog(fr, "Open a file", FileDialog.LOAD);
fDlg.show();
}
}

//-------------------------------------
class btnRed implements ActionListener {
public void actionPerformed(ActionEvent e) {
p.setBackground(Color.red);
}
}

//-------------------------------------
class fileExit implements ActionListener {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
}
}
//=====================================

Core Design Patterns:Facade Pattern

Facade Pattern bir nesne merkezli tasarım paternidir.Facade in kelime anlamı maske , önyüz anlamındadır. Bir facade nesnesi büyük, karmaşık bir kod bloğuna yada bir sınıf kütüphanesine basit bir arayüzdür. Yani karmaşık kütüphanelerin client tarafından kolay kullanımı sağlar.


FacadeSınıfı
package facadePattern;
import java.text.*;
import java.util.*;
/** "Façade" */
class UserfriendlyDate
{
Calendar cal = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

public UserfriendlyDate (String isodate_ymd) throws ParseException {
Date date = sdf.parse(isodate_ymd);
cal.setTime(date);
}

public void addDays (int days) {
cal.add (Calendar. DAY_OF_MONTH, days);
}

public String toString() {
return sdf.format(cal.getTime());
}
}


Client Code:
package facadePattern;
import java.text.ParseException;
class FacadePattern
{
public static void main(String[] args) throws ParseException
{
UserfriendlyDate d = new UserfriendlyDate("1980-08-20");
System.out.println ("Date: " + d);
d.addDays(20);
System.out.println ("20 days after: " + d);
}
}

UML of Façade Pattern

Core Design Patterns: Observer Pattern

Observer Pattern: Bu pattern haberleşme ile ilgili bir patterndir. Bir objenin başka bir objedeki değişiklikten haberdar olması ihtiyacına cevap verir.

Örnek Kod:

EvenstSource Objesi
package observerPattern;
import java.util.Observable; //Observable is here
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class EventSource extends Observable implements Runnable
{
String response;
public void run()
{
try
{
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
while( true )
{
response = br.readLine();
setChanged();
notifyObservers( response );
}
}
catch (IOException e)
{
e.printStackTrace();
}
}
}

/* File Name: ResponseHandler.java */
package observerPattern;
import java.util.Observable;
import java.util.Observer; /* this is Event Handler */

public class ResponseHandler implements Observer
{
private String resp;
public void update(Observable obj,Object arg)
{
if(arg instanceof String)
{
resp = (String) arg;
System.out.println("\nReceived Response: "+ resp );
}
}
}


/* Filename : myapp.java */
/* This is main program */
package observerPattern;
public class myapp
{
public static void main(String args[])
{
System.out.println("Enter Text >");
EventSource evSrc = new EventSource();
ResponseHandler respHandler = new ResponseHandler();
evSrc.addObserver(respHandler);
evSrc.run();
}
}
Observer Pattern UML

9 Ağustos 2007 Perşembe

Core Design Patterns: Adapter Pattern

package adapterPattern;

/*

Software Architecture Design Patterns in Java
by Partha Kuchana

Auerbach Publications

*/

import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;

import com.sun.java.swing.plaf.windows.WindowsLookAndFeel;

public class AddressManager extends JFrame {
public static final String newline = "\n";

public static final String VALIDATE = "Validate";

public static final String EXIT = "Exit";

private JTextField txtCustomerName, txtAddress, txtZip, txtState;

private JLabel lblCustomerName, lblAddress;

private JLabel lblZip, lblState, lblType;

private JComboBox cmbAddressType;

private JLabel lblResult, lblResultValue;

public AddressManager() {
super(" Adapter Pattern - Example ");

txtCustomerName = new JTextField(20);
txtAddress = new JTextField(20);
txtZip = new JTextField(10);
txtState = new JTextField(10);

cmbAddressType = new JComboBox();
cmbAddressType.addItem(Customer.US);
cmbAddressType.addItem(Customer.CANADA);

lblCustomerName = new JLabel("Customer Name:");
lblAddress = new JLabel("Address:");
lblZip = new JLabel("Zip/PostalCode:");
lblState = new JLabel("State/Province:");
lblType = new JLabel("Address Type:");
lblResult = new JLabel("Result:");
lblResultValue = new JLabel("Click the Validate Button");

//Create the open button
JButton validateButton = new JButton(AddressManager.VALIDATE);
validateButton.setMnemonic(KeyEvent.VK_V);
JButton exitButton = new JButton(AddressManager.EXIT);
exitButton.setMnemonic(KeyEvent.VK_X);
ButtonHandler objButtonHandler = new ButtonHandler(this);

validateButton.addActionListener(objButtonHandler);
exitButton.addActionListener(new ButtonHandler());

JPanel captionPanel = new JPanel();
String captionText = ""
+ "Adapter Pattern Example
";

JLabel captionLabel = new JLabel(captionText);
captionPanel.add(captionLabel);

JPanel UIPanel = new JPanel();

//****************************************************
GridBagLayout gridbag = new GridBagLayout();
UIPanel.setLayout(gridbag);
GridBagConstraints gbc = new GridBagConstraints();

UIPanel.add(lblCustomerName);
UIPanel.add(txtCustomerName);
UIPanel.add(lblAddress);
UIPanel.add(txtAddress);
UIPanel.add(lblZip);
UIPanel.add(txtZip);
UIPanel.add(lblState);
UIPanel.add(txtState);
UIPanel.add(lblType);
UIPanel.add(cmbAddressType);
UIPanel.add(lblResult);
UIPanel.add(lblResultValue);

UIPanel.add(validateButton);
UIPanel.add(exitButton);

gbc.insets.top = 5;
gbc.insets.bottom = 5;
gbc.insets.left = 5;
gbc.insets.right = 5;
gbc.anchor = GridBagConstraints.WEST;

gbc.gridx = 0;
gbc.gridy = 0;
gridbag.setConstraints(lblCustomerName, gbc);
gbc.gridx = 1;
gbc.gridy = 0;
gridbag.setConstraints(txtCustomerName, gbc);
gbc.gridx = 0;
gbc.gridy = 1;
gridbag.setConstraints(lblAddress, gbc);
gbc.gridx = 1;
gbc.gridy = 1;
gridbag.setConstraints(txtAddress, gbc);
gbc.gridx = 0;
gbc.gridy = 2;
gridbag.setConstraints(lblZip, gbc);
gbc.gridx = 1;
gbc.gridy = 2;
gridbag.setConstraints(txtZip, gbc);
gbc.gridx = 0;
gbc.gridy = 3;
gridbag.setConstraints(lblState, gbc);
gbc.gridx = 1;
gbc.gridy = 3;
gridbag.setConstraints(txtState, gbc);
gbc.gridx = 0;
gbc.gridy = 4;
gridbag.setConstraints(lblType, gbc);
gbc.gridx = 1;
gbc.gridy = 4;
gridbag.setConstraints(cmbAddressType, gbc);
gbc.gridx = 0;
gbc.gridy = 5;
gridbag.setConstraints(lblResult, gbc);
gbc.gridx = 1;
gbc.gridy = 5;
gridbag.setConstraints(lblResultValue, gbc);

//gbc.anchor = GridBagConstraints.CENTER;
gbc.insets.left = 2;
gbc.insets.right = 2;
gbc.insets.top = 40;

JPanel buttonPanel = new JPanel();
buttonPanel.add(validateButton);
buttonPanel.add(exitButton);
UIPanel.add(buttonPanel);
gbc.gridx = 1;
gbc.gridy = 6;
gridbag.setConstraints(buttonPanel, gbc);

//

//Add the buttons and the log to the frame
Container contentPane = getContentPane();
contentPane.add(UIPanel, BorderLayout.CENTER);

try {
UIManager.setLookAndFeel(new WindowsLookAndFeel());
SwingUtilities.updateComponentTreeUI(AddressManager.this);
} catch (Exception ex) {
System.out.println(ex);
}

}

public static void main(String[] args) {
JFrame frame = new AddressManager();

frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});

//frame.pack();
frame.setSize(350, 300);
frame.setVisible(true);
}

public String getCustomerName() {
return txtCustomerName.getText();
}

public String getAddress() {
return txtAddress.getText();
}

public String getZip() {
return txtZip.getText();
}

public String getAddrState() {
return txtState.getText();
}

public String getAddressType() {
return (String) cmbAddressType.getSelectedItem();
}

public void setResultValue(String str) {
lblResultValue.setText(str);
}

} // End of class AddressManager

class ButtonHandler implements ActionListener {
AddressManager objAddressManager;

public void actionPerformed(ActionEvent e) {
String validationResult = null;

//System.out.println(e.getActionCommand());
if (e.getActionCommand().equals(AddressManager.EXIT)) {
System.exit(1);
}
if (e.getActionCommand().equals(AddressManager.VALIDATE)) {
String custName = objAddressManager.getCustomerName();
String address = objAddressManager.getAddress();
String zip = objAddressManager.getZip();
String state = objAddressManager.getAddrState();
String addressType = objAddressManager.getAddressType();

//Create a customer object
Customer objCustomer = new Customer(custName, address, zip, state,
addressType);

//Check if the address is valid
if (objCustomer.isValidCustomerAddress()) {
validationResult = "Valid customer data";
} else {
validationResult = "Invalid customer data";
}

objAddressManager.setResultValue(validationResult);
}
}

public ButtonHandler() {
}

public ButtonHandler(AddressManager inObjAddressManager) {
objAddressManager = inObjAddressManager;
}

} // End of class ButtonHandler

class USAddress extends AddressValidator {

public boolean isValidAddress(String inp_address, String inp_zip,
String inp_state) {

if (inp_address.trim().length() <> 10)
return false;
if (inp_state.trim().length() != 2)
return false;

return true;
}
}// end of class

class Customer {
public static final String US = "US";

public static final String CANADA = "Canada";

private String address;

private String name;

private String zip, state, type;

public boolean isValidCustomerAddress() {
if (type.equals(Customer.US)) {
USAddress us = new USAddress();
return us.isValidAddress(address, zip, state);
}
if (type.equals(Customer.CANADA)) {
CAAddress objCAAddress = new CAAddress();
CAAddressAdapter adapter = new CAAddressAdapter(objCAAddress);
return adapter.isValidAddress(address, zip, state);
}
return true;
}

public Customer(String inp_name, String inp_address, String inp_zip,
String inp_state, String inp_type) {

name = inp_name;
address = inp_address;
zip = inp_zip;
state = inp_state;
type = inp_type;
}
}// end of class

class CAAddressAdapter extends AddressValidator {

private CAAddress objCAAddress;

public CAAddressAdapter(CAAddress address) {
objCAAddress = address;
}

public boolean isValidAddress(String inp_address, String inp_zip,
String inp_state) {

return objCAAddress
.isValidCanadianAddr(inp_address, inp_zip, inp_state);
}
}// end of class

class CAAddress {

public boolean isValidCanadianAddr(String inp_address, String inp_pcode,
String inp_prvnc) {

if (inp_address.trim().length() < 15) return false; if (inp_pcode.trim().length() != 6) return false; if (inp_prvnc.trim().length() < 6) return false; return true; } }// end of class abstract class AddressValidator { public abstract boolean isValidAddress(String inp_address, String inp_zip, String inp_state); }// end of class

UML Of Adapter Pattern

1 Ağustos 2007 Çarşamba

What is the difference between standard webservice and wrapped webservice

The difference between wrapped and normal webservice is not very important. The xml files send are very similar in both methodolgy. Than what is the difference.
Difference is about the interfaces:

Standard Document Style Web Service Interface:
public class SimpleServiceSOAPImpl implements SimpleService_PortType{
public String concat(ConcatRequest concatRequest) ... {
return concatRequest.getS1()+concatRequest.getS2();
}
}

Wrapped Document Style Web Service Interface:
public class SimpleServiceSOAPImpl implements SimpleService_PortType{
public String concat(String s1, String s2) ... {
return s1+s2;
}
}

But both are document style web services at real.

Tomcat Deploy Tips

tomcat\conf\Catalina\localhost klasöründe bir xml file yaratılır.
Örnek içerik:
Axis.xml


Burada yapılan işlem tomcate c:/axis/webapps/axis klasörünün bir webapplication olduğunu söylemektir. Ve http://........./Axis pathi ile browserdan erişileceği söylenmektedir.

RPC and Document Style WebServices

RPC Style Interface WS Interface

Local name: concat
Namespace: http://ttdev.com/ss
Input message:
Part 1:
Name: s1
Type: string in http://www.w3.org/2001/XMLSchema
Part 2:
Name: s2
Type: string in http://www.w3.org/2001/XMLSchema
Output message:
Part 1:
Name: return
Type: string in http://www.w3.org/2001/XMLSchema


Document Style WS Interface

Local name: concat
Namespace: http://ttdev.com/ss
Input message:
Part 1:
Name: concatRequest
Element: concatRequest in http://ttdev.com/ss
Output message:
Part 1:
Name: concatResponse
Type: string in http://www.w3.org/2001/XMLSchema

Note: See that we have an xsd scheme in the document style ws interface, but not in a rpc style ws interface.


Compare the input messages of the RPC style web service and the document style
web service:

RPC Style Request:

abc
123


Document Style Request:

abc
123


According to WS-I (web services interoperability organization), you should use
document style web services only.

28 Temmuz 2007 Cumartesi

Ant Tasks For Axis

This is a template page

Some of Widely Known And Used Design Patterns

Some of Widely Known And Used Design Patterns
The Observer Pattern
The Decorator Pattern
The Factory Pattern
The Singleton Pattern
The Command Pattern
Tha Adapter and Facade Pattern
The Template Method Pattern
The Iterator and Composite PAttern
The State Pattern
The Proxy Pattern

26 Temmuz 2007 Perşembe

13 Haziran 2007 Çarşamba

XML Parsers

Some of the XML parsers
• Apache Xerces: http://xml.apache.org/
• IBM XML4J: http://alphaworks.ibm.com/tech/xml4j
• James Clark's XP: http://www.jclark.com/xml/xp
• Oracle XML Parser: http://technet.oracle.com/tech/xml
• Sun Microsystems Crimson: http://xml.apache.org/crimson
• Tim Bray's Lark and Larval: http://www.textuality.com/Lark
• The Mind Electric's Electric XML:http://www.themindelectric.com/products/xml/xml.html
• Microsoft's MXSML Parser: http://msdn.microsoft.com/xml/default.asp

Web Services Frameworks

Widely Used Web Service Frameworks:
Axis
Axis2
Xfire

Widely Used EE Frameworks

Spring
Jdon
Expresso

Widely Used Web Frameworks

Widely Used Web Frameworks
1) Struts
2) JSF
3) Tapestry
4) Cocoon
5) Spring
6) Hibernate

Also WebOnSwing is an interesting web framework.

Favorite Books

* The Design Patterns Java Companion
By Addison Wesley Design Patterns Series
Author=James W. Cooper
* Java Cookbook
O'Reilly
Author=Ian Darwin

* O'Reilly Java and XML
Author=Brett McLauglin
* Java Web Services
O'Reilly
Author= David Chappell & Tyler Jewell
* A Programmer's Guide to JAVA Certification
Addison Wesley
Author=KHalid A. Muqhal, Rolf W. Rasmussen
* Java 2: Web Developer Certification Study Guide
Sybex
Author=Natalie Levi, Phillip Heller
* Enterprise Integration Patterns:
Author=by Gregor Hohpe (Author), Bobby Woolf

J2EE Concepts

1) Web Tier
*Servlet
*JSP
*JSTL
*Custom Tagged JSPs
*JSF
2) Web Services
*JAX-WS
*XML Schema and Java Object Binding
*stax
*JAXR Java API for XML Registry
3) Enterprise Beans
*Session Beans
*Message Driven Beans
4) Persistence
*Persistence in the web tier
*Persistence int the ejb tier
5) Services
*Security
*JMS API
*Transactions
*Resource Connections JNDI

Java Basics

1) Basics of Java Programming
2) Declarations and Access Control
3)Exception Handling and Assertions
4) Object Oriented Programming
5) Nested Classes and Interfaces
6) Object Lifetime
7) Threads
8) java.lang package --
9) Collections and Maps-- java.util