Example usage for javax.ejb EJBException EJBException

List of usage examples for javax.ejb EJBException EJBException

Introduction

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

Prototype

public EJBException(String message, Exception ex) 

Source Link

Document

Constructs an EJBException that embeds the originally thrown exception with the specified detail message.

Usage

From source file:org.ejbca.core.ejb.ra.EndEntityManagementSessionBean.java

@Override
public void revokeUser(AuthenticationToken admin, String username, int reason)
        throws AuthorizationDeniedException, FinderException, ApprovalException, WaitingForApprovalException,
        AlreadyRevokedException {/*from   w w  w .  j a v a 2  s.  c o  m*/
    if (log.isTraceEnabled()) {
        log.trace(">revokeUser(" + username + ")");
    }
    final UserData userData = UserData.findByUsername(entityManager, username);
    if (userData == null) {
        throw new FinderException("Could not find user " + username);
    }
    final int caid = userData.getCaId();
    assertAuthorizedToCA(admin, caid);
    if (getGlobalConfiguration().getEnableEndEntityProfileLimitations()) {
        assertAuthorizedToEndEntityProfile(admin, userData.getEndEntityProfileId(),
                AccessRulesConstants.REVOKE_END_ENTITY, caid);
    }

    if ((userData.getStatus() == EndEntityConstants.STATUS_REVOKED) && ((reason == RevokedCertInfo.NOT_REVOKED)
            || (reason == RevokedCertInfo.REVOCATION_REASON_REMOVEFROMCRL))) {
        final String msg = intres.getLocalizedMessage("ra.errorinvalidrevokereason", userData.getUsername(),
                reason);
        log.info(msg);
        throw new AlreadyRevokedException(msg);
    }

    // Check if approvals is required.
    final int numOfReqApprovals = getNumOfApprovalRequired(CAInfo.REQ_APPROVAL_REVOCATION, caid,
            userData.getCertificateProfileId());
    if (numOfReqApprovals > 0) {
        final RevocationApprovalRequest ar = new RevocationApprovalRequest(false, username, reason, admin,
                numOfReqApprovals, caid, userData.getEndEntityProfileId());
        if (ApprovalExecutorUtil.requireApproval(ar, NONAPPROVABLECLASSNAMES_REVOKEUSER)) {
            approvalSession.addApprovalRequest(admin, ar);
            throw new WaitingForApprovalException(intres.getLocalizedMessage("ra.approvalrevoke"));
        }
    }
    // Revoke all certs, one at the time
    final Collection<Certificate> certs = certificateStoreSession.findCertificatesByUsername(username);
    for (final Certificate cert : certs) {
        try {
            revokeCert(admin, CertTools.getSerialNumber(cert), CertTools.getIssuerDN(cert), reason);
        } catch (AlreadyRevokedException e) {
            if (log.isDebugEnabled()) {
                log.debug("Certificate from issuer '" + CertTools.getIssuerDN(cert) + "' with serial "
                        + CertTools.getSerialNumber(cert) + " was already revoked.");
            }
        }
    }
    // Finally set revoke status on the user as well
    try {
        setUserStatus(admin, userData, EndEntityConstants.STATUS_REVOKED);
    } catch (ApprovalException e) {
        throw new EJBException("This should never happen", e);
    } catch (WaitingForApprovalException e) {
        throw new EJBException("This should never happen", e);
    }
    final String msg = intres.getLocalizedMessage("ra.revokedentity", username);
    Map<String, Object> details = new LinkedHashMap<String, Object>();
    details.put("msg", msg);
    auditSession.log(EjbcaEventTypes.RA_REVOKEDENDENTITY, EventStatus.SUCCESS, EjbcaModuleTypes.RA,
            ServiceTypes.CORE, admin.toString(), String.valueOf(caid), null, username, details);
    if (log.isTraceEnabled()) {
        log.trace("<revokeUser()");
    }
}

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

private BasicOCSPResp generateBasicOcspResp(Extensions exts, List<OCSPResponseItem> responses, String sigAlg,
        X509Certificate signerCert, OcspSigningCacheEntry ocspSigningCacheEntry, Date producedAt)
        throws OCSPException, NoSuchProviderException, CryptoTokenOfflineException {
    final PrivateKey signerKey = ocspSigningCacheEntry.getPrivateKey();
    final String provider = ocspSigningCacheEntry.getSignatureProviderName();
    BasicOCSPResp returnval = null;//from   www  .j av  a  2s . com
    BasicOCSPRespBuilder basicRes = new BasicOCSPRespBuilder(ocspSigningCacheEntry.getRespId());
    if (responses != null) {
        for (OCSPResponseItem item : responses) {
            basicRes.addResponse(item.getCertID(), item.getCertStatus(), item.getThisUpdate(),
                    item.getNextUpdate(), item.getExtensions());
        }
    }
    if (exts != null) {
        @SuppressWarnings("rawtypes")
        Enumeration oids = exts.oids();
        if (oids.hasMoreElements()) {
            basicRes.setResponseExtensions(exts);
        }
    }
    final X509Certificate[] chain = ocspSigningCacheEntry.getResponseCertChain();
    if (log.isDebugEnabled()) {
        log.debug("The response certificate chain contains " + chain.length + " certificates");
    }
    /*
     * The below code breaks the EJB standard by creating its own thread pool and creating a single thread (of the HsmResponseThread 
     * type). The reason for this is that the HSM may deadlock when requesting an OCSP response, which we need to guard against. Since 
     * there is no way of performing this action within the EJB3.0 standard, we are consciously creating threads here. 
     * 
     * Note that this does in no way break the spirit of the EJB standard, which is to not interrupt EJB's transaction handling by 
     * competing with its own thread pool, since these operations have no database impact.
     */
    final Future<BasicOCSPResp> task = service
            .submit(new HsmResponseThread(basicRes, sigAlg, signerKey, chain, provider, producedAt));
    try {
        returnval = task.get(HsmResponseThread.HSM_TIMEOUT_SECONDS, TimeUnit.SECONDS);
    } catch (InterruptedException e) {
        task.cancel(true);
        throw new Error("OCSP response retrieval was interrupted while running. This should not happen", e);
    } catch (ExecutionException e) {
        task.cancel(true);
        throw new OcspFailureException("Failure encountered while retrieving OCSP response.", e);
    } catch (TimeoutException e) {
        task.cancel(true);
        throw new CryptoTokenOfflineException("HSM timed out while trying to get OCSP response", e);
    }
    if (log.isDebugEnabled()) {
        log.debug("Signing OCSP response with OCSP signer cert: " + signerCert.getSubjectDN().getName());
    }
    if (!returnval.getResponderId().equals(ocspSigningCacheEntry.getRespId())) {
        log.error("Response responderId does not match signer certificate responderId!");
        throw new OcspFailureException("Response responderId does not match signer certificate responderId!");
    }
    if (!ocspSigningCacheEntry.checkResponseSignatureVerified()) {
        // We only check the response signature the first time for each OcspSigningCacheEntry to detect a misbehaving HSM.
        // The client is still responsible for validating the signature, see RFC 6960 Section 3.2.2
        boolean verify;
        try {
            verify = returnval
                    .isSignatureValid(new JcaContentVerifierProviderBuilder().build(signerCert.getPublicKey()));
        } catch (OperatorCreationException e) {
            // Very fatal error
            throw new EJBException("Can not create Jca content signer: ", e);
        }
        if (verify) {
            if (log.isDebugEnabled()) {
                log.debug("The OCSP response is verifying.");
            }
        } else {
            log.error("The response is NOT verifying! Attempted to sign using "
                    + CertTools.getSubjectDN(signerCert) + " but signature was not valid.");
            throw new OcspFailureException("Attempted to sign using " + CertTools.getSubjectDN(signerCert)
                    + " but signature was not valid.");
        }
    }
    return returnval;
}

From source file:org.ejbca.core.ejb.ca.caadmin.CAAdminSessionBean.java

@Override
public void removeCAKeyStore(AuthenticationToken admin, String caname) throws EJBException {
    if (log.isTraceEnabled()) {
        log.trace(">removeCAKeyStore");
    }//from  w  ww . ja  v  a2  s .c  o m
    try {
        // check authorization
        if (!accessSession.isAuthorizedNoLogging(admin, StandardRules.ROLE_ROOT.resource())) {
            String msg = intres.getLocalizedMessage("caadmin.notauthorizedtoremovecatoken", caname);
            Map<String, Object> details = new LinkedHashMap<String, Object>();
            details.put("msg", msg);
            auditSession.log(EventTypes.ACCESS_CONTROL, EventStatus.FAILURE, ModuleTypes.CA, ServiceTypes.CORE,
                    admin.toString(), null, null, null, details);
        }
        CA ca = caSession.getCAForEdit(admin, caname);
        final CAToken currentCaToken = ca.getCAToken();
        final int cryptoTokenId = currentCaToken.getCryptoTokenId();
        CryptoToken cryptoToken = cryptoTokenSession.getCryptoToken(cryptoTokenId);
        if (!(cryptoToken instanceof SoftCryptoToken)) {
            throw new Exception("Cannot export anything but a soft token.");
        }
        cryptoTokenManagementSession.deactivate(admin, cryptoTokenId);
        // Create a new CAToken with the same properties but without the reference to the removed CryptoToken
        cryptoTokenSession.removeCryptoToken(cryptoTokenId);
        final CAToken newCaToken = new CAToken(0, currentCaToken.getProperties());
        newCaToken.setKeySequence(newCaToken.getKeySequence());
        newCaToken.setKeySequenceFormat(newCaToken.getKeySequenceFormat());
        newCaToken.setSignatureAlgorithm(newCaToken.getSignatureAlgorithm());
        newCaToken.setEncryptionAlgorithm(newCaToken.getEncryptionAlgorithm());
        ca.setCAToken(newCaToken);
        // Set this CA to offline, since it cannot be used without a CryptoToken this is probably intended.
        ca.setStatus(CAConstants.CA_OFFLINE);
        // Save to database
        caSession.editCA(admin, ca, false);
        // Log
        final String detailsMsg = intres.getLocalizedMessage("caadmin.removedcakeystore",
                Integer.valueOf(ca.getCAId()));
        auditSession.log(EjbcaEventTypes.CA_REMOVETOKEN, EventStatus.SUCCESS, ModuleTypes.CA, ServiceTypes.CORE,
                admin.toString(), String.valueOf(ca.getCAId()), null, null, detailsMsg);
    } catch (Exception e) {
        final String detailsMsg = intres.getLocalizedMessage("caadmin.errorremovecakeystore", caname, "PKCS12",
                e.getMessage());
        auditSession.log(EjbcaEventTypes.CA_REMOVETOKEN, EventStatus.FAILURE, ModuleTypes.CA, ServiceTypes.CORE,
                admin.toString(), null, null, null, detailsMsg);
        throw new EJBException(detailsMsg, e);
    }
    if (log.isTraceEnabled()) {
        log.trace("<removeCAKeyStore");
    }
}