Example usage for javax.ejb TransactionAttributeType NOT_SUPPORTED

List of usage examples for javax.ejb TransactionAttributeType NOT_SUPPORTED

Introduction

In this page you can find the example usage for javax.ejb TransactionAttributeType NOT_SUPPORTED.

Prototype

TransactionAttributeType NOT_SUPPORTED

To view the source code for javax.ejb TransactionAttributeType NOT_SUPPORTED.

Click Source Link

Document

The container invokes an enterprise bean method whose transaction attribute NOT_SUPPORTED with an unspecified transaction context.

Usage

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

@Override
@TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED)
public void initTimers() {
    // Reload OCSP signing cache, and cancel/create timers if there are no timers or if the cache is empty (probably a fresh startup)
    if (getTimerCount(TIMERID_OCSPSIGNINGCACHE) == 0 || OcspSigningCache.INSTANCE.getEntries().isEmpty()) {
        reloadOcspSigningCache();/*  ww  w  .java2 s. co  m*/
    } else {
        log.info("Not initing OCSP reload timers, there are already some.");
    }
}

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

@Override
@TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED)
public void reloadOcspExtensionsCache() {
    OcspExtensionsCache.INSTANCE.reloadCache();
}

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

@Override
@TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED)
public void clearCTFailFastCache() {
    final CertificateTransparency ct = CertificateTransparencyFactory.getInstance();
    if (ct != null) {
        ct.clearCaches();/*w  w w. jav  a 2  s  .c om*/
    }
}

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

@Override
@TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED)
public void reloadOcspSigningCache() {
    if (log.isTraceEnabled()) {
        log.trace(">reloadOcspSigningCache");
    }//w w w.  ja  va2  s. co m
    // Cancel any waiting timers of this type
    cancelTimers(TIMERID_OCSPSIGNINGCACHE);
    try {
        // Verify card key holder
        if (log.isDebugEnabled() && (CardKeyHolder.getInstance().getCardKeys() == null)) {
            log.debug(intres.getLocalizedMessage("ocsp.classnotfound", hardTokenClassName));
        }
        GlobalOcspConfiguration ocspConfiguration = (GlobalOcspConfiguration) globalConfigurationSession
                .getCachedConfiguration(GlobalOcspConfiguration.OCSP_CONFIGURATION_ID);
        OcspSigningCache.INSTANCE.stagingStart();
        try {
            // Populate OcspSigningCache
            // Add all potential CA's as OCSP responders to the staging area
            for (final Integer caId : caSession.getAllCaIds()) {
                final List<X509Certificate> caCertificateChain = new ArrayList<X509Certificate>();
                try {
                    final CAInfo caInfo = caSession.getCAInfoInternal(caId.intValue());
                    if (caInfo.getCAType() == CAInfo.CATYPE_CVC) {
                        // Bravely ignore OCSP for CVC CAs
                        continue;
                    }
                    if (caInfo.getStatus() == CAConstants.CA_ACTIVE) {
                        //Cache active CAs as signers
                        if (log.isDebugEnabled()) {
                            log.debug(
                                    "Processing X509 CA " + caInfo.getName() + " (" + caInfo.getCAId() + ").");
                        }
                        final CAToken caToken = caInfo.getCAToken();
                        final CryptoToken cryptoToken = cryptoTokenSession
                                .getCryptoToken(caToken.getCryptoTokenId());
                        if (cryptoToken == null) {
                            log.info("Excluding CA with id " + caId
                                    + " for OCSP signing consideration due to missing CryptoToken.");
                            continue;
                        }
                        for (final Certificate certificate : caInfo.getCertificateChain()) {
                            caCertificateChain.add((X509Certificate) certificate);
                        }
                        final String keyPairAlias;
                        try {
                            keyPairAlias = caToken.getAliasFromPurpose(CATokenConstants.CAKEYPURPOSE_CERTSIGN);
                        } catch (CryptoTokenOfflineException e) {
                            log.warn("Referenced private key with purpose "
                                    + CATokenConstants.CAKEYPURPOSE_CERTSIGN
                                    + " could not be used. CryptoToken is off-line for CA with id " + caId
                                    + ": " + e.getMessage());
                            continue;
                        }
                        final PrivateKey privateKey;
                        try {
                            privateKey = cryptoToken.getPrivateKey(keyPairAlias);
                        } catch (CryptoTokenOfflineException e) {
                            log.warn("Referenced private key with alias " + keyPairAlias
                                    + " could not be used. CryptoToken is off-line for CA with id " + caId
                                    + ": " + e.getMessage());
                            continue;
                        }
                        if (privateKey == null) {
                            log.warn("Referenced private key with alias " + keyPairAlias
                                    + " does not exist. Ignoring CA with id " + caId);
                            continue;
                        }
                        final String signatureProviderName = cryptoToken.getSignProviderName();
                        if (caCertificateChain.size() > 0) {
                            X509Certificate caCertificate = caCertificateChain.get(0);
                            CertificateStatus caCertificateStatus = certificateStoreSession.getStatus(
                                    CertTools.getIssuerDN(caCertificate),
                                    CertTools.getSerialNumber(caCertificate));
                            OcspSigningCache.INSTANCE.stagingAdd(new OcspSigningCacheEntry(caCertificate,
                                    caCertificateStatus, caCertificateChain, null, privateKey,
                                    signatureProviderName, null, OcspConfiguration.getResponderIdType()));
                            // Check if CA cert has been revoked somehow. Always make this check, even if this CA has an OCSP signing certificate, because
                            // signing will still fail even if the signing cert is valid. Shouldn't happen, but log it just in case.
                            if (caCertificateStatus.equals(CertificateStatus.REVOKED)) {
                                log.warn("Active CA with subject DN '" + CertTools.getSubjectDN(caCertificate)
                                        + "' and serial number " + CertTools.getSerialNumber(caCertificate)
                                        + " has a revoked certificate.");
                            }
                            //Check if CA cert is expired
                            if (!CertTools.isCertificateValid(caCertificate)) {
                                log.warn("Active CA with subject DN '" + CertTools.getSubjectDN(caCertificate)
                                        + "' and serial number " + CertTools.getSerialNumber(caCertificate)
                                        + " has an expired certificate.");
                            }
                        } else {
                            log.warn("CA with ID " + caId
                                    + " appears to lack a certificate in the database. This may be a serious error if not in a test environment.");
                        }
                    } else if (caInfo.getStatus() == CAConstants.CA_EXTERNAL) {
                        // If set, all external CA's without a keybinding (set below) will be responded to by the default responder. 
                        for (final Certificate certificate : caInfo.getCertificateChain()) {
                            caCertificateChain.add((X509Certificate) certificate);
                        }
                        CertificateStatus caCertificateStatus = certificateStoreSession.getStatus(
                                CertTools.getIssuerDN(caCertificateChain.get(0)),
                                CertTools.getSerialNumber(caCertificateChain.get(0)));
                        // Check if CA cert has been revoked somehow. Always make this check, even if this CA has an OCSP signing certificate, because
                        // signing will still fail even if the signing cert is valid. 
                        if (caCertificateStatus.equals(CertificateStatus.REVOKED)) {
                            log.warn("External CA with subject DN '"
                                    + CertTools.getSubjectDN(caCertificateChain.get(0)) + "' and serial number "
                                    + CertTools.getSerialNumber(caCertificateChain.get(0))
                                    + " has a revoked certificate.");
                        }
                        //Check if CA cert is expired
                        if (!CertTools.isCertificateValid(caCertificateChain.get(0))) {
                            log.warn("External CA with subject DN '"
                                    + CertTools.getSubjectDN(caCertificateChain.get(0)) + "' and serial number "
                                    + CertTools.getSerialNumber(caCertificateChain.get(0))
                                    + " has an expired certificate.");
                        }
                        //Add an entry with just a chain and nothing else
                        OcspSigningCache.INSTANCE.stagingAdd(
                                new OcspSigningCacheEntry(caCertificateChain.get(0), caCertificateStatus, null,
                                        null, null, null, null, OcspConfiguration.getResponderIdType()));

                    }
                } catch (CADoesntExistsException e) {
                    // Should only happen if the CA was deleted between the getAvailableCAs and the last one
                    log.warn("CA with Id " + caId + " disappeared during reload operation.");
                }
            }
            // Add all potential InternalKeyBindings as OCSP responders to the staging area, overwriting CA entries from before
            for (final int internalKeyBindingId : internalKeyBindingDataSession
                    .getIds(OcspKeyBinding.IMPLEMENTATION_ALIAS)) {
                final OcspKeyBinding ocspKeyBinding = (OcspKeyBinding) internalKeyBindingDataSession
                        .getInternalKeyBinding(internalKeyBindingId);
                if (log.isDebugEnabled()) {
                    log.debug("Processing " + ocspKeyBinding.getName() + " (" + ocspKeyBinding.getId() + ")");
                }
                if (!ocspKeyBinding.getStatus().equals(InternalKeyBindingStatus.ACTIVE)) {
                    if (log.isDebugEnabled()) {
                        log.debug("Ignoring OcspKeyBinding since it is not active.");
                    }
                    continue;
                }
                final X509Certificate ocspSigningCertificate = (X509Certificate) certificateStoreSession
                        .findCertificateByFingerprint(ocspKeyBinding.getCertificateId());
                if (ocspSigningCertificate == null) {
                    log.warn("OCSP signing certificate with referenced fingerprint "
                            + ocspKeyBinding.getCertificateId()
                            + " does not exist. Ignoring internalKeyBinding with id " + ocspKeyBinding.getId());
                    continue;
                }
                //Make the same check as above 
                if (certificateStoreSession
                        .getStatus(CertTools.getIssuerDN(ocspSigningCertificate),
                                CertTools.getSerialNumber(ocspSigningCertificate))
                        .equals(CertificateStatus.REVOKED)) {
                    log.warn("OCSP Responder certificate with subject DN '"
                            + CertTools.getSubjectDN(ocspSigningCertificate) + "' and serial number "
                            + CertTools.getSerialNumber(ocspSigningCertificate) + " is revoked.");
                }
                //Check if signing cert is expired
                if (!CertTools.isCertificateValid(ocspSigningCertificate)) {
                    log.warn("OCSP Responder certificate with subject DN '"
                            + CertTools.getSubjectDN(ocspSigningCertificate) + "' and serial number "
                            + CertTools.getSerialNumber(ocspSigningCertificate) + " is expired.");
                }

                OcspSigningCacheEntry ocspSigningCacheEntry = makeOcspSigningCacheEntry(ocspSigningCertificate,
                        ocspKeyBinding);
                if (ocspSigningCacheEntry == null) {
                    continue;
                } else {
                    OcspSigningCache.INSTANCE.stagingAdd(ocspSigningCacheEntry);
                }
            }
            OcspSigningCache.INSTANCE.stagingCommit(ocspConfiguration.getOcspDefaultResponderReference());
        } finally {
            OcspSigningCache.INSTANCE.stagingRelease();
        }
    } finally {
        // Schedule a new timer of this type
        addTimer(OcspConfiguration.getSigningCertsValidTimeInMilliseconds(), TIMERID_OCSPSIGNINGCACHE);
    }
}

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

/**
 * When a timer expires, this method will update
 * /*from ww w . ja  v  a 2s. c  om*/
 * 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.ejbca.core.ejb.ocsp.OcspKeyRenewalSessionBean.java

/**
 * When the timer expires, this method will check through the cache and automatically renew keystore matching the predefined criteria, 
 * and which expire within the designated time frame.
 * //from  www  .j  a v  a  2 s .  co  m
 * According to JSR 220 FR (18.2.2), this method may not throw any exceptions.
 * 
 * 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. 
 * 
 * @param timer The timer whose expiration caused this notification.
 * 
 */
@Timeout
@TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED)
public void timeoutHandler(Timer timer) {
    long rekeyingUpdateTime = OcspConfiguration.getRekeyingUpdateTimeInSeconds();
    try {
        renewKeyStores(RENEW_ALL_KEYS, OcspConfiguration.getRekeyingSafetyMarginInSeconds());
    } catch (InvalidKeyException e) {
        log.error("A cached crypto token contains an invalid key pair. Stopping timers.", e);
    } catch (CryptoTokenOfflineException e) {
        //Rescheduling is handled in a finally clause in OcspKeyRenewalSessionBean.renewKeyStores(String, long)
        log.error(
                "Crypto token was offline or unavailable during automatic update. Rescheduling a new timer in "
                        + rekeyingUpdateTime + " seconds.",
                e);
    }

}

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  w  ww  .  ja  va2  s. c  o 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 a  v  a 2s . c  o m*/
public void executeServiceInNoTransaction(IWorker worker, String serviceName) {
    try {
        // Awkward way of letting POJOs get interfaces, but shows dependencies on the EJB level for all used classes. Injection wont work, since
        // we have circular dependencies!
        Map<Class<?>, Object> ejbs = new HashMap<Class<?>, Object>();
        ejbs.put(ApprovalSessionLocal.class, approvalSession);
        ejbs.put(EndEntityAuthenticationSessionLocal.class, authenticationSession);
        ejbs.put(AccessControlSessionLocal.class, authorizationSession);
        ejbs.put(CAAdminSessionLocal.class, caAdminSession);
        ejbs.put(CaSessionLocal.class, caSession);
        ejbs.put(CertificateProfileSessionLocal.class, certificateProfileSession);
        ejbs.put(CertificateStoreSessionLocal.class, certificateStoreSession);
        ejbs.put(CrlCreateSessionLocal.class, crlCreateSession);
        ejbs.put(CrlStoreSessionLocal.class, crlStoreSession);
        ejbs.put(EndEntityProfileSessionLocal.class, endEntityProfileSession);
        ejbs.put(HardTokenSessionLocal.class, hardTokenSession);
        ejbs.put(SecurityEventsLoggerSessionLocal.class, auditSession);
        ejbs.put(InternalSecurityEventsLoggerSessionLocal.class, internalAuditSession);
        ejbs.put(KeyRecoverySessionLocal.class, keyRecoverySession);
        ejbs.put(AdminPreferenceSessionLocal.class, raAdminSession);
        ejbs.put(GlobalConfigurationSessionLocal.class, globalConfigurationSession);
        ejbs.put(SignSessionLocal.class, signSession);
        ejbs.put(EndEntityManagementSessionLocal.class, endEntityManagementSession);
        ejbs.put(PublisherQueueSessionLocal.class, publisherQueueSession);
        ejbs.put(PublisherSessionLocal.class, publisherSession);
        ejbs.put(CertificateRequestSessionLocal.class, certificateRequestSession);
        ejbs.put(EndEntityAccessSessionLocal.class, endEntityAccessSession);
        ejbs.put(WebAuthenticationProviderSessionLocal.class, webAuthenticationSession);
        ejbs.put(ComplexAccessControlSessionLocal.class, complexAccessControlSession);
        ejbs.put(PublishingCrlSessionLocal.class, publishingCrlSession);
        ejbs.put(CryptoTokenManagementSessionLocal.class, cryptoTokenSession);
        worker.work(ejbs);
        final String msg = intres.getLocalizedMessage("services.serviceexecuted", serviceName);
        log.info(msg);
    } catch (ServiceExecutionFailedException e) {
        final String msg = intres.getLocalizedMessage("services.serviceexecutionfailed", serviceName);
        log.info(msg, e);
    }
}

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

@TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED)
@Override/*from   w  w w  .  ja  v a 2s. c om*/
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

@TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED)
@Override//w ww.  j  a  v a 2s  .  c  om
public void unload() {
    log.debug("Unloading all timers.");
    // Get all services
    for (Timer timer : (Collection<Timer>) timerService.getTimers()) {
        try {
            timer.cancel();
        } 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.info("Caught exception canceling timer: " + e.getMessage());
        }
    }
}