Monday, December 29, 2008

Sample of Java Pattern -- Factory

Customer.java
package factory;

import java.io.Serializable;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;

public class Customer implements Serializable {

private Long customerId;
private String firstName;
private String lastName;
private String address;
private String city;
private String postalCode;
private String workPhone;
private String homePhone;
private String cellPhone;
private String email;
private Date createdOn;
private Date updatedOn;
private Set<Order> orders = new HashSet<Order>(0);

public Long getCustomerId() {
return customerId;
}
public void setCustomerId(Long customerId) {
this.customerId = customerId;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getPostalCode() {
return postalCode;
}
public void setPostalCode(String postalCode) {
this.postalCode = postalCode;
}
public String getWorkPhone() {
return workPhone;
}
public void setWorkPhone(String workPhone) {
this.workPhone = workPhone;
}
public String getHomePhone() {
return homePhone;
}
public void setHomePhone(String homePhone) {
this.homePhone = homePhone;
}
public String getCellPhone() {
return cellPhone;
}
public void setCellPhone(String cellPhone) {
this.cellPhone = cellPhone;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public Date getCreatedOn() {
return createdOn;
}
public void setCreatedOn(Date createdOn) {
this.createdOn = createdOn;
}
public Date getUpdatedOn() {
return updatedOn;
}
public void setUpdatedOn(Date updatedOn) {
this.updatedOn = updatedOn;
}
public Set<Order> getOrders() {
return orders;
}
public void setOrders(Set<Order> orders) {
this.orders = orders;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((email == null) ? 0 : email.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Customer other = (Customer) obj;
if (email == null) {
if (other.email != null)
return false;
} else if (!email.equals(other.email))
return false;
return true;
}

}

Order.java
package factory;

import java.io.Serializable;
import java.util.Date;

public class Order implements Serializable {

private int orderId;
private Customer customer;
private String sku;
private Date createdOn;
private Date updatedOn;
private int status;

public int getOrderId() {
return orderId;
}
public void setOrderId(int orderId) {
this.orderId = orderId;
}
public Customer getCustomer() {
return customer;
}
public void setCustomer(Customer customer) {
this.customer = customer;
}
public String getSku() {
return sku;
}
public void setSku(String sku) {
this.sku = sku;
}
public Date getCreatedOn() {
return createdOn;
}
public void setCreatedOn(Date createdOn) {
this.createdOn = createdOn;
}
public Date getUpdatedOn() {
return updatedOn;
}
public void setUpdatedOn(Date updatedOn) {
this.updatedOn = updatedOn;
}
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((sku == null) ? 0 : sku.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Order other = (Order) obj;
if (sku == null) {
if (other.sku != null)
return false;
} else if (!sku.equals(other.sku))
return false;
return true;
}
}

DomainObjMgmt.java
package factory;

import java.util.Date;

public class DomainObjMgmt {
public static Object create(String which){
Object obj = null;
if (which.equalsIgnoreCase("customer")) {
Customer customer = new Customer();
customer.setFirstName("firstName");
customer.setLastName("lastName");
customer.setAddress("address");
customer.setCity("city");
customer.setPostalCode("postalCode");
customer.setWorkPhone("workPhone");
customer.setHomePhone("homePhone");
customer.setCellPhone("cellPhone");
customer.setEmail("email");
customer.setCreatedOn(new Date());
customer.setUpdatedOn(new Date());
obj = customer;
System.out.println("Creating a customer, done.");
}else if(which.equalsIgnoreCase("order")){
Order order = new Order();
order.setSku("sku");
order.setCreatedOn(new Date());
order.setUpdatedOn(new Date());
obj = order;
System.out.println("Creating an order, done.");
}else{
obj = null;
System.out.println("Could not create this object");
}
return obj;
}
}


FactoryTest.java
package factory;

public class FactoryTest {
public static void main(String[] args) {
Customer customer = (Customer)DomainObjMgmt.create("customer");
Order order = (Order)DomainObjMgmt.create("order");
DomainObjMgmt.create("advisor");
}
}


you may download the source code.

Monday, December 22, 2008

Sample of Java Pattern -- Observer

Appointment.java
package observer;

import java.util.Date;
import java.util.Observable;

public class Appointment extends Observable {
private String host;
private String guest;
private Date appointmentDate;
private int status;

public Appointment(){}

public String getHost() {
return host;
}

public String getGuest() {
return guest;
}

public Date getAppointmentDate() {
return appointmentDate;
}

public int getStatus() {
return status;
}

public void createAppointment(String host, String guest, Date appointmentDate){
this.host = host;
this.guest = guest;
this.appointmentDate = appointmentDate;
this.status = 0;
setChanged();
this.notifyObservers(this);
}

public void cancelAppointment(String host, String guest, Date appointmentDate){
if(this.host != null && this.guest != null && this.appointmentDate != null && this.status != 1){
this.status = 1;
setChanged();
this.notifyObservers(this);
}
}

}



EmailService.java
package observer;

import java.util.Observable;
import java.util.Observer;

public class EmailService implements Observer {
private Observable observable;

public EmailService(Observable observable){
this.observable = observable;
observable.addObserver(this);
}

public void update(Observable o, Object arg) {
if(arg instanceof Appointment){
Appointment appointment = (Appointment)arg;
if(appointment.getStatus() ==0)
System.out.println("send a creation email to host and guest");
else
System.out.println("send a cancellation email to host and guest");
}
}

}



SMSService.java
package observer;

import java.util.Observable;
import java.util.Observer;

public class SMSService implements Observer {
private Observable observable;

public SMSService(Observable observable){
this.observable = observable;
observable.addObserver(this);
}

public void update(Observable o, Object arg) {
if(arg instanceof Appointment){
Appointment appointment = (Appointment)arg;
if(appointment.getStatus() ==0)
System.out.println("send a creation sms to host and guest");
else
System.out.println("send a cancellation sms to host and guest");
}
}
}



ObserverTest.java
package observer;

import java.util.Date;

public class ObserverTest {

public static void main(String[] args) {
Appointment appointment = new Appointment();
EmailService emailService = new EmailService(appointment);
SMSService smsService = new SMSService(appointment);
String host ="";
String guest ="";
Date appointmentDate = new Date();
appointment.createAppointment(host, guest, appointmentDate);
appointment.cancelAppointment(host, guest, appointmentDate);
}

}



you may download the source code.

Monday, December 15, 2008

sample of Java Pattern -- Strategy

Intent
Define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently from clients that use it.

Type
Object Behavioral

Solution
The Strategy Pattern is one of the less complex patterns defined by the Gang of Four. The Strategy Pattern first identifies the behaviors or algorithms that vary and separate them from the system that stays the same. These behaviors or algorithms are encapsulated in classes that implement a common interface. This enables the developer to program to an interface and not an implementation. The different algorithms are encapsulated in a concrete class (ConcreteStrategy). Each of these objects are referenced by classes (Context) through the common interface (Strategy).

Class Diagram Example


Java Sample Code
EmailService.java
package strategy;

public interface EmailService {
public void send(String[] recipients, String subject, String message, String from);
}



GeneralEmailServiceImpl.java
package strategy;

import java.util.Properties;

import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class GeneralEmailServiceImpl implements EmailService {
private String smtpHostName;
private String smtpPort;
private String smtpAuthUser;
private String smtpAuthPwd;

public String getSmtpHostName() {
return smtpHostName;
}

public String getSmtpPort() {
return smtpPort;
}

public String getSmtpAuthUser() {
return smtpAuthUser;
}

public String getSmtpAuthPwd() {
return smtpAuthPwd;
}

public GeneralEmailServiceImpl(String smtpHostName, String smtpPort, String smtpAuthUser, String smtpAuthPwd){
this.smtpHostName = smtpHostName;
this.smtpPort = smtpPort;
this.smtpAuthUser = smtpAuthUser;
this.smtpAuthPwd = smtpAuthPwd;
}

public void send(String[] recipients, String subject, String message, String from) {
boolean debug = false;

Properties props = new Properties();
props.setProperty("mail.transport.protocol", "smtp");
props.setProperty("mail.host", getSmtpHostName());
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.port", getSmtpPort());
props.setProperty("mail.smtp.quitwait", "false");

Authenticator auth = new SMTPAuthenticator();
Session session = Session.getDefaultInstance(props, auth);

session.setDebug(debug);

MimeMessage msg = new MimeMessage(session);

try {
InternetAddress addressFrom = new InternetAddress(from);
msg.setFrom(addressFrom);

InternetAddress[] addressTo = new InternetAddress[recipients.length];
for (int i = 0; i < recipients.length; i++) {
addressTo[i] = new InternetAddress(recipients[i]);
}
msg.setRecipients(Message.RecipientType.TO, addressTo);

msg.setSubject(subject);
msg.setContent(message, "text/html");
Transport.send(msg);
} catch (MessagingException e) {
e.printStackTrace();
return;
}
}

private class SMTPAuthenticator extends javax.mail.Authenticator {
public PasswordAuthentication getPasswordAuthentication() {
String username = getSmtpAuthUser();
String password = getSmtpAuthPwd();
return new PasswordAuthentication(username, password);
}
}

}



GoogleEmailServiceImpl.java
package strategy;

import java.security.Security;
import java.util.Properties;

import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class GoogleEmailServiceImpl implements EmailService {
private String smtpHostName;
private String smtpPort;
private String smtpAuthUser;
private String smtpAuthPwd;

public String getSmtpHostName() {
return smtpHostName;
}

public String getSmtpPort() {
return smtpPort;
}

public String getSmtpAuthUser() {
return smtpAuthUser;
}

public String getSmtpAuthPwd() {
return smtpAuthPwd;
}

public GoogleEmailServiceImpl(String smtpHostName, String smtpPort, String smtpAuthUser, String smtpAuthPwd){
this.smtpHostName = smtpHostName;
this.smtpPort = smtpPort;
this.smtpAuthUser = smtpAuthUser;
this.smtpAuthPwd = smtpAuthPwd;
}

public void send(String[] recipients, String subject, String message, String from) {
boolean debug = false;

Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());

Properties props = new Properties();
props.setProperty("mail.transport.protocol", "smtp");
props.setProperty("mail.host", getSmtpHostName());
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.port", getSmtpPort());
props.setProperty("mail.smtp.quitwait", "false");
props.put("mail.smtp.socketFactory.port", getSmtpPort());
props.put("mail.smtp.socketFactory.class","javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.socketFactory.fallback", "false");

Authenticator auth = new SMTPAuthenticator();
Session session = Session.getDefaultInstance(props, auth);

session.setDebug(debug);

MimeMessage msg = new MimeMessage(session);

try {
InternetAddress addressFrom = new InternetAddress(from);
msg.setFrom(addressFrom);

InternetAddress[] addressTo = new InternetAddress[recipients.length];
for (int i = 0; i < recipients.length; i++) {
addressTo[i] = new InternetAddress(recipients[i]);
}
msg.setRecipients(Message.RecipientType.TO, addressTo);

msg.setSubject(subject);
msg.setContent(message, "text/html");
Transport.send(msg);
} catch (MessagingException e) {
e.printStackTrace();
}
}

private class SMTPAuthenticator extends javax.mail.Authenticator {
public PasswordAuthentication getPasswordAuthentication() {
String username = getSmtpAuthUser();
String password = getSmtpAuthPwd();
return new PasswordAuthentication(username, password);
}
}


}



EmailServiceSelectorTest.java
package strategy;

public class EmailServiceSelectorTest {

public static void main(String[] args) {
String smtpHostName = "";
String smtpPort = "";
String smtpAuthUser = "";
String smtpAuthPwd = "";
String[] recipients = {""};
String subject = "";
String message = "";
String from = "";
GoogleEmailServiceImpl googleEmailServiceImpl = new GoogleEmailServiceImpl(smtpHostName, smtpPort, smtpAuthUser, smtpAuthPwd);
GeneralEmailServiceImpl generalEmailServiceImpl = new GeneralEmailServiceImpl(smtpHostName, smtpPort, smtpAuthUser, smtpAuthPwd);
googleEmailServiceImpl.send(recipients, subject, message, from);
generalEmailServiceImpl.send(recipients, subject, message, from);
}

}



you may download the source code.

Friday, November 28, 2008

Blazeds Configuration under Http and Https

1. visitor --> Flex app on Apache/IIS (Https) --> Backend system on Tomcat/JBoss(Http)
service-config.xml:
<channel-definition 
id="my-amf-secure"
class="mx.messaging.channels.SecureAMFChannel">
<endpoint
uri="https://{server.name}:{server.port}/{context.root}/messagebroker/amfsecure"
class="flex.messaging.endpoints.AMFEndpoint "/>
<properties>
<add-no-cache-headers>false</add-no-cache-headers>
</properties>
</channel-definition>


2. visitor --> Flex app on Apache/IIS (Http) --> Backend system on Tomcat/JBoss(Https)
service-config.xml:
<channel-definition 
id="my-amf"
class="mx.messaging.channels.SecureAMFChannel">
<endpoint
uri="https://{server.name}:{server.port}/{context.root}/messagebroker/amfsecure"
class="flex.messaging.endpoints.SecureAMFEndpoint"/>
<properties>
<add-no-cache-headers>false</add-no-cache-headers>
</properties>
</channel-definition>

Tuesday, November 25, 2008

Bind Java Object to Flex Object

To represent a server-side Java object in a client application, you use the [RemoteClass(alias=" ")] metadata tag to create an ActionScript object that maps directly to the Java object. You specify the fully qualified class name of the Java class as the value of alias. This is the same technique that you use to map to Java objects when using RemoteObject components.

You can use the [RemoteClass] metadata tag without an alias if you do not map to a Java object on the server, but you do send back your object type from the server. Your ActionScript object is serialized to a Map object when it is sent to the server, but the object returned from the server to the clients is your original ActionScript type.

1. write a bindable class and attach the [RemoteClass] tag.
2. use this class in your main flex code.

sample code:
blazeds-rc-server-tutorial.rar and blazeds-rc-client-tutorial.rar , enjoy it.

Monday, November 17, 2008

Integrated BlazeDS with Spring Framework

Spring is one of the most popular Java frameworks. The foundation of the Spring framework is a lightweight component container that implements the Inversion of Control (IoC) pattern.
Using an IoC container, components don't instantiate or even look up their dependencies (the objects they work with). The container is responsible for injecting those dependencies when it creates the components (hence the term "Dependency Injection" also used to describe this pattern).
The result is looser coupling between components. The Spring IoC container has proven to be a solid foundation for building robust enterprise applications. The components managed by the Spring IoC container are called Spring beans.

step by step:

1. Follow this article to create a basic blazeds-based java project.
2. Download spring framework and put the spring.jar into the blazeds-based java project.
3. Download flex-spring.zip and unzip it and put the SpringFactory.java to your source code folder. don't fotget to adjust the package name according to your package path.
4. Register the Spring factory on your services-config.xml.
5. Create applicationContext.xml in /WEB-INF and register Spring beans.
6. Update your remoting-config.xml.
7. Update your web.xml.
8. Create your flex app and new remoteObject to call java module.

For another new way to integrate spring to blazeds, pls go to Using Spring BlazeDS Integration 1.0.0.M1 .

sample code:
blazeds-spring-server-tutorial.rar and blazeds-spring-client-tutorial.rar , enjoy it.

Sunday, November 9, 2008

Build a Java-Flex Application Based on BlazeDS

BlazeDS is the server-based Java remoting and web messaging technology that enables developers to easily connect to back-end distributed data and push data in real-time to Adobe® Flex® and Adobe AIR™ applications for more responsive rich Internet application (RIA) experiences.

Follow these steps to get started with BlazeDS:

1. Ensure any necessary software and configuration item work properly on your computer. For instance, jdk, a java application server( tomcat, jboss, weblogic... ) that BlazeDS support.
2. Download and save BlazeDS to your computer.
3. Create a new web-project in eclipse.
3. Unzip balzeds.war, and copy folder /WEB-INF to your /WEB-INF folder.
4. Create a balzeds remote call interface file, I create and name it WeatherService.
5. Edit remoteing-config.xml, add your destination item.
6. Create your flex application, and new a remoteObject to call java function above.

sample code:
blazeds-client-tutorial.rar and blazeds-server-tutorial.rar , enjoy it.