Java 类javax.ejb.TimerService 实例源码

项目:oscm    文件:TimerServiceBean.java   
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));
}
项目:oscm    文件:InitializerTest.java   
@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);

}
项目:oscm    文件:TimerServiceBean.java   
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;
}
项目:oscm    文件:TimerServiceBean.java   
/**
 * 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));
        }
    }

}
项目:development    文件:InitializerTest.java   
@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);

}
项目:development    文件:TimerServiceBean.java   
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));
}
项目:development    文件:TimerServiceBean.java   
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;
}
项目:development    文件:TimerServiceBean.java   
/**
 * 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));
        }
    }

}
项目:tomee    文件:BaseContext.java   
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
        }
    };
}
项目:Mastering-Java-EE-Development-with-WildFly    文件:OldSpecsBean.java   
@Override
public void fireInThirtySeconds() throws EJBException {

    TimerService theTimerService = theEJBContext.getTimerService();
    String aLabel = "30SecondTimeout";
    Timer theTimer = theTimerService.createTimer(300, aLabel);
    logger.info("timer is: " + theTimer);
}
项目:oscm-app    文件:InitializerTest.java   
@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);

}
项目:oscm    文件:TimerServiceBean.java   
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);
}
项目:oscm    文件:InitializerTest.java   
@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);

}
项目:oscm    文件:APPTimerServiceBeanTest.java   
@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();

}
项目:oscm    文件:TestContainer.java   
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));
}
项目:myWMS    文件:LocationSanityBusinessBean.java   
public void createCronJob() {

    Long intervall = 10 * 1000L;

    String value;
    try {
        value = configService
                .getValue(LocationSanityBusiness.class, contextService.getCallersUser()
                        .getClient(), LocationSanityBusiness.TIME_OUT_KEY);
        if (value != null) {
            try {
                intervall = Long.parseLong(value);
            } catch (NumberFormatException ex) {
                log.warn(ex.getMessage());
                intervall = 10 * 1000L;
            }
        }
    } catch (EntityNotFoundException e) {
        log.error(e.getMessage(), e);
    }

    if (getTimer() != null){
        cancelCronJob();
    }
    TimerService timerService = ctx.getTimerService();
    timerService.createTimer(new Date(System.currentTimeMillis() + intervall), intervall,
            LocationSanityBusiness.TIME_OUT_INFO);

}
项目:myWMS    文件:LocationSanityBusinessBean.java   
public void cancelCronJob() {
    TimerService timerService = ctx.getTimerService();
    for (Timer timer : (Collection<Timer>) timerService.getTimers()) {
        if (timer.getInfo() instanceof String) {
            if (((String) timer.getInfo())
                    .equals(LocationSanityBusiness.TIME_OUT_INFO)) {
                timer.cancel();
                log.info("Cancel timer: " + timer.toString());
                return;
            }
        }
    }
}
项目:myWMS    文件:LocationSanityBusinessBean.java   
public Timer getTimer() {
    TimerService timerService = ctx.getTimerService();
    for (Timer timer : (Collection<Timer>) timerService.getTimers()) {
        if (timer.getInfo() instanceof String) {
            if (((String) timer.getInfo())
                    .equals(LocationSanityBusiness.TIME_OUT_INFO)) {
                log.info(" " + timer.toString());
                return timer;
            }
        }
    }

    return null;
}
项目:development    文件:TimerServiceBean.java   
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);
}
项目:development    文件:InitializerTest.java   
@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);

}
项目:development    文件:APPTimerServiceBeanTest.java   
@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();

}
项目:development    文件:TestContainer.java   
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));
}
项目:tomee    文件:Timers.java   
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());
}
项目:oscm    文件:TimerServiceBean.java   
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));
}
项目:oscm    文件:TestSessionContext.java   
@Override
public TimerService getTimerService() throws IllegalStateException {
    throw new UnsupportedOperationException();
}
项目:development    文件:TimerServiceBean.java   
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));
}
项目:development    文件:TestSessionContext.java   
@Override
public TimerService getTimerService() throws IllegalStateException {
    throw new UnsupportedOperationException();
}
项目:tomee    文件:TimerServiceWrapper.java   
private TimerService getTimerService() throws IllegalStateException {
    final ThreadContext threadContext = ThreadContext.getThreadContext();
    final BeanContext beanContext = threadContext.getBeanContext();
    return Timers.getTimerService(threadContext.getPrimaryKey(), beanContext, false);
}
项目:caarray    文件:SessionContextStub.java   
/**
 * {@inheritDoc}
 */
public TimerService getTimerService() throws IllegalStateException {
    // no-op
    return null;
}