Sunday 8 June 2014

Examples of EJB 3.1 TimerService - Programmatic Timers

A programmatic timer is typically required when there is a user interface that controls the scheduling activity.
User would be able to start or stop a scheduler which do certain processing using the specified timer schedule. Here is a simple example of a programmatic EJB Timer.

In this example, it is assumed that the application have a SessionBean facade(s) which have all the business methods. A SessionBean facade is required for making use of the container managed persistence context in the business methods. The timer just invokes the relevant business method based on the timer schedule expiration.

package com.prasune.ejb.timer;

import java.util.Date;

import javax.annotation.Resource;
import javax.ejb.EJB;
import javax.ejb.ScheduleExpression;
import javax.ejb.Stateless;
import javax.ejb.Timeout;
import javax.ejb.Timer;
import javax.ejb.TimerConfig;
import javax.ejb.TimerService;

import com.prasune.ejb.persistence.JPASessionFacade;

@Stateless(name = "ProgramaticTimer", mappedName = "ProgramaticTimer")
public class ProgramaticTimerBean implements ProgramaticTimer {
   
    @Resource
    TimerService timerService;
   
    @EJB
    private JPASessionFacade jpaSessionFacade;

    public ProgramaticTimerBean() {
    }

    @Timeout
    public void doProcess(Timer timer) {
        System.out.println("Programatic Timer got invoked at " + new Date());
        jpaSessionFacade.dmlOperation();
    }
   
    public void startScheduler(){
        ScheduleExpression scheduleExpression = new ScheduleExpression();
        scheduleExpression.hour("*").minute("*").second("*/5");
        timerService.createCalendarTimer(scheduleExpression, new TimerConfig("TestTimer", true));
        System.out.println("Programatic Timer got created succesfully");
    }
   
    public void stopScheduler(String schedulerId) {
        if (timerService.getTimers() != null) {
            for (Timer timer : timerService.getTimers()) {
                if (timer.getInfo().equals(schedulerId)) {
                    timer.cancel();
                    System.out.println("Programatic Timer got stopped succesfully");
                }
            }
        }
    }
}


startScheduler() method creates a timer using the calendar based ejb ScheduleExpression.
The ScheduleExpression is very similar to chrone job schedule expression. Detailed usage of the ScheduleExpression for creating a timer can be found at Understanding EJB Timer Service 3.1.
In the example, we are creating a timer schedule to be executed every 5 seconds from now.

TimerConfig: There is an optional TimerConfig that can be passed while creating the calendar based timer. In the TimerConfig, we can specify an info like an Id using which we can identify the Timer. The Timer needs to be identified for stopping it as and when the user requires to do the same.The second parameter of the TimerConfig decides whether the Timer Schedule needs to be persisted or not. This is by default true and it means that the schedule of the timer is persisted and is not specific to JVM. Hence, it can survive a server crash.

@Resource annotation is used by the JEE server to inject the TimerService to the EJB.

@Timeout annotation is used to mark the method to be executed on timer schedule expiration. A programmatic Timer can have only one method with this annotation per EJB. The doProcess() method executes the relevant business method specified from the SessionBean facade.

@EJB annotation is used by the JEE server for injecting the SessionBean facade for calling the relevant business method.

stopScheduler() method fetches the Timers registered with TimerService and uses the TimerConfig info to identify the relevant timer and stops it.


ProgramaticTimer is the Local and Remote interface of the EJB. Although it is not mandatory to have a separate interface and the EJB can be annotated with Local/Remote annotations, it is better to program to interface. This will help while multiple applications are involved as the integrator needs to be given only the interface. 

package com.prasune.ejb.timer;

import javax.ejb.Local;
import javax.ejb.Remote;

@Local
@Remote
public interface ProgramaticTimer {
    public void startScheduler();
    public void stopScheduler(String schedulerId);
}


ProgramaticTimerRemoteClient is a sample remote client for invoking the timer application to see if it is working fine. The example client uses Weblogic server initial context. The ProgramaticTimerBean APIs can be called for starting/stopping the scheduler and to verify whether it is working fine.

package com.prasune.ejb.timer.client;

import com.prasune.ejb.timer.ProgramaticTimer;

import java.util.Hashtable;

import javax.naming.CommunicationException;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;

public class ProgramaticTimerRemoteClient {
    public static void main(String[] args) {
        try {
            final Context context = getInitialContext();
            ProgramaticTimer programaticTimer =
                (ProgramaticTimer) context.lookup("ProgramaticTimer#com.prasune.ejb.timer.ProgramaticTimer");
            programaticTimer.startScheduler();
            //programaticTimer.stopScheduler("TestTimer");
            System.out.println("Invoked Timer");
        } catch (CommunicationException ex) {
            System.out.println(ex.getClass().getName());
            System.out.println(ex.getRootCause().getLocalizedMessage());
            System.out.println("\n*** A CommunicationException was raised.  This typically\n*** occurs when the target WebLogic server is not running.\n");
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    private static Context getInitialContext() throws NamingException {
        Hashtable env = new Hashtable();
        // WebLogic Server 10.x/12.x connection details
        env.put(Context.INITIAL_CONTEXT_FACTORY, "weblogic.jndi.WLInitialContextFactory");
        env.put(Context.PROVIDER_URL, "t3://127.0.0.1:7101");
        return new InitialContext(env);
    }
}


Packaging and Deployment

Packaging and deployment of an EJB 3.1 Timer is very simple. The class file needs to be in a jar file with the correct directory structure of the package and the jar file can be directly deployed on any JEE server supporting EJB 3.1. The vendor specific ejb-jar.xml are optional and annotations are sufficient for the JEE server to identify the class as EJB Timer

Examples of EJB 3.1 TimerService - Automatic Timers


An automatic timer typically suits for doing either an end of day kind of processing or for a purging activity.
Here is a simple example of an EJB 3.1 Timer to suit such a typical requirement.

In this example, it is assumed that the application have a SessionBean facade(s) which have all the business methods. A SessionBean facade is required for making use of the container managed persistence context in the business methods. The timer just invokes the relevant business method based on the timer schedule expiration.

package com.prasune.ejb.timer;

import javax.ejb.EJB;
import javax.ejb.Schedule;
import javax.ejb.Stateless;
import javax.ejb.Timer;

import com.prasune.ejb.persistence.JPASessionFacade;


@Stateless(name = "AutomaticTimer")
public class AutomaticTimerBean {
   
    @EJB
    private JPASessionFacade jpaSessionFacade;

    public AutomaticTimerBean()
    {
    }
   
    @Schedule(dayOfWeek="*", hour="0", persistent=true,
            timezone="UTC")
    public void processEOD(Timer timer)
    {      
        jpaSessionFacade.dmlOperation();
    }
}

Our example Automatic Timer executes the specified SessionBean facade business method every day at 12:00:00 a.m midnight.

@EJB annotation is used by the JEE server for injecting the SessionBean facade for calling the relevant business method.

@Schedule annotation has elements that corresponds to chrone job like calendar expression detailed at Understanding EJB Timer Service 3.1. In our example the timer schedule is to execute every day at 12:00:00 a.m midnight.

Elements of @Schedule annotation: @Schedule has a persistent element which is optional. This is by default true. This means the schedule of the timer is persisted and not specific to JVM and hence it should survive a server crash. There is also a time zone element to specify the time zone in which the timer schedule needs to be considered. By default, the time zone of the server is considered.

@Schedules annotation can be used to specify multiple @Schedule child annotations for the same method for various types of schedule. For example: 
@Schedules ({
    @Schedule(dayOfMonth="1"),
    @Schedule(dayOfWeek="Wed", hour="4")
})
The above schedule means the timer should execute on 1st of every month and every wednesday at 4:00:00 a.m.

Packaging and Deployment

Packaging and deployment of an EJB 3.1 Timer is very simple. The class file needs to be in a jar file with the correct directory structure of the package and the jar file can be directly deployed on any JEE server supporting EJB 3.1. The vendor specific ejb-jar.xml are optional and annotations are sufficient for the JEE server to identify the class as EJB Timer.

Risk Management in a Business Organization

Risk management enables an organisation to effectively deal with the uncertainty, associated risk and opportunity to build the value. In a global competitive environment risk management is the prime concern for all the organisations.
Risk Management Process.
  1. Risk Identification
  2. Risk Assessment
  3. Measurement and Analysis of Risk
  4. Evaluation of risk
  5. Treatment of risk
  6. Monitor and Review
Risk Identification

We have to first identify the possible risk which may affect positively or negatively.We have to generate a list of sources of threats impacting on achievement of objectives at the time of pre-set ideas and past events.

In general risk may relate to

  • It's origin( eg: a hostile employee)
  • Consequences or impact of (unavailability of services)
  • Certain activity( kind of unauthorized leakage of data)
  • Specific reasons for it's occurrence(system error)
  • :Lack of protective mechanism
  • Time and place of occurrence

Risk management in an organization requires few information for the identification of risk. which include information on the list of assets and it's book value and replacement value, process information regarding it's raw materials, product information like consumer products or industrial products and liability information to the employee and the public.

Some of the important methods used to identify risk include check lists, judgements based on experiments and records, flow charts brain storming, system analysis, scenario analysis, system engineering techniques etc.

Cost of risk

Cost of risk can be presented as below
Value without risk-value with risk=cost of risk

There are different components which determine the cost of risk and those are:
  • expected losses
  • cost of loss control
  • cost of loss financing
  • cost of internal risk deduction
  • cost of any residual uncertainty

Risk Assessment.

It's the step in which we assess of evaluate the risks identified.It's important to identify the probability of occurrence of the risk, magnitude of the risk which can occur and the potential loss caused by the risk.Here we use different qualitative and quantitative techniques to assess the risk.

Risk Measurement and Analysis

Risk analysis is the phase where the level of risk and it's nature are assessed and understood.Here determine which risk has greater consequences or impact than the others.Few important elements of risk analysis are mentioned below:

  • Intensive examination of risk sources
  • Identification of strategies that minimise negative risk and enhance opportunity
  • Determine the consequence of negative impact and opportunity
  • Determine likely hood of negative opportunity
  • Estimate risk by combining consequence and likelihood.


The calculations that needs to be done for each risk are:
  • Likelihood or probability of the occurrence of the event.
  • extend of the impact or consequences.
The information used to estimate the likelihood and impact of risk are mentioned below:

  • Past experience, data and records
  • Reliable practises, international standards and guidelines
  • Market research and analysis
  • Experiments and prototypes
  • Economic engineering and other models
  • specialist and expert advice.

The analysis technique for risk management can be classified as,

Qualitative Analysis

Here magnitude and likelihood of potential consequences are presented and described in detail. An initial assessment to identify risk will be followed by further detail analysis. Here all non tangible aspects  of risk are considered. Reputation, culture Image all comes in that.It's relevant where there is lack of adequate information and numerical data.

Semi-quantitative Analysis

Here we assigns some values to the scales used in qualitative analysis method.These values are usually indicates and real.

Quantitative Analysis

Here numeric values are assigned to both impact and likelihood.

Risk is identified in 2 dimensions The impact and probability of the risk need to be assessed. It's rated in a scale of 1-4.
           
Medium
Critical
Low
High

If the probability is high and the impact is low it's considered as medium risk. But if the impact is high and probability is low it should be considered with high priority.

Risk Evaluation

At this Phase we compare the levels of risk found during risk an analysis processed and decide whether these risk requires treatment. After this we prioritise the list of risks which require further action.

In case of loss exposure we consider:

  • Potential severity of loss
  • Potential probability of loss


Risk treatment

At this phase we identify options for treating or controlling risk. Treatment of risk prioritised to,


  • Avoid the risk
  • Change the likelihood of the occurrence
  • Change the consequences
  • Share the risk
  • Retain the risk


The risk treatment techniques are implemented as a


  • Key to mange risk by implementing effective treatment option
  • When implement the treatment ensure adequate resources are available and define a time frame and responsibility
  • Physical check that treatment implemented reduces residual risk
  • Undertake remedial measures to reduce the risk


Risk Monitoring and Review

The owner must monitor and review the effectiveness of risk treatment. Also the risk managements process has to be repeated in regular intervals as there is chances for the occurrence of new risk and we need to refresh our priorities

Types of risk

Systematic risk
This risk affect the entire market and it's difficult to avoid. This risk can be mitigated by hedging exercise.
For example a significant political event can affect the entire market.

Unsystematic risk
This risk is quiet specific in nature. Strike by the employees in a plant can be a very specific risk to the plant.

Market risk
This risk is due to the day to day fluctuations in the stock market.This risk also can not be diversified much.Few factors associated with market risk are equity risk,interest rate risk,commodity risk,currency risk and credit(finance risk).

Business risk
It relates to the operation cash flow of a business. The major business risk which can give variation in cash flow and business value are
  • Price risk-Change in the cash flow due to possible change in the prices of output and input.It can be in the form of commodity price risk and exchange rate risk.
  • Credit risk-It's the risk in the settlement of dues by client. Commercial banks which are in the business of lending loans are quite subject to this risk.
  • Pure risk-Reduction in the value of the business asset as a result of physical damage,theft or legal liability.
Purchasing power risk
It refers to the impact of inflation and deflation in the economy.

Interest rate risk
This risk is due to the adverse movement of interest rates. It affects bonds more than stocks because bonds are more of a fixed income return.

Financial risk
It's related to the way in which a company utilises it's resources. It's a risk which can be avoided.

Default risk
It arise when a company is unable to pay it debt obligations like payment of bond.

Investment risk
It measures the chance of investment value to fall. Standard deviation used to measure the investment risk.

Operational risk
It includes the process risk, people risk and technology risk involved during the operation.