A good Example of Timer Thread

A

anonieko

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;
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();
}
}
 
O

Oliver Wong

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,768
Messages
2,569,574
Members
45,051
Latest member
CarleyMcCr

Latest Threads

Top