Example usage for javax.ejb Timer getInfo

List of usage examples for javax.ejb Timer getInfo

Introduction

In this page you can find the example usage for javax.ejb Timer getInfo.

Prototype

public Serializable getInfo()
        throws java.lang.IllegalStateException, javax.ejb.NoSuchObjectLocalException, javax.ejb.EJBException;

Source Link

Document

Get the information associated with the timer at the time of creation.

Usage

From source file:org.cesecore.certificates.certificate.CertificateStoreSessionBean.java

License:asdf

@Override
@TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED)
public void reloadCaCertificateCacheAndSetTimeout() {
    if (log.isTraceEnabled()) {
        log.trace(">timeOutReloadCaCertificateCache");
    }/*  w w w.j  a va 2  s .  c o m*/
    // Cancel any waiting timers of this type
    @SuppressWarnings("unchecked")
    final Collection<Timer> timers = timerService.getTimers();
    for (final Timer timer : timers) {
        if (timer.getInfo() instanceof Integer) {
            final int currentTimerId = ((Integer) timer.getInfo()).intValue();
            if (currentTimerId == TIMERID_CACERTIFICATECACHE) {
                timer.cancel();
            }
        }
    }
    try {
        certificateStoreSession.reloadCaCertificateCache();
    } finally {
        // Schedule a new timer of this type
        final long interval = OcspConfiguration.getSigningCertsValidTimeInMilliseconds();
        if (interval > 0) {
            timerService.createTimer(interval, Integer.valueOf(TIMERID_CACERTIFICATECACHE));
        }
    }
}

From source file:org.cesecore.certificates.certificate.CertificateStoreSessionBean.java

License:asdf

/** @return the number of timers where TimerInfo is an Integer and hold the specified value */
private int getTimerCount(final int id) {
    if (log.isTraceEnabled()) {
        log.trace(">getTimerCount");
    }/*  w ww . j av a  2  s  .  c  om*/
    int count = 0;
    @SuppressWarnings("unchecked")
    final Collection<Timer> timers = timerService.getTimers();
    for (final Timer timer : timers) {
        if (timer.getInfo() instanceof Integer) {
            final int currentTimerId = ((Integer) timer.getInfo()).intValue();
            if (currentTimerId == id) {
                count++;
            }
        }
    }
    if (log.isTraceEnabled()) {
        log.trace("<getTimerCount, timers: " + count);
    }
    return count;
}

From source file:org.cesecore.certificates.ocsp.OcspResponseGeneratorSessionBean.java

/**
 * When a timer expires, this method will update
 * /*  w w w .j a v a 2s.c o m*/
 * According to JSR 220 FR (18.2.2), this method may not throw any exceptions.
 * 
 * @param timer The timer whose expiration caused this notification.
 * 
 */
@Timeout
/* Glassfish 2.1.1:
 * "Timeout method ....timeoutHandler(javax.ejb.Timer)must have TX attribute of TX_REQUIRES_NEW or TX_REQUIRED or TX_NOT_SUPPORTED"
 * JBoss 5.1.0.GA: We cannot mix timer updates with our EJBCA DataSource transactions. 
 */
@TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED)
public void timeoutHandler(Timer timer) {
    if (log.isTraceEnabled()) {
        log.trace(">timeoutHandler: " + timer.getInfo().toString());
    }
    // reloadTokenAndChainCache cancels old timers and adds a new timer
    reloadOcspSigningCache();
    if (log.isTraceEnabled()) {
        log.trace("<timeoutHandler");
    }
}

From source file:org.cesecore.certificates.ocsp.OcspResponseGeneratorSessionBean.java

/**
 * This method cancels all timers associated with this bean.
 *//*from   w  ww  .j a v  a  2 s  .c  om*/
// We don't want the appserver to persist/update the timer in the same transaction if they are stored in different non XA DataSources. This method
// should not be run from within a transaction.
private void cancelTimers(final int id) {
    if (log.isTraceEnabled()) {
        log.trace(">cancelTimers");
    }
    @SuppressWarnings("unchecked")
    final Collection<Timer> timers = timerService.getTimers();
    for (final Timer timer : timers) {
        final int currentTimerId = ((Integer) timer.getInfo()).intValue();
        if (currentTimerId == id) {
            timer.cancel();
        }
    }
    if (log.isTraceEnabled()) {
        log.trace("<cancelTimers, timers canceled: " + timers.size());
    }
}

From source file:org.cesecore.certificates.ocsp.OcspResponseGeneratorSessionBean.java

private int getTimerCount(final int id) {
    if (log.isTraceEnabled()) {
        log.trace(">getTimerCount");
    }/* ww w .  ja  v a2s  .c om*/
    int count = 0;
    @SuppressWarnings("unchecked")
    final Collection<Timer> timers = timerService.getTimers();
    for (final Timer timer : timers) {
        final int currentTimerId = ((Integer) timer.getInfo()).intValue();
        if (currentTimerId == id) {
            count++;
        }
    }
    if (log.isTraceEnabled()) {
        log.trace("<getTimerCount, timers: " + count);
    }
    return count;
}

From source file:org.ejbca.core.ejb.ocsp.OcspKeyRenewalSessionBean.java

/**
 * This method cancels all timers associated with this bean.
 *//*from w  w w. j a  v  a  2  s .  com*/
private void cancelTimers() {
    Collection<Timer> timers = timerService.getTimers();
    for (Timer timer : timers) {
        try {
            timer.cancel();
        } catch (NoSuchObjectLocalException e) {
            if (log.isDebugEnabled()) {
                log.debug("Timer was already expired or canceled: " + timer.getInfo());
            }
        }
    }
}

From source file:org.ejbca.core.ejb.services.ServiceSessionBean.java

/**
 * Method implemented from the TimerObject and is the main method of this session bean. It calls the work object for each object.
 * //from ww  w.  j  a va 2 s. co  m
 * @param timer timer whose expiration caused this notification.
 */
@Timeout
// Glassfish 2.1.1:
// "Timeout method ....timeoutHandler(javax.ejb.Timer)must have TX attribute of TX_REQUIRES_NEW or TX_REQUIRED or TX_NOT_SUPPORTED"
// JBoss 5.1.0.GA: We cannot mix timer updates with our EJBCA DataSource transactions.
@TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED)
public void timeoutHandler(Timer timer) {
    if (log.isTraceEnabled()) {
        log.trace(">ejbTimeout");
    }
    final long startOfTimeOut = System.currentTimeMillis();
    long serviceInterval = IInterval.DONT_EXECUTE;
    Integer timerInfo = (Integer) timer.getInfo();
    if (timerInfo.equals(SERVICELOADER_ID)) {
        if (log.isDebugEnabled()) {
            log.debug("Running the internal Service loader.");
        }
        load();
    } else {
        String serviceName = null;
        try {
            serviceName = serviceDataSession.findNameById(timerInfo);
        } catch (Throwable t) { // NOPMD: we really need to catch everything to not risk hanging somewhere in limbo
            log.warn("Exception finding service name: ", t); // if this throws, there is a failed database or similar
            // Unexpected error (probably database related). We need to reschedule the service w a default interval.
            addTimer(30 * 1000, timerInfo);
        }
        if (serviceName == null) {
            final String msg = intres.getLocalizedMessage("services.servicenotfound", timerInfo);
            log.info(msg);
        } else {
            // Get interval of worker
            try {
                serviceInterval = serviceSession.getServiceInterval(timerInfo);
            } catch (Throwable t) { // NOPMD: we really need to catch everything to not risk hanging somewhere in limbo
                log.warn("Exception getting service interval: ", t); // if this throws, there is a failed database or similar
                // Unexpected error (probably database related). We need to reschedule the service w a default interval.
                addTimer(30 * 1000, timerInfo);
            }
            // Reschedule timer
            IWorker worker = null;
            if (serviceInterval != IInterval.DONT_EXECUTE) {
                Timer nextTrigger = addTimer(serviceInterval * 1000, timerInfo);
                try {
                    // Try to acquire lock / see if this node should run
                    worker = serviceSession.getWorkerIfItShouldRun(timerInfo,
                            nextTrigger.getNextTimeout().getTime());
                } catch (Throwable t) { // NOPMD: we really need to catch everything to not risk hanging somewhere in limbo
                    if (log.isDebugEnabled()) {
                        log.debug("Exception: ", t); // Don't spam log with stacktraces in normal production cases
                    }
                }
                if (worker != null) {
                    try {
                        serviceSession.executeServiceInNoTransaction(worker, serviceName);
                    } catch (RuntimeException e) {
                        /*
                         * If the service worker fails with a RuntimeException we need to
                         * swallow this here. If we allow it to propagate outside the
                         * ejbTimeout method it is up to the application server config how it
                         * should be retried, but we have already scheduled a new try
                         * previously in this method. We still want to log this as an ERROR
                         * since it is some kind of catastrophic failure..
                         */
                        log.error("Service worker execution failed.", e);
                    }
                } else {
                    if (log.isDebugEnabled()) {
                        Object o = timerInfo;
                        if (serviceName != null) {
                            o = serviceName;
                        }
                        final String msg = intres.getLocalizedMessage("services.servicerunonothernode", o);
                        log.debug(msg);
                    }
                }
                if (System.currentTimeMillis() - startOfTimeOut > serviceInterval * 1000) {
                    log.warn("Service '" + serviceName + "' took longer than it's configured service interval ("
                            + serviceInterval + ")."
                            + " This can trigger simultanious service execution on several nodes in a cluster."
                            + " Increase interval or lower each invocations work load.");
                }
            }
        }
    }
    if (log.isTraceEnabled()) {
        log.trace("<ejbTimeout");
    }
}

From source file:org.ejbca.core.ejb.services.ServiceSessionBean.java

@TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED)
@Override//from   w w  w  .j ava  2 s  .c o  m
public void load() {
    // Get all services
    Collection<Timer> currentTimers = timerService.getTimers();
    Iterator<Timer> iter = currentTimers.iterator();
    HashSet<Serializable> existingTimers = new HashSet<Serializable>();
    while (iter.hasNext()) {
        Timer timer = iter.next();
        try {
            Serializable info = timer.getInfo();
            existingTimers.add(info);
        } catch (Throwable e) { // NOPMD: we really need to catch everything to not risk hanging somewhere in limbo
            // EJB 2.1 only?: We need this try because weblogic seems to ... suck ...
            log.debug("Error invoking timer.getInfo(): ", e);
        }
    }

    // Get new services and add timeouts
    Map<Integer, Long> newTimeouts = serviceSession.getNewServiceTimeouts(existingTimers);
    for (Integer id : newTimeouts.keySet()) {
        addTimer(newTimeouts.get(id), id);
    }

    if (!existingTimers.contains(SERVICELOADER_ID)) {
        // load the service timer
        addTimer(SERVICELOADER_PERIOD, SERVICELOADER_ID);
    }
}

From source file:org.ejbca.core.ejb.services.ServiceSessionBean.java

/**
 * Cancels all existing timeouts for this id.
 * //from www .j  a v a 2  s. c  o  m
 * @param id the id of the timer
 */
// We don't want the appserver to persist/update the timer in the same transaction if they are stored in different non XA DataSources. This method
// should not be run from within a transaction.
@TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED)
@Override
public void cancelTimer(Integer id) {
    if (log.isDebugEnabled()) {
        log.debug("cancelTimer: " + id);
    }
    for (Timer next : (Collection<Timer>) timerService.getTimers()) {
        try {
            if (id.equals(next.getInfo())) {
                next.cancel();
                break;
            }
        } catch (Exception e) {
            /*
             * EJB 2.1 only?: We need to catch this because Weblogic 10
             * throws an exception if we have not scheduled this timer, so
             * we don't have anything to cancel. Only weblogic though...
             */
            log.error("Caught exception canceling timer: " + e.getMessage(), e);
        }
    }
}

From source file:org.niord.core.batch.BatchSetService.java

/**
 * Called in order to execute a batch set item
 *///from  ww w.ja  v a2 s  .  c o  m
@Timeout
private void executeBatchSetItem(Timer timer) {
    BatchSetExecution batchSetExecution = (BatchSetExecution) timer.getInfo();

    String batchJobName = batchSetExecution.getBatchSetItem().getJobName();
    String batchFileName = batchSetExecution.getBatchSetItem().getFileName();
    Path file = batchSetExecution.getBatchSetSpec().getFolder().resolve(batchFileName);
    if (!Files.isRegularFile(file)) {
        log.error("Batch file for batch set item " + batchJobName + " did not exist: " + file);
        return;
    }
    Map<String, Object> properties = batchSetExecution.getBatchSetItem().getProperties() != null
            ? batchSetExecution.getBatchSetItem().getProperties()
            : new HashMap<>();

    try (InputStream in = new FileInputStream(file.toFile())) {
        batchService.startBatchJobWithDataFile(batchJobName, in, batchFileName, properties);
    } catch (Exception e) {
        log.error("Error executing batch set item " + batchJobName + " from file " + file);
    }
}