Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
HomeAnnouncementsWhite Papers
Discussion GroupsFirst AidDatabasesJavaBeansGUIJava 3DVirtual MachineCORBASecurityToolsGeneral
Java DirectoryOpen Source ProjectsSample Book ChaptersUser GroupsWeb Resources
Related Topics
Databases.NETMore Topics ...

Java Forum / General / January 2006

Tip: Looking for answers? Try searching our database.

A good Example of  Timer Thread

Thread view: 
anonieko@hotmail.com - 23 Jan 2006 19:01 GMT
package xxx

import org.apache.log4j.Logger;

/*
*  This the main thread class for the polling pending email-xml files
ready to be
*  sent to siebel via webservice.  Designed to run throughout
application lifetime.
*  It periodically call FileHandler send() method.
*/
public class CSIClientTimer implements Runnable {

    public static Logger log =
Logger.getLogger(SetupServlet.class.getName());
    private static final int ONE_MINUTE            = 60000;
    private static final int DEFAULT_INTERVAL      = 2;
    private static int timeInterval                = 1;
    private static CSIClientTimer instance          = null;
    public  static Thread currentThread             = null;

    /*
    * Constructor will set time interval.
    */
    private CSIClientTimer() {
        setTimeInterval();
    }

    public static CSIClientTimer getInstance() {
        if (instance == null) {
            synchronized (CSIClientTimer.class) {
                if (instance == null) {
                    instance = new CSIClientTimer();
                }
            }
        }
        return instance;
    }

    /*
    * This method guarantees that a timer will be set (no matter what).
    */
    private void setTimeInterval() {
        try {
            String timeS =
                ServiceLocator.getInstance().getProperty("CLIENT_TIME_MIN");
            timeInterval = Integer.parseInt(timeS);
        } catch (Exception e) {
            log.warn( "["+ Thread.currentThread().getName()+"] Timer warning!!!
Invalid property setup. Using default." );
            timeInterval = DEFAULT_INTERVAL;
        } finally {
            log.info( "["+ Thread.currentThread().getName()+"] TIMER is set to
sleep for " + timeInterval + " minute(s)." );
        }
    }

    /*
    *  This kicks off the thread.  Calling again this method
    *  should not create additional threads.
    */
    public static void start() {
        try {
            if (currentThread == null) {
                currentThread = new Thread(CSIClientTimer.getInstance());
            }
            currentThread.start();
            log.info( "["+ Thread.currentThread().getName()+"] Started the
thread ->" + currentThread.getName());
        } catch (Exception e) {
            log.error(e.getMessage());
        }
    }

    public static void stop() {
        String tname = "null thread name";
        if (currentThread != null)
            tname = currentThread.getName();
        currentThread = null;
        log.info( "["+ Thread.currentThread().getName()+"] Stopping Thread
->" + tname);
    }

    public void run() {

        Thread thisThread = Thread.currentThread();
        try {
            while (thisThread == currentThread && currentThread != null) {
                FileHandler.Send();
                log.debug( "["+ Thread.currentThread().getName()+"] Sleeping for "
+ timeInterval + " minute(s)...");
                Thread.sleep(ONE_MINUTE * (timeInterval));
            }
        } catch (ThreadDeath e) {
            log.error(e.getMessage());
        } catch (InterruptedException e) {
            log.error(e.getMessage());
        } catch (Exception e) {
            log.error(e.getMessage());
        }
        log.info( "["+ Thread.currentThread().getName()+"] Terminating this
thread.");
    }
}

------------Supporting classes follows -----------------

package xxx;

import java.net.MalformedURLException;
import java.net.URL;
import java.util.Vector;

import org.apache.log4j.Logger;
import org.apache.soap.Constants;
import org.apache.soap.Fault;
import org.apache.soap.rpc.Call;
import org.apache.soap.rpc.Parameter;
import org.apache.soap.rpc.Response;

/*
*
* This class in charge of setup and actual call to ApacheSOAP
webservice.
*
*/
public class ServiceAgent {

    public static Logger log =
Logger.getLogger(SetupServlet.class.getName());
    private String _urn;
    private String _url;
    private String _svc;

    /*
    *  Constructor initializes Iplanet parameters from property files.
    */
    public ServiceAgent() {
        _url = ServiceLocator.getInstance().getProperty("IPLANET_WS_URL");
        _urn = ServiceLocator.getInstance().getProperty("IPLANET_WS_URN");
        _svc =
ServiceLocator.getInstance().getProperty("IPLANET_WS_SIEBEL_SERVICE");
    }

    /*
    *  Sends the email info as xml string to ApacheSOAP webservice.
    *  Returns string 'success' otherwise 'err_connect' or 'errxxxxxxx'
if error.
    */
    public String Send(String message) {
        String reply = "err_unknown";

        try {
            URL url = new URL(_url);
            Call call = new Call();
            call.setTargetObjectURI(_urn);
            call.setMethodName(_svc);
            call.setEncodingStyleURI(Constants.NS_URI_SOAP_ENC);
            Vector params = new Vector();
            params.addElement(
                new Parameter("message", String.class, message, null));
            call.setParams(params);
            Response rep = call.invoke(url, "");

            if (rep.generatedFault()) {
                Fault fault = rep.getFault();
                reply = "err_fault";
            } else {
                Parameter result = rep.getReturnValue();
                String res = result.getValue().toString().toLowerCase().trim();
                if (res.equalsIgnoreCase("success"))
                    reply = "success";
                else
                    reply = "err [" + res + "]";
            }

        } catch (MalformedURLException e) {
            log.info("URL error: "+e.getMessage());
            return e.getMessage();
        } catch (Exception e) {
            if (e.toString().indexOf("java.net.ConnectException") >= 0
                || e.toString().indexOf("java.net.SocketException") >= 0) {
                log.info("Either box or Web Server is down: "+e.getMessage());
                return e.getMessage();
            }
            log.info("UNDEFINED exception: "+e.getMessage());
            return e.getMessage();
        }
        return reply;
    }
}

package com.tta.ua.util;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;

import org.apache.log4j.Logger;

public class FileHandler {
    public static Logger log =
Logger.getLogger(SetupServlet.class.getName());
    /*
    * Sends the xml files in backup dir to siebel.  On success, files are
deleted.
    * Only files matching the configured 'prefix' will be processed.
    */
    synchronized public static void Send() {
        try {
            ServiceAgent mailWsAgent = new ServiceAgent();
            String dir =
                ServiceLocator.getInstance().getProperty("BACKUP_DIRECTORY");
            String prefix =
                ServiceLocator.getInstance().getProperty("FILENAME_PREFIX");
            if (dir == null)
                throw new Exception("BACKUP_DIRECTORY propery not found!");
            if (prefix == null)
                throw new Exception("FILENAME_PREFIX propery not found!");
            File backupDir = new File(dir);
            if (!backupDir.isDirectory())
                throw new Exception("[" + dir + "] is invalid!");
            File[] files = backupDir.listFiles();
            log.debug("["+ Thread.currentThread().getName()+"] Processing files
in dir: "+dir);
            for (int i = 0; i < files.length; i++) {
                File nextFile = files[i];
                if (nextFile.isFile()
                    && nextFile.canRead()
                    &&
nextFile.getName().toLowerCase().startsWith(prefix.toLowerCase())) {
                    String contents = getContents(nextFile);
                    String results = mailWsAgent.Send(contents);
                    log.info("["+ Thread.currentThread().getName()+"] WS call
returned=[" + results + "] after sending " + nextFile.getName());
                    if (results.equalsIgnoreCase("err_connect")) {
                        break;
                    } else if (results.equalsIgnoreCase("success")) {
                        if (!nextFile.delete()) {
                            log.error("["+ Thread.currentThread().getName()+"] !!!Warning!!!
Unable to delete "
                                    + nextFile.getName());
                        } else
                        log.info("["+ Thread.currentThread().getName()+"] File = "
                                    + nextFile.getName()
                                    + " resent ok & deleted.");
                    }
                }
            }
        } catch (Exception e) {
            log.error("ERROR = " + e.getMessage());
        }
    }

    /*
    *  Read a file into a string (omitting line separator due to
ApacheSOAP requirement).
    */
    private static String getContents(File aFile) {
        StringBuffer contents = new StringBuffer();
        BufferedReader input = null;
        try {
            input = new BufferedReader(new FileReader(aFile));
            String line = null;
            while ((line = input.readLine()) != null) {
                contents.append(line);
                //contents.append(System.getProperty("line.separator"));
            }
        } catch (Exception ex) {
            log.error("["+
Thread.currentThread().getName()+"]"+ex.getMessage());
        } finally {
            try {
                if (input != null)
                    input.close();
            } catch (Exception ex) {
                log.error("["+ Thread.currentThread().getName()+"] err closing
file:" + ex);
            }
        }
        return contents.toString();
    }
}
Oliver Wong - 23 Jan 2006 19:15 GMT
> package xxx

[rest of the code snipped]

"xxx" is an actual TLD that is currently in use. So unless you own that TLD
(and I suspect that you don't), you probably should not be using "xxx" as
your package name, as it collide with java programs written by the people
who DO own that domain.

   - Oliver


Free Magazines

Get these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...

Oracle MagazineNetwork ComputingComputer WorldBio-IT WorldeWeekInformation WeekInfosecurity
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2009 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.