Showing posts with label java. Show all posts
Showing posts with label java. Show all posts

Thursday, April 2, 2009

Unit Testing Sample with Spring and JUnit Annotations

package test.com.one.dao.impl;

import java.util.Calendar;
import java.util.Date;
import java.util.List;

import junit.framework.Assert;

import org.junit.After;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.AbstractTransactionalJUnit4SpringContextTests;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import com.one.dao.CustomerDAO;
import com.one.model.Customer;

@ContextConfiguration(locations={"/applicationContext.xml"})
@RunWith(SpringJUnit4ClassRunner.class)
public class CustomerDAOHibernateImplTests extends AbstractTransactionalJUnit4SpringContextTests{

@Autowired
private CustomerDAO customerDAO;

@Before
public void setup(){

}

@After
public void clean(){

}

@Test
public void testCRUD(){
Customer customer = new Customer();
customer.setCustomerFirstName("firstName");
customer.setCustomerLastName("lastName");
customer.setEmailAddr("email");
customer.setCreatedOn(new Date());
customer.setUpdatedOn(new Date());
customerDAO.saveOrUpdateCustomer(customer);
Assert.assertNotNull(customer.getCustomerId());
Assert.assertTrue(customer.getCustomerId().intValue() > 0);
customer = (Customer) customerDAO.getCustomerByCustomerId(customer.getCustomerId());
Assert.assertNotNull(customer);
Assert.assertEquals(customer.getCustomerFirstName(), "firstName");
Assert.assertEquals(customer.getCustomerLastName(), "lastName");
Assert.assertEquals(customer.getEmailAddr(), "email");
customerDAO.deleteCustomer(customer);
customer = (Customer) customerDAO.getCustomerByCustomerId(customer.getCustomerId());
Assert.assertNull(customer);
}

@Test
public void testGetCustomersByDateRange(){
Customer customer = new Customer();
customer.setCustomerFirstName("firstName");
customer.setCustomerLastName("lastName");
customer.setEmailAddr("email");
customer.setCreatedOn(new Date());
customer.setUpdatedOn(new Date());
customerDAO.saveOrUpdateCustomer(customer);
Assert.assertNotNull(customer.getCustomerId());
Assert.assertTrue(customer.getCustomerId().intValue() > 0);
Calendar c = Calendar.getInstance();
c.add(Calendar.DAY_OF_YEAR, -1);
Date from = c.getTime();
c.add(Calendar.DAY_OF_YEAR, +2);
Date to = c.getTime();
List list = customerDAO.getCustomersByDateRange(from, to);
Assert.assertNotNull(list);
Assert.assertTrue(list.size() > 0);
}

@Ignore
public void testGetCustomerByFirstnameAndLastnameAndEmail(){
Customer customer = new Customer();
customer.setCustomerFirstName("firstName");
customer.setCustomerLastName("lastName");
customer.setEmailAddr("email");
customer.setCreatedOn(new Date());
customer.setUpdatedOn(new Date());
customerDAO.saveOrUpdateCustomer(customer);
Assert.assertNotNull(customer.getCustomerId());
Assert.assertTrue(customer.getCustomerId().intValue() > 0);
customer = (Customer) customerDAO.getCustomerByFirstnameAndLastnameAndEmail("firstName", "lastName", "email");
Assert.assertNotNull(customer);
Assert.assertEquals(customer.getCustomerFirstName(), "firstName");
Assert.assertEquals(customer.getCustomerLastName(), "lastName");
Assert.assertEquals(customer.getEmailAddr(), "email");
}

}

Sunday, March 22, 2009

Best Practices for Exception Handling and Logging

The Nature of Exceptions
Broadly speaking, there are three different situations that cause exceptions to be thrown:
Exceptions due to programming errors: In this category, exceptions are generated due to programming errors (e.g., NullPointerException and IllegalArgumentException). The client code usually cannot do anything about programming errors.
Exceptions due to client code errors: Client code attempts something not allowed by the API, and thereby violates its contract. The client can take some alternative course of action, if there is useful information provided in the exception. For example: an exception is thrown while parsing an XML document that is not well-formed. The exception contains useful information about the location in the XML document that causes the problem. The client can use this information to take recovery steps.
Exceptions due to resource failures: Exceptions that get generated when resources fail. For example: the system runs out of memory or a network connection fails. The client's response to resource failures is context-driven. The client can retry the operation after some time or just log the resource failure and bring the application to a halt.
Best Practices for Exception Handling
1. When deciding on checked exceptions vs. unchecked exceptions, ask yourself, "What action can the client code take when the exception occurs?"
If the client can take some alternate action to recover from the exception, make it a checked exception. If the client cannot do anything useful, then make the exception unchecked. By useful, I mean taking steps to recover from the exception and not just logging the exception.
Moreover, prefer unchecked exceptions for all programming errors: unchecked exceptions have the benefit of not forcing the client API to explicitly deal with them. They propagate to where you want to catch them, or they go all the way out and get reported. The Java API has many unchecked exceptions, such as NullPointerException, IllegalArgumentException, and IllegalStateException. I prefer working with standard exceptions provided in Java rather than creating my own. They make my code easy to understand and avoid increasing the memory footprint of code.
2. Preserve encapsulation.
Never let implementation-specific checked exceptions escalate to the higher layers. For example, do not propagate SQLException from data access code to the business objects layer. Business objects layer do not need to know about SQLException. You have two options:
1) Convert SQLException into another checked exception, if the client code is expected to recuperate from the exception.
2) Convert SQLException into an unchecked exception, if the client code cannot do anything about it.
3. Try not to create new custom exceptions if they do not have useful information for client code.
4. Do not use your base exception class for "unkown" exception cases.
actually a follow-up from the first advice above. If you model your own exception hierarchy, you will typically have an exception base class (eg. MyAPIException) and several specific ones that inherit from that one (eg. MyAPIPathNotFoundException). Now it is tempting to throw the base exception class whenever you don't really know what else to throw, because the error case is not clear or very seldom. It's probably a Fault and thus you would start mixing it with your Contingency exception class hierarchy, which is obviously a bad thing.
One of the advantages of an exception base class is that the client has the choice to catch the base class if he does not want to handle the specific cases (although that's probably not the most robust code). But if that exception is also thrown in faulty situations, the client can no longer make a distinction between one-of-those-contingency-cases and all-those-unexcpected-fault-cases. And it obviously brakes your explicit exception design: there are those specific error cases you state and let the client know about, but then there is this generic exception thrown where the client cannot know what it means and is not able to handle it as a consequence.
5. When wrapping or logging exceptions, add your specific data to the message.
6. Don't throw exceptions in methods that are likely to be used for the exception handling itself.
This follows straight from the two previous advices: if you throw or log exceptions, you are typically in exception handling code, because you wrap a lower-level exception. If you add dynamic data to your exceptions, you might access methods from the underlying API. But if those methods throw exceptions, your code becomes ugly.
7. Document exceptions.

Best Practices for Using Exceptions
1. Always clean up after yourself
If you are using resources like database connections or network connections, make sure you clean them up. If the API you are invoking uses only unchecked exceptions, you should still clean up resources after use, with try - finally blocks.
2. Never use exceptions for flow control
Generating stack traces is expensive and the value of a stack trace is in debugging. In a flow-control situation, the stack trace would be ignored, since the client just wants to know how to proceed.
3. Do not suppress or ignore exceptions
When a method from an API throws a checked exception, it is trying to tell you that you should take some counter action. If the checked exception does not make sense to you, do not hesitate to convert it into an unchecked exception and throw it again, but do not ignore it by catching it with {} and then continue as if nothing had happened.
4. Do not catch top-level exceptions
5. Log exceptions just once
Logging the same exception stack trace more than once can confuse the programmer examining the stack trace about the original source of exception. So just log it once.

Logging
When your code encounters an exception, it must either handle it, let it bubble up, wrap it, or log it. If your code can programmatically handle an exception (e.g., retry in the case of a network failure), then it should. If it can't, it should generally either let it bubble up (for unchecked exceptions) or wrap it (for checked exceptions). However, it is ultimately going to be someone's responsibility to log the fact that this exception occurred if nobody in the calling stack was able to handle it programmatically. This code should typically live as high in the execution stack as it can. Some examples are the onMessage() method of an MDB, and the main() method of a class. Once you catch the exception, you should log it appropriately.
The JDK has a java.util.logging package built in, although the Log4j project from Apache continues to be a commonly-used alternative. Apache also offers the Commons Logging project, which acts as a thin layer that allows you to swap out different logging implementations underneath in a pluggable fashion. All of these logging frameworks that I've mentioned have basically equivalent levels:
1) FATAL: Should be used in extreme cases, where immediate attention is needed. This level can be useful to trigger a support engineer's pager.
2) ERROR: Indicates a bug, or a general error condition, but not necessarily one that brings the system to a halt. This level can be useful to trigger email to an alerts list, where it can be filed as a bug by a support engineer.
3) WARN: Not necessarily a bug, but something someone will probably want to know about. If someone is reading a log file, they will typically want to see any warnings that arise.
4) INFO: Used for basic, high-level diagnostic information. Most often good to stick immediately before and after relatively long-running sections of code to answer the question "What is the app doing?" Messages at this level should avoid being very chatty.
5) DEBUG: Used for low-level debugging assistance.
If you are using commons-logging or Log4j, watch out for a common gotcha. The error, warn, info, and debug methods are overloaded with one version that takes only a message parameter, and one that also takes a Throwable as the second parameter. Make sure that if you are trying to log the fact that an exception was thrown, you pass both a message and the exception. If you call the version that accepts a single parameter, and pass it the exception, it hides the stack trace of the exception.
When calling log.debug(), it's good practice to always surround the call with a check for log.isDebugEnabled(). This is purely for optimization. It's simply a good habit to get into, and once you do it for a few days, it will just become automatic.
Do not use System.out or System.err. You should always use a logger. Loggers are extremely configurable and flexible, and each appender can decide which level of severity it wants to report/act on, on a package-by-package basis. Printing a message to System.out is just sloppy and generally unforgivable.

Thanks for these following articles:
Best Practices for Exception Handling
Exception Handling Best Practices Part 1
Exception Handling Best Practices Part 2: Control flow in data oriented APIs
Exception Handling Best Practices Part 3
Exception-Handling Antipatterns
Effective Java Exceptions
Three Rules for Effective Exception Handling

Friday, February 27, 2009

Sample of Java Pattern -- Proxy

Order.java
package proxy;

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

public class Order implements Serializable {

private int orderId;
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 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;
}
}

OrderDAO.java
package proxy;

import java.util.List;

public interface OrderDAO {
public List<Order> getAllOrders();
}


OrderDAOImpl.java
package proxy;

import java.util.ArrayList;
import java.util.List;

public class OrderDAOImpl implements OrderDAO{
public List<Order> getAllOrders(){
List<Order> list = new ArrayList<Order>();
for(int i =0; i<10; i++){
Order order = new Order();
order.setSku("sku"+i);
list.add(order);
}
return list;
}
}


OrderDAOProxy.java
package proxy;

import java.util.List;

public class OrderDAOProxy implements OrderDAO{
public List<Order> getAllOrders(){
long stTime = System.currentTimeMillis();
OrderDAO orderDAOImpl = new OrderDAOImpl();
List<Order> list = orderDAOImpl.getAllOrders();
long endTime = System.currentTimeMillis();
System.out.println("took " + (endTime - stTime) + " milliseconds.");
return list;
}
}


ProxyTest.java
package proxy;

public class ProxyTest {

public static void main(String[] args) {
OrderDAO orderDAOProxy = new OrderDAOProxy();
orderDAOProxy.getAllOrders();
}

}


you may download the source code.

Saturday, February 21, 2009

Sample of Java Pattern -- State

OrderState.java
package state;

public interface OrderState {
public void handleOrder(String orderNo);
public void cancelOrder(String orderNo);
public void completeOrder(String orderNo);
}



OrderOpendState.java
package state;

public class OrderOpendState implements OrderState {

OrderStateMgmt orderStateMgmt;

public OrderOpendState(OrderStateMgmt orderStateMgmt){
this.orderStateMgmt = orderStateMgmt;
}

public void handleOrder(String orderNo){
System.out.println("handle this order, orderNo=" + orderNo);
orderStateMgmt.setState(orderStateMgmt.getOrderInProgressState());
}

public void cancelOrder(String orderNo){
System.out.println("cancel this order, orderNo=" + orderNo);
orderStateMgmt.setState(orderStateMgmt.getOrderCancelledState());
}

public void completeOrder(String orderNo){
System.out.println("could not complete this order under opend status, orderNo=" + orderNo);
}
}



OrderInProgressState.java
package state;

public class OrderInProgressState implements OrderState {

OrderStateMgmt orderStateMgmt;

public OrderInProgressState(OrderStateMgmt orderStateMgmt){
this.orderStateMgmt = orderStateMgmt;
}

public void handleOrder(String orderNo){
System.out.println("could not handle this order under in progress status, orderNo=" + orderNo);
}

public void cancelOrder(String orderNo){
System.out.println("cancel this order, orderNo=" + orderNo);
orderStateMgmt.setState(orderStateMgmt.getOrderCancelledState());
}

public void completeOrder(String orderNo){
System.out.println("complete this order, orderNo=" + orderNo);
orderStateMgmt.setState(orderStateMgmt.getOrderClosedState());
}
}



OrderCancelledState.java
package state;

public class OrderCancelledState implements OrderState {

OrderStateMgmt orderStateMgmt;

public OrderCancelledState(OrderStateMgmt orderStateMgmt){
this.orderStateMgmt = orderStateMgmt;
}

public void handleOrder(String orderNo){
System.out.println("could not handle this order under cancelled status, orderNo=" + orderNo);
}

public void cancelOrder(String orderNo){
System.out.println("could not cancel this order under cancelled status, orderNo=" + orderNo);
}

public void completeOrder(String orderNo){
System.out.println("could not complete this order under cancelled status, orderNo=" + orderNo);
}
}



OrderClosedState.java
package state;

public class OrderClosedState implements OrderState {

OrderStateMgmt orderStateMgmt;

public OrderClosedState(OrderStateMgmt orderStateMgmt){
this.orderStateMgmt = orderStateMgmt;
}

public void handleOrder(String orderNo){
System.out.println("could not handle this order under closed status, orderNo=" + orderNo);
}

public void cancelOrder(String orderNo){
System.out.println("could not cancel this order under closed status, orderNo=" + orderNo);
}

public void completeOrder(String orderNo){
System.out.println("could not complete this order under closed status, orderNo=" + orderNo);
}
}



OrderStateMgmt.java
package state;

public class OrderStateMgmt {

private OrderOpendState orderOpendState;
private OrderInProgressState orderInProgressState;
private OrderCancelledState orderCancelledState;
private OrderClosedState orderClosedState;

private OrderState orderState;

public OrderStateMgmt(){
this.orderOpendState = new OrderOpendState(this);
this.orderInProgressState = new OrderInProgressState(this);
this.orderCancelledState = new OrderCancelledState(this);
this.orderClosedState = new OrderClosedState(this);
this.orderState = this.orderOpendState;
System.out.println("The order inital status is: opend.");
}

public void setState(OrderState orderState){
this.orderState = orderState;
}

public OrderOpendState getOrderOpendState() {
return orderOpendState;
}

public OrderInProgressState getOrderInProgressState() {
return orderInProgressState;
}

public OrderCancelledState getOrderCancelledState() {
return orderCancelledState;
}

public OrderClosedState getOrderClosedState() {
return orderClosedState;
}

public void handleOrder(String orderNo){
orderState.handleOrder(orderNo);
}

public void cancelOrder(String orderNo){
orderState.cancelOrder(orderNo);
}

public void completeOrder(String orderNo){
orderState.completeOrder(orderNo);
}
}



OrderStateTest.java
package state;

public class OrderStateTest {

public static void main(String[] args) {
OrderStateMgmt orderStateMgmtA = new OrderStateMgmt();

orderStateMgmtA.handleOrder("01");
orderStateMgmtA.completeOrder("01");

OrderStateMgmt orderStateMgmtB = new OrderStateMgmt();

orderStateMgmtB.handleOrder("02");
orderStateMgmtB.cancelOrder("02");

OrderStateMgmt orderStateMgmtC = new OrderStateMgmt();

orderStateMgmtC.completeOrder("03");
}

}



you may download the source code.

Friday, February 13, 2009

Sample of Java Pattern -- Composite

Department.java
package composite;

import java.util.List;

public interface Department {
public Department getDepartment();
public String getDepartmentname();
public void add(Department department);
public void remove(Department department);
public boolean hasSubDepartments();
public List<Department> getSubDepartments();
}


CompositeDepartment.java
package composite;

import java.util.ArrayList;
import java.util.List;

public class CompositeDepartment implements Department {
private String name;
private List<Department> departments = new ArrayList<Department>();

public CompositeDepartment(String name) {
super();
System.out.println("Department " + name + " is created.");
this.name = name;
}

public Department getDepartment() {
return this;
}

public String getDepartmentname() {
return this.name;
}

public void add(Department department){
System.out.println("Department " + department.getDepartmentname() + " is added to Department " + this.name + ".");
departments.add(department);
}

public void remove(Department department){
System.out.println("Department " + department.getDepartmentname() + " is removed from Department " + this.name + ".");
departments.remove(department);
}

public boolean hasSubDepartments(){
if(departments == null || departments.isEmpty())
return false;
return true;
}

public List<Department> getSubDepartments(){
if(hasSubDepartments())
return departments;
return null;
}
}


SingleDepartment.java
package composite;

import java.util.List;

public class SingleDepartment implements Department {
private String name;

public SingleDepartment(String name) {
super();
System.out.println("Department " + name + " is created.");
this.name = name;
}

public Department getDepartment() {
return this;
}

public String getDepartmentname() {
return this.name;
}

public void add(Department department){
System.out.println("Could not add a child department in Department " + this.name + ".");
}

public void remove(Department department){
System.out.println("Department " + department.getDepartmentname() + " doesn't belong to Department " + this.name + ".");
}

public boolean hasSubDepartments(){
return false;
}

public List<Department> getSubDepartments(){
return null;
}
}


CompositeTest.java
package composite;

public class CompositeTest {
public static void main(String[] args) {
Department hq = new CompositeDepartment("HQ");
Department financing = new SingleDepartment("Financing");
Department marketing = new CompositeDepartment("Marketing");
Department preSales = new SingleDepartment("PreSales");
Department sales = new SingleDepartment("Sales");
Department postSales = new SingleDepartment("PostSales");
Department techSupport = new SingleDepartment("TechSupport");
hq.add(financing);
hq.add(marketing);
hq.add(techSupport);
marketing.add(preSales);
marketing.add(sales);
marketing.add(postSales);
System.out.println("hq has sub departments: " + hq.hasSubDepartments());
System.out.println("marketing has sub departments: " + marketing.hasSubDepartments());
System.out.println("techSupport has sub departments: " + techSupport.hasSubDepartments());
marketing.remove(preSales);
marketing.remove(sales);
marketing.remove(postSales);
sales.remove(preSales);
hq.remove(financing);
hq.remove(marketing);
hq.remove(techSupport);
}
}


you may download the source code.

Saturday, February 7, 2009

Sample of Java Pattern -- Iterator

Aggregate.java
package iterator;

public interface Aggregate {
public abstract Iterator iterator();
}


Iterator.java
package iterator;

public interface Iterator {
public abstract boolean hasNext();
public abstract Object next();
}


Order.java
package iterator;

import java.util.Date;

public class Order {
private String name;
private Date createdOn = new Date();
private Date updatedOn = new Date();

public Order(String name) {
super();
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
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;
}
}


Orders.java
package iterator;

import java.util.Date;

public class Orders implements Aggregate{
private Order[] orders;
private int last = 0;

public Orders(int max){
this.orders = new Order[max];
}

public Order getOrderAt(int index){
return this.orders[index];
}

public void appendOrder(Order order){
this.orders[last] = order;
this.last ++ ;
}

public int getLength(){
return orders.length;
}

public Iterator iterator() {
return new OrdersIterator(this);
}
}


OrdersIterator.java
package iterator;

public class OrdersIterator implements Iterator{
private Orders orders;
private int index;

public OrdersIterator(Orders orders) {
this.orders = orders;
this.index = 0;
}

public boolean hasNext(){
if(index < orders.getLength()){
return true;
}else{
return false;
}
}

public Order next(){
Order order = orders.getOrderAt(this.index);
this.index ++ ;
return order;
}
}


IteratorTest.java
package iterator;

public class IteratorTest {

public static void main(String[] args) {
Orders orders = new Orders(3);
orders.appendOrder(new Order("order1"));
orders.appendOrder(new Order("order2"));
orders.appendOrder(new Order("order3"));
Iterator iterator = orders.iterator();
while(iterator.hasNext()) {
Order order = (Order)iterator.next();
System.out.println(order.getName());
}
}

}


you may download the source code.

Friday, January 30, 2009

Sample of Java Pattern -- Template Method

EmailTemplate.java
package templatemethod;

import javax.mail.*;
import javax.mail.internet.*;

public abstract class EmailTemplate {
public void send(String smtpHostName, String smtpPort, String smtpAuthUser, String smtpAuthPwd, String[] recipients, String subject,String message, String from){
MimeMessage msg = connect(smtpHostName, smtpPort, smtpAuthUser, smtpAuthPwd);
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) {
System.out.println("Could not send this email, title=" + subject + " addressTo=" + recipients[0] + ", please check the email server connection.");
}
}

protected abstract MimeMessage connect(String smtpHostName, String smtpPort, String smtpAuthUser, String smtpAuthPwd);
}


GeneralEmailService.java
package templatemethod;

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

import javax.mail.Authenticator;
import javax.mail.Session;
import javax.mail.internet.MimeMessage;

import templatemethod.GoogleEmailService.SMTPAuthenticator;

public class GeneralEmailService extends EmailTemplate{
private String smtpAuthUser;
private String smtpAuthPwd;
protected MimeMessage connect(String smtpHostName, String smtpPort, String smtpAuthUser, String smtpAuthPwd){

this.smtpAuthUser = smtpAuthUser;
this.smtpAuthPwd = smtpAuthPwd;

boolean debug = false;

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

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

session.setDebug(debug);

MimeMessage msg = new MimeMessage(session);

return msg;

}

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


}


GoogleEmailService.java
package templatemethod;

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

import javax.mail.Authenticator;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.internet.MimeMessage;

public class GoogleEmailService extends EmailTemplate{
private String smtpAuthUser;
private String smtpAuthPwd;
protected MimeMessage connect(String smtpHostName, String smtpPort, String smtpAuthUser, String smtpAuthPwd){

this.smtpAuthUser = smtpAuthUser;
this.smtpAuthPwd = smtpAuthPwd;

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", smtpHostName);
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.port", smtpPort);
props.setProperty("mail.smtp.quitwait", "false");

props.put("mail.smtp.socketFactory.port", smtpPort);
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);

return msg;

}

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

}


TemplateMethodTest.java
package templatemethod;

public class TemplateMethodTest {

public static void main(String[] args) {
String smtpHostName = "";
String smtpPort = "";
String smtpAuthUser = "";
String smtpAuthPwd = "";
String[] recipients = {""};
String subject = "";
String message = "";
String from = "";
EmailTemplate googleEmailService = new GoogleEmailService();
googleEmailService.send(smtpHostName, smtpPort, smtpAuthUser, smtpAuthPwd, recipients, subject, message, from);
EmailTemplate generalEmailService = new GeneralEmailService();
generalEmailService.send(smtpHostName, smtpPort, smtpAuthUser, smtpAuthPwd, recipients, subject, message, from);
}

}


you may download the source code.

Saturday, January 24, 2009

Sample of Java Pattern -- Façade

Customer.java
package facade;

public class Customer {
private String name;
private String address;
private Order order;

public String getName() {
return name;
}

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

public String getAddress() {
return address;
}

public void setAddress(String address) {
this.address = address;
}

public Order getOrder() {
return order;
}

public void setOrder(Order order) {
this.order = order;
}

public void save(){

}

}


Order.java
package facade;

public class Order {
private String sku;

public String getSku() {
return sku;
}

public void setSku(String sku) {
this.sku = sku;
}

public void save(){

}
}


CustomerFacade.java
package facade;

public class CustomerFacade {
public void placeOrder(String customerName, String customerAddress, String sku){
Customer customer = new Customer();
customer.setName(customerName);
customer.setAddress(customerAddress);
Order order = new Order();
order.setSku(sku);
customer.setOrder(order);
customer.save();
order.save();
}
}


FacadeTest.java
package facade;

public class FacadeTest {

public static void main(String[] args) {
CustomerFacade customerFacade = new CustomerFacade();
customerFacade.placeOrder("customerName", "customerAddress", "sku");
}

}


you may download the source code.

Friday, January 16, 2009

Sample of Java Pattern -- Adapter

LegacyModel.java
package adapter;

public class LegacyModel {
public void ins(String sku){
System.out.println("call ins method.");
}
}


ModernModel.java
package adapter;

public interface ModernModel {
public void save(Order order);
}


ModernModelAdapter.java
package adapter;

public class ModernModelAdapter implements ModernModel{
private LegacyModel legacyModel;

public ModernModelAdapter(LegacyModel legacyModel) {
super();
this.legacyModel = legacyModel;
}

public void save(Order order){
String sku = order.getSku();
legacyModel = new LegacyModel();
legacyModel.ins(sku);
}
}


Order.java
package adapter;

public class Order {
private String sku;

public String getSku() {
return sku;
}

public void setSku(String sku) {
this.sku = sku;
}

}


AdapterTest.java
package adapter;

public class AdapterTest {
public static void main(String[] args) {
LegacyModel legacy = new LegacyModel();
Order order = new Order();
order.setSku("sku");
ModernModelAdapter adapter = new ModernModelAdapter(legacy);
adapter.save(order);
}
}


you may download the source code.

Monday, January 12, 2009

Sample of Java Pattern -- Command

Command.java
package command;

public interface Command {
public void execute();
}


ConfirmCommand.java
package command;

public class ConfirmCommand implements Command {

private EmailService emailService;

public ConfirmCommand(){}

public void execute() {
emailService = new EmailService();
emailService.confirmMeeting();
}

}


CancelCommand.java
package command;

public class CancelCommand implements Command {

private EmailService emailService;

public CancelCommand(){}

public void execute() {
emailService = new EmailService();
emailService.cancelMeeting();
}

}


EmailService.java
package command;

public class EmailService {

public EmailService(){}

public void cancelMeeting(){
System.out.println("send cacellation email");
}

public void confirmMeeting(){
System.out.println("send confirmation email");
}

}


Invoker.java
package command;

public class Invoker {
private Command command;

public Invoker(){
}

public void setCommand(Command command){
this.command = command;
}

public void executeCommand(){
this.command.execute();
}
}


CommandTest.java
package command;

public class CommandTest {

public static void main(String[] args) {
CancelCommand cancelCommand = new CancelCommand();
ConfirmCommand confirmCommand = new ConfirmCommand();
Invoker invoker = new Invoker();
invoker.setCommand(confirmCommand);
invoker.executeCommand();
invoker.setCommand(cancelCommand);
invoker.executeCommand();
}

}
you can download the source code .

Monday, January 5, 2009

Sample of Java Pattern -- Singleton

Utils.java
package singleton;

public class Utils {

private Utils(){}

private static Utils instance = new Utils();

public static Utils getInstance() {
return instance;
}

public void println(String str){
System.out.println(str);
}

public static void main(String[] args) {
Utils.getInstance().println("Hello");
}
}


you may download the source code.

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.

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.