
package de.ivu.elect.jee.faces;

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

@Stateless
public class CronExpressionValidatorTimerBean {

  @Resource
  private transient TimerService timerService;

  public boolean isExpressionValid(ScheduleExpression expression) {
    Timer timer = null;
    try {
      timer = timerService.createCalendarTimer(expression, new TimerConfig("", false));
    } catch (IllegalArgumentException ex) {
      return false;
    } finally {
      cancelTimer(timer);
    }

    return true;
  }

  @Timeout
  public void timeout(Timer timer) {
    cancelTimer(timer);
  }

  private void cancelTimer(Timer timer) {
    if (timer == null) {
      return;
    }
    try {
      timer.cancel();
    } catch (Exception ex) {
      /* Nichts zu tun hier, alles gut. */
    }

  }
}
