javax.ejb.TimerService Java Examples

The following examples show how to use javax.ejb.TimerService. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: InitializerTest.java    From development with Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() throws Exception {
    testElm = new Initializer();
    controllerAccess = Mockito.mock(ControllerAccess.class);
    Mockito.when(controllerAccess.getControllerId()).thenReturn(
            "ess.common");
    testElm.setControllerAccess(controllerAccess);

    timerService = Mockito.mock(TimerService.class);
    Collection<Timer> timers = new ArrayList<Timer>();
    Mockito.when(timerService.getTimers()).thenReturn(timers);

    // Set timer resource
    Field field = testElm.getClass().getDeclaredField("timerService");
    field.setAccessible(true);
    field.set(testElm, timerService);

}
 
Example #2
Source File: TimerServiceBean.java    From development with Apache License 2.0 6 votes vote down vote up
void createTimerWithPeriod(TimerService timerService, TimerType timerType,
        long timerOffset, Period period) {
    if (isTimerCreated(timerType, timerService)) {
        return;
    }
    TimerConfig config = new TimerConfig();
    config.setInfo(timerType);
    Date startDate = getDateForNextTimerExpiration(period, timerOffset);
    ScheduleExpression schedleExpression = getExpressionForPeriod(period,
            startDate);
    Timer timer = timerService.createCalendarTimer(schedleExpression,
            config);
    Date nextStart = timer.getNextTimeout();
    SimpleDateFormat sdf = new SimpleDateFormat();
    logger.logInfo(Log4jLogger.SYSTEM_LOG,
            LogMessageIdentifier.INFO_TIMER_CREATED,
            String.valueOf(timerType), sdf.format(nextStart));
}
 
Example #3
Source File: TimerServiceBean.java    From development with Apache License 2.0 6 votes vote down vote up
boolean isTimerCreated(TimerType timerType, TimerService timerService) {
    for (Timer timer : ParameterizedTypes.iterable(
            timerService.getTimers(), Timer.class)) {
        TimerType tType = (TimerType) timer.getInfo();
        if ((TimerType.BILLING_INVOCATION.equals(tType) && TimerType.BILLING_INVOCATION
                .equals(timerType))
                || (TimerType.DISCOUNT_END_CHECK.equals(tType) && TimerType.DISCOUNT_END_CHECK
                        .equals(timerType))) {
            long currentTime = System.currentTimeMillis();
            if (timer.getNextTimeout().getTime() - currentTime > 0) {
                return true;
            } else {
                timer.cancel();
            }
        }
    }
    return false;
}
 
Example #4
Source File: TimerServiceBean.java    From development with Apache License 2.0 6 votes vote down vote up
/**
 * Determines all currently queued timers and cancel timer with target type.
 * 
 * @param timerService
 *            The timer service.
 * @param timerType
 *            The timer type.
 */
private void cancelObsoleteTimer(TimerService timerService,
        TimerType timerType) {

    for (Timer timer : ParameterizedTypes.iterable(
            timerService.getTimers(), Timer.class)) {
        Serializable info = timer.getInfo();
        if (info != null && info instanceof TimerType && timerType == info) {
            TimerType type = (TimerType) info;
            timer.cancel();
            logger.logInfo(Log4jLogger.SYSTEM_LOG,
                    LogMessageIdentifier.INFO_TIMER_REMOVED,
                    String.valueOf(type));
        }
    }

}
 
Example #5
Source File: BaseContext.java    From tomee with Apache License 2.0 6 votes vote down vote up
public TimerService getTimerService() throws IllegalStateException {
    doCheck(Call.getTimerService);

    final ThreadContext threadContext = ThreadContext.getThreadContext();
    final BeanContext beanContext = threadContext.getBeanContext();
    final EjbTimerService timerService = beanContext.getEjbTimerService();
    if (timerService == null) {
        throw new IllegalStateException("This ejb does not support timers " + beanContext.getDeploymentID());
    } else if (!timerService.isStarted()) {
        try {
            timerService.start();
        } catch (final OpenEJBException e) {
            throw new IllegalStateException(e);
        }
    }
    return new TimerServiceImpl(timerService, threadContext.getPrimaryKey(), beanContext.getEjbTimeout()) {
        @Override
        public Collection<Timer> getAllTimers() throws IllegalStateException, EJBException {
            return Timers.all(); // allowed here
        }
    };
}
 
Example #6
Source File: TimerServiceBean.java    From development with Apache License 2.0 5 votes vote down vote up
private void initAllTimers() throws ValidationException {
    TimerType[] supportedTimers = TimerType.values();
    TimerService timerService = ctx.getTimerService();

    for (TimerType timerType : supportedTimers) {
        TimerIntervalDetails timerDetails = getTimerDetailsForTimerType(timerType);
        long timerInterval = timerDetails.getIntervalTime();
        long timerOffset = timerDetails.getIntervalOffset();
        Period period = timerDetails.getPeriod();

        // create required timers
        if (timerInterval > 0) {
            createTimerWithInterval(timerService, timerType, timerInterval,
                    timerOffset);
        } else if (period != null) {
            // if there is only a period, start a calendar timer.
            createTimerWithPeriod(timerService, timerType, timerOffset,
                    period);
        } else {
            logger.logInfo(Log4jLogger.SYSTEM_LOG,
                    LogMessageIdentifier.INFO_TIMER_NOT_INITIALIZED,
                    String.valueOf(timerType));
        }
    }

    logger.logInfo(Log4jLogger.SYSTEM_LOG,
            LogMessageIdentifier.INFO_TIMER_INITIALIZED);
}
 
Example #7
Source File: InitializerTest.java    From development with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() throws Exception {

    testElm = new Initializer();
    timerService = Mockito.mock(TimerService.class);
    Collection<Timer> timers = new ArrayList<Timer>();
    Mockito.when(timerService.getTimers()).thenReturn(timers);

    // Set timer resource
    Field field = testElm.getClass().getDeclaredField("timerService");
    field.setAccessible(true);
    field.set(testElm, timerService);

}
 
Example #8
Source File: APPTimerServiceBeanTest.java    From development with Apache License 2.0 5 votes vote down vote up
@Before
public void setup() throws Exception {
    timerService = spy(new APPTimerServiceBean());
    timer = mock(Timer.class);
    em = mock(EntityManager.class);
    logger = mock(Logger.class);
    timerService.em = em;
    timerService.logger = logger;
    doNothing().when(em).persist(any(ServiceInstance.class));
    ts = mock(TimerService.class);
    mailService = Mockito.mock(APPCommunicationServiceBean.class);
    besDAOMock = mock(BesDAO.class);
    provFactoryBean = mock(ProductProvisioningServiceFactoryBean.class);
    configService = mock(APPConfigurationServiceBean.class);
    instanceDAO = mock(ServiceInstanceDAO.class);
    timerBean = mock(APPTimerServiceBean.class);
    timerService.instanceDAO = instanceDAO;
    timerService.configService = configService;
    timerService.mailService = mailService;
    timerService.besDAO = besDAOMock;
    timerService.timerService = ts;
    timerService.appTimerServiceBean = timerBean;
    Collection<Timer> timers = new ArrayList<Timer>();
    controller = mock(APPlatformController.class);

    doReturn(getResult()).when(instanceDAO).getInstancesInWaitingState();
    doReturn(timers).when(timerService.timerService).getTimers();

}
 
Example #9
Source File: TestContainer.java    From development with Apache License 2.0 5 votes vote down vote up
public TestContainer(TestPersistence persistence) throws Exception {
    this.persistence = persistence;
    this.sessionContext = new TestSessionContext(
            persistence.getTransactionManager(), sessionBeans);
    this.timerService = new TestTimerService();

    resources.put(SessionContext.class, sessionContext);
    resources.put(TimerService.class, timerService);
    resources.put(ConnectionFactory.class, new TestJMSConnectionFactory());
    resources.put(Queue.class, TestJMSQueue.getInstance());
    resources.put(WebServiceContext.class, new TestWebServiceContext(
            sessionContext));
    contextManager = new ContextManager(this);
    addBean(new TestEvent(contextManager));
}
 
Example #10
Source File: Timers.java    From tomee with Apache License 2.0 5 votes vote down vote up
public static TimerService getTimerService(final Object pk, final BeanContext beanContext, final boolean nullIfNotRelevant) throws IllegalStateException {
    final EjbTimerService timerService = beanContext.getEjbTimerService();
    if (timerService == null) {
        if (nullIfNotRelevant) {
            return null;
        }
        throw new IllegalStateException("This ejb does not support timers " + beanContext.getDeploymentID());
    } else if (beanContext.getEjbTimeout() == null) {

        HasSchedule hasSchedule = beanContext.get(HasSchedule.class);

        boolean hasSchedules = false;

        if (hasSchedule != null) {
            hasSchedules = hasSchedule.value;
        } else {
            for (final Iterator<Map.Entry<Method, MethodContext>> it = beanContext.iteratorMethodContext(); it.hasNext(); ) {
                final Map.Entry<Method, MethodContext> entry = it.next();
                final MethodContext methodContext = entry.getValue();
                if (methodContext.getSchedules().size() > 0) {
                    hasSchedules = true;
                }
            }
            synchronized (beanContext) { // surely not the best lock instance but works in this context
                if (beanContext.get(HasSchedule.class) == null) {
                    beanContext.set(HasSchedule.class, new HasSchedule(hasSchedules));
                }
            }
        }

        if (!hasSchedules) {
            if (nullIfNotRelevant) {
                return null;
            }
            LOGGER.error("This ejb does not support timers " + beanContext.getDeploymentID() + " due to no timeout method nor schedules in methodContext is configured");
        }

    }
    return new TimerServiceImpl(timerService, pk, beanContext.getEjbTimeout());
}
 
Example #11
Source File: TimerServiceBean.java    From development with Apache License 2.0 4 votes vote down vote up
private void createTimerWithInterval(TimerService timerService,
        TimerType timerType, long timerInterval, long timerOffset)
        throws ValidationException {
    // FIXME: this is quick fix for bug 11241. To avoid generate the
    // same constraint of timer, set timerInterval to
    // TIMER_HANDLING_DISTANCE if the timerInterval is smaller than
    // TIMER_HANDLING_DISTANCE.
    if (timerInterval <= TIMER_HANDLING_DISTANCE) {
        timerInterval = TIMER_HANDLING_DISTANCE;
    }

    Date nextStart = getDateForNextTimerExpiration(timerInterval,
            timerOffset);
    ValidationException validationException;
    String[] params;
    if (nextStart.getTime() < 0) {
        if (timerType.name().equals(TimerType.USER_NUM_CHECK.name())) {
            params = new String[] { timerType.name(),
                    timerType.getKeyForIntervalTime().name() };
            validationException = new ValidationException(
                    ValidationException.ReasonEnum.TIMER_USERCOUNT_EXPIRATIONDATE_INVALID,
                    null, params);
            logger.logError(
                    Log4jLogger.SYSTEM_LOG,
                    validationException,
                    LogMessageIdentifier.ERROR_TIMER_USERCOUNT_EXPIRATIONDATE_INVALID,
                    params);
        } else {
            params = new String[] { timerType.name(),
                    timerType.getKeyForIntervalTime().name(),
                    timerType.getKeyForIntervalOffset().name() };
            validationException = new ValidationException(
                    ValidationException.ReasonEnum.TIMER_EXPIRATIONDATE_INVALID,
                    null, params);
            logger.logError(
                    Log4jLogger.SYSTEM_LOG,
                    validationException,
                    LogMessageIdentifier.ERROR_TIMER_EXPIRATIONDATE_INVALID,
                    params);
        }
        throw validationException;
    }

    cancelObsoleteTimer(timerService, timerType);

    timerService.createTimer(nextStart, timerInterval, timerType);

    SimpleDateFormat sdf = new SimpleDateFormat();
    logger.logInfo(Log4jLogger.SYSTEM_LOG,
            LogMessageIdentifier.INFO_TIMER_CREATED_WITH_INTERVAL,
            timerType.toString(), sdf.format(nextStart),
            Long.toString(timerInterval));
}
 
Example #12
Source File: TestSessionContext.java    From development with Apache License 2.0 4 votes vote down vote up
@Override
public TimerService getTimerService() throws IllegalStateException {
    throw new UnsupportedOperationException();
}
 
Example #13
Source File: TimerServiceWrapper.java    From tomee with Apache License 2.0 4 votes vote down vote up
private TimerService getTimerService() throws IllegalStateException {
    final ThreadContext threadContext = ThreadContext.getThreadContext();
    final BeanContext beanContext = threadContext.getBeanContext();
    return Timers.getTimerService(threadContext.getPrimaryKey(), beanContext, false);
}