www.pudn.com > WAPpush.zip > Birthday.java


package push;

import java.util.Vector;
import java.util.Calendar;
import java.text.SimpleDateFormat;

/**
 * Birthday checker class. 
 *
 * @version 1.0
 * @since 1.0
 * @see Runnable
 */
public final class Birthday implements Runnable {

    private final PushInitiator pusher;
    private final String url;
    private static final String messageContent =  
	"We hear you're having a birthday soon! We would like to invite you to celebrate it in our zoo. " +
	"A refreshment is  on the house at the Safari restaurant.";
    private final String addressType;

    /**
     * Creates a new Birthday instance.
     *
     * @param pusher a PushInitiator value
     * @param url a String value
     * @param addressType a String value
     */
    public Birthday(PushInitiator pusher, String url, String addressType) {
	this.pusher = pusher;
	this.url = url;
	this.addressType = addressType;
    }

    /**
     *  A birthday checker thread sends push messages to users about approaching birthday. The message
     *  is sent 1 to 14 days before the birthday. 
     */
    public void run() {
	String message = PushInitiator.createSiMessage(url,  null, null, null, 
						       null, messageContent);
	while(true) {
	    try {
		Vector users = User.getUsersOnline();
		for(int i=0; i= 1 && days <= 14) {
			String address = user.getAddress(addressType);
			if(address != null && !address.trim().equals("")) {
			  
			    try {
				pusher.sendPushMessage(address, addressType, message, PushService.SI_CONTENT_TYPE);
			    } catch(Exception ee) {}
			    user.setProperty("birthdayNotified", new Long(System.currentTimeMillis()));
			}
		    }
		}
		
	    }
	    catch(Exception e) { System.err.println(e); }
	    try {
		Thread.sleep(60000); // 1 min
	    }
	    catch(InterruptedException e){}
	}
    }

    /**
     * Calculates the number of days to birthday on the basis of date of birth
     * given in format "yyyy.mm.dd"
     *
     * @param dob a String value
     * @return an int value
     */
    private static int numberOfDaysToBirthday(String dob) {
        SimpleDateFormat s = new SimpleDateFormat("yyyy.MM.dd");
        final long numberOfMillisecondsPerDay = 1000*60*60*24;
        try {
            java.util.Date d = s.parse(dob);
            Calendar c1 = Calendar.getInstance();
            c1.setTime(d);
            Calendar c2 = Calendar.getInstance();
            c1.set(Calendar.YEAR, c2.get(Calendar.YEAR));
            int d1 = c1.get(Calendar.DAY_OF_YEAR);
            int d2 = c2.get(Calendar.DAY_OF_YEAR); // current day
	    if(d2 > d1)  { // birthday next year
                c1.roll(Calendar.YEAR, true); // set next birthday
                d1 = c1.get(Calendar.DAY_OF_YEAR);
            }
            return (int)((c1.getTime().getTime() - c2.getTime().getTime())/numberOfMillisecondsPerDay);
        }
        catch(Exception e) { System.err.println(e); }
        return -1;
    }

}