javax.ejb.Timer Java Examples

The following examples show how to use javax.ejb.Timer. 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: TimerHandleImpl.java    From tomee with Apache License 2.0 6 votes vote down vote up
public Timer getTimer() {
    final ContainerSystem containerSystem = SystemInstance.get().getComponent(ContainerSystem.class);
    if (containerSystem == null) {
        throw new NoSuchObjectLocalException("OpenEJb container system is not running");
    }
    final BeanContext beanContext = containerSystem.getBeanContext(deploymentId);
    if (beanContext == null) {
        throw new NoSuchObjectLocalException("Deployment info not found " + deploymentId);
    }
    final EjbTimerService timerService = beanContext.getEjbTimerService();
    if (timerService == null) {
        throw new NoSuchObjectLocalException("Deployment no longer supports ejbTimout " + deploymentId + ". Has this ejb been redeployed?");
    }
    final Timer timer = timerService.getTimer(id);
    if (timer == null) {
        throw new NoSuchObjectLocalException("Timer not found for ejb " + deploymentId);
    }
    return timer;
}
 
Example #2
Source File: TimerServiceBean.java    From development with Apache License 2.0 6 votes vote down vote up
@TransactionAttribute(TransactionAttributeType.MANDATORY)
public List<VOTimerInfo> getCurrentTimerExpirationDates() {
    List<VOTimerInfo> result = new ArrayList<VOTimerInfo>();

    for (Timer timer : ParameterizedTypes.iterable(ctx.getTimerService()
            .getTimers(), Timer.class)) {
        Serializable info = timer.getInfo();
        if (info != null && info instanceof TimerType) {
            TimerType type = (TimerType) info;
            long expirationTime = timer.getTimeRemaining()
                    + System.currentTimeMillis();
            VOTimerInfo timerInfo = new VOTimerInfo();
            timerInfo.setTimerType(type.name());
            timerInfo.setExpirationDate(new Date(expirationTime));
            result.add(timerInfo);
        }
    }

    return result;
}
 
Example #3
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 #4
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 #5
Source File: TimerServiceBean2Test.java    From development with Apache License 2.0 6 votes vote down vote up
@Test(expected = ValidationException.class)
public void initTimers_nextExpirationDateNegative_userCount()
        throws ValidationException {
    // given
    tss = new TimerServiceStub() {
        @Override
        public Timer createTimer(Date arg0, Serializable arg1)
                throws IllegalArgumentException, IllegalStateException,
                EJBException {
            initTimer((TimerType) arg1, arg0);
            getTimers().add(timer);
            return null;
        }
    };
    when(ctx.getTimerService()).thenReturn(tss);
    cfs.setConfigurationSetting(ConfigurationKey.TIMER_INTERVAL_USER_COUNT,
            "9223372036854775807");
    // when
    tm.initTimers();

}
 
Example #6
Source File: EurekaClient.java    From snoop with MIT License 6 votes vote down vote up
@Timeout
public void health(Timer timer) {
   LOGGER.config(() -> "health update: " + Calendar.getInstance().getTime());
   LOGGER.config(() -> "Next: " + timer.getNextTimeout());

   EurekaConfig eurekaConfig = new EurekaConfig();
   eurekaConfig.setStatus("UP");
   Entity<InstanceConfig> entity = Entity.entity(new InstanceConfig(eurekaConfig), MediaType.APPLICATION_JSON);

   Response response = ClientBuilder.newClient()
           .target(serviceUrl + "apps/" + applicationName + "/" + applicationName)
           .request()
           .put(entity);

   LOGGER.config(() -> "PUT resulted in: " + response.getStatus() + ", " + response.getEntity());

}
 
Example #7
Source File: EjbTimerServiceImpl.java    From tomee with Apache License 2.0 6 votes vote down vote up
@Override
public Timer createTimer(final Object primaryKey, final Method timeoutMethod, final ScheduleExpression scheduleExpression, final TimerConfig timerConfig) {
    if (scheduleExpression == null) {
        throw new IllegalArgumentException("scheduleExpression is null");
    }
    //TODO add more schedule expression validation logic ?
    checkState();
    try {
        final TimerData timerData = timerStore.createCalendarTimer(this,
            (String) deployment.getDeploymentID(),
            primaryKey,
            timeoutMethod,
            scheduleExpression,
            timerConfig,
            false);
        initializeNewTimer(timerData);
        return timerData.getTimer();
    } catch (final TimerStoreException e) {
        throw new EJBException(e);
    }
}
 
Example #8
Source File: BeanContext.java    From tomee with Apache License 2.0 6 votes vote down vote up
public BeanContext(final String id, final Context jndiContext, final ModuleContext moduleContext, final Class beanClass, final Class mdbInterface, final Map<String, String> activationProperties) throws SystemException {
    this(id, jndiContext, moduleContext, BeanType.MESSAGE_DRIVEN, false, beanClass, false);

    this.getMdb().mdbInterface = mdbInterface;
    this.getMdb().activationProperties.putAll(activationProperties);

    if (TimedObject.class.isAssignableFrom(beanClass)) {
        try {
            this.ejbTimeout = beanClass.getMethod("ejbTimeout", Timer.class);
        } catch (final NoSuchMethodException e) {
            throw new IllegalStateException(e);
        }
    }

    this.initDefaultLock();

    this.createMethodMap();
}
 
Example #9
Source File: Initializer.java    From development with Apache License 2.0 5 votes vote down vote up
/**
 * Handles the timer event.
 */
@Timeout
public void handleTimer(@SuppressWarnings("unused") Timer timer) {
	if (logFile != null) {
		handleOnChange(logFile);
	}
}
 
Example #10
Source File: Initializer.java    From development with Apache License 2.0 5 votes vote down vote up
/**
 * Handles the timer event.
 */
@Timeout
public void handleTimer(@SuppressWarnings("unused") Timer timer) {
    if (logFile != null) {
        handleOnChange(logFile);
    }
}
 
Example #11
Source File: Bot.java    From monolith with Apache License 2.0 5 votes vote down vote up
public void stop(Timer timer) {
    String stopMessage = new StringBuilder("==========================\n")
            .append("Bot stopped at ").append(new Date().toString()).append("\n")
            .toString();
    event.fire(stopMessage);
    timer.cancel();
}
 
Example #12
Source File: TimerServiceBeanIT.java    From development with Apache License 2.0 5 votes vote down vote up
@Override
public void setup(TestContainer container) throws Exception {

    container.login("1");
    container.addBean(new ConfigurationServiceStub());
    container.addBean(new DataServiceBean());
    container.addBean(new ConfigurationServiceStub());
    container.addBean(accountManagementStub = new AccountServiceStub());
    container.addBean(Mockito.mock(SubscriptionServiceLocal.class));
    container.addBean(Mockito.mock(BillingServiceLocal.class));
    container.addBean(new PaymentServiceStub());
    container.addBean(new IdentityServiceStub());
    container.addBean(tm = new TimerServiceBean());
    tss = new TimerServiceStub() {
        @Override
        public Timer createTimer(Date arg0, Serializable arg1)
                throws IllegalArgumentException, IllegalStateException,
                EJBException {
            getTimers().add(new TimerStub(0, arg1, arg0, false) {
                @Override
                public Date getNextTimeout() throws EJBException,
                        IllegalStateException, NoSuchObjectLocalException {

                    return getExecDate();
                }

            });
            return null;
        }
    };
    ctx = Mockito.mock(SessionContext.class);
    Mockito.when(ctx.getTimerService()).thenReturn(tss);
    tm.ctx = ctx;
    mgr = container.get(DataService.class);
    cfgs = container.get(ConfigurationServiceLocal.class);
    setUpDirServerStub(cfgs);
}
 
Example #13
Source File: TimerServiceStub.java    From development with Apache License 2.0 5 votes vote down vote up
@Override
public Timer createTimer(Date arg0, Serializable arg1)
        throws IllegalArgumentException, IllegalStateException,
        EJBException {
    timers.add(new TimerStub(0, arg1, arg0, false));
    return null;
}
 
Example #14
Source File: Bot.java    From monolith with Apache License 2.0 5 votes vote down vote up
public Timer start() {
    String startMessage = new StringBuilder("==========================\n")
            .append("Bot started at ").append(new Date().toString()).append("\n")
            .toString();
    event.fire(startMessage);
    return timerService.createIntervalTimer(0, DURATION, new TimerConfig(null, false));
}
 
Example #15
Source File: TimerServiceStub.java    From development with Apache License 2.0 5 votes vote down vote up
@Override
public Timer createTimer(long arg0, Serializable arg1)
        throws IllegalArgumentException, IllegalStateException,
        EJBException {

    return null;
}
 
Example #16
Source File: Bot.java    From monolith with Apache License 2.0 5 votes vote down vote up
public Timer start() {
    String startMessage = new StringBuilder("==========================\n")
            .append("Bot started at ").append(new Date().toString()).append("\n")
            .toString();
    event.fire(startMessage);
    return timerService.createIntervalTimer(0, DURATION, new TimerConfig(null, false));
}
 
Example #17
Source File: EjbTimerServiceImpl.java    From tomee with Apache License 2.0 5 votes vote down vote up
@Override
public Timer getTimer(final long timerId) {
    final TimerData timerData = timerStore.getTimer((String) deployment.getDeploymentID(), timerId);
    if (timerData != null) {
        return timerData.getTimer();
    } else {
        return null;
    }
}
 
Example #18
Source File: TimerData.java    From tomee with Apache License 2.0 5 votes vote down vote up
protected void doReadObject(final ObjectInputStream in) throws IOException {
    id = in.readLong();
    deploymentId = in.readUTF();
    persistent = in.readBoolean();
    autoScheduled = in.readBoolean();

    try {
        timer = (Timer) in.readObject();
        primaryKey = in.readObject();
        timerService = (EjbTimerServiceImpl) in.readObject();
        info = in.readObject();
        trigger = AbstractTrigger.class.cast(in.readObject());
    } catch (final ClassNotFoundException e) {
        throw new IOException(e);
    }

    final String mtd = in.readUTF();
    final BeanContext beanContext = SystemInstance.get().getComponent(ContainerSystem.class).getBeanContext(deploymentId);
    scheduler = timerService.getScheduler();
    for (final Iterator<Map.Entry<Method, MethodContext>> it = beanContext.iteratorMethodContext(); it.hasNext(); ) {
        final MethodContext methodContext = it.next().getValue();
        /* this doesn't work in all cases
        if (methodContext.getSchedules().isEmpty()) {
            continue;
        }
        */

        final Method method = methodContext.getBeanMethod();
        if (method != null && method.getName().equals(mtd)) { // maybe we should check parameters too
            setTimeoutMethod(method);
            break;
        }
    }
}
 
Example #19
Source File: SingletonSimulationBean.java    From marathonv5 with Apache License 2.0 5 votes vote down vote up
@Timeout
public void timeout(Timer timer) {
    if (timer.equals(simulationTimer)){
        sim.run();
    }
    else if (timer.equals(hourlySalesTimer)){
        hourlySalesGenerator.run();
    }
}
 
Example #20
Source File: SingleActionTimerTest.java    From tomee with Apache License 2.0 5 votes vote down vote up
@Timeout
public void programmaticTimeout(final Timer timer) {

    if (!TIMER_NAME.equals(timer.getInfo())) {
        return;
    }

    final int i = this.counter.incrementAndGet();
    System.out.println("SingleActionTimer: Timeout " + i);

    this.createTimer();
}
 
Example #21
Source File: TimerServiceStub.java    From development with Apache License 2.0 5 votes vote down vote up
@Override
public Timer createIntervalTimer(long arg0, long arg1, TimerConfig arg2)
        throws IllegalArgumentException, IllegalStateException,
        EJBException {

    return null;
}
 
Example #22
Source File: TimerServiceStub.java    From development with Apache License 2.0 5 votes vote down vote up
@Override
public Timer createIntervalTimer(Date arg0, long arg1, TimerConfig arg2)
        throws IllegalArgumentException, IllegalStateException,
        EJBException {

    return null;
}
 
Example #23
Source File: TimerServiceStub.java    From development with Apache License 2.0 5 votes vote down vote up
@Override
public Timer createSingleActionTimer(long arg0, TimerConfig arg1)
        throws IllegalArgumentException, IllegalStateException,
        EJBException {

    return null;
}
 
Example #24
Source File: TimerServiceStub.java    From development with Apache License 2.0 5 votes vote down vote up
@Override
public Timer createSingleActionTimer(Date arg0, TimerConfig arg1)
        throws IllegalArgumentException, IllegalStateException,
        EJBException {

    return null;
}
 
Example #25
Source File: GetAllTimersTest.java    From tomee with Apache License 2.0 5 votes vote down vote up
private void checkList(final Collection<Timer> in) {
    final List<Timer> list = new ArrayList<>(in); list.sort(new Comparator<Timer>() {
        @Override
        public int compare(final Timer o1, final Timer o2) {
            return o1.getInfo().toString().compareTo(o2.getInfo().toString());
        }
    });
    assertEquals(2, list.size());
    final Iterator<Timer> it = list.iterator();
    assertEquals(Bean1.class.getSimpleName(), it.next().getInfo());
    assertEquals(Bean2.class.getSimpleName(), it.next().getInfo());
}
 
Example #26
Source File: TimerServlet.java    From java-course-ee with MIT License 5 votes vote down vote up
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    Collection<Timer> timers = ejb.getAllTimers();
    for (Timer timer : timers) {
        resp.getWriter().write(timer.toString() + "\n\n\n");
    }
    resp.getWriter().close();

}
 
Example #27
Source File: BasicSingletonBean.java    From tomee with Apache License 2.0 5 votes vote down vote up
public void ejbTimeout(final Timer timer) {
    testAllowedOperations("ejbTimeout");
    try {
        final String name = (String) timer.getInfo();
        final TimerSync timerSync = (TimerSync) ejbContext.lookup("TimerSyncBeanBusinessRemote");
        timerSync.countDown(name);
    } catch (final Exception e) {
        e.printStackTrace();
    }
}
 
Example #28
Source File: EntityContainer.java    From tomee with Apache License 2.0 5 votes vote down vote up
private void cancelTimers(final ThreadContext threadContext) {
    final BeanContext beanContext = threadContext.getBeanContext();
    final Object primaryKey = threadContext.getPrimaryKey();

    // if we have a real timerservice, stop all timers. Otherwise, ignore...
    if (primaryKey != null) {
        final EjbTimerService timerService = beanContext.getEjbTimerService();
        if (timerService != null && timerService instanceof EjbTimerServiceImpl) {
            for (final Timer timer : beanContext.getEjbTimerService().getTimers(primaryKey)) {
                timer.cancel();
            }
        }
    }
}
 
Example #29
Source File: EjbTimerServiceImpl.java    From tomee with Apache License 2.0 5 votes vote down vote up
@Override
public Timer createTimer(final Object primaryKey,
                         final Method timeoutMethod,
                         final long initialDuration,
                         final long intervalDuration,
                         final TimerConfig timerConfig) throws IllegalArgumentException, IllegalStateException, EJBException {
    if (initialDuration < 0) {
        throw new IllegalArgumentException("initialDuration is negative: " + initialDuration);
    }
    if (intervalDuration < 0) {
        throw new IllegalArgumentException("intervalDuration is negative: " + intervalDuration);
    }
    checkState();

    final Date initialExpiration = new Date(System.currentTimeMillis() + initialDuration);
    try {
        final TimerData timerData = timerStore.createIntervalTimer(this,
            (String) deployment.getDeploymentID(),
            primaryKey,
            timeoutMethod,
            initialExpiration,
            intervalDuration,
            timerConfig);
        initializeNewTimer(timerData);
        return timerData.getTimer();
    } catch (final TimerStoreException e) {
        throw new EJBException(e);
    }
}
 
Example #30
Source File: EjbTimerServiceImpl.java    From tomee with Apache License 2.0 5 votes vote down vote up
@Override
public Timer createTimer(final Object primaryKey,
                         final Method timeoutMethod,
                         final Date initialExpiration,
                         final long intervalDuration,
                         final TimerConfig timerConfig) throws IllegalArgumentException, IllegalStateException, EJBException {
    if (initialExpiration == null) {
        throw new IllegalArgumentException("initialExpiration is null");
    }
    if (initialExpiration.getTime() < 0) {
        throw new IllegalArgumentException("initialExpiration is negative: " + initialExpiration.getTime());
    }
    if (intervalDuration < 0) {
        throw new IllegalArgumentException("intervalDuration is negative: " + intervalDuration);
    }
    checkState();

    try {
        final TimerData timerData = timerStore.createIntervalTimer(this,
            (String) deployment.getDeploymentID(),
            primaryKey,
            timeoutMethod,
            initialExpiration,
            intervalDuration,
            timerConfig);
        initializeNewTimer(timerData);
        return timerData.getTimer();
    } catch (final TimerStoreException e) {
        throw new EJBException(e);
    }
}