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(Exception ex) 

Source Link

Document

Constructs an EJBException that embeds the originally thrown exception.

Usage

From source file:com.egt.ejb.toolkit.ToolKitSessionBean.java

@Override
public void generarPagina() {
    //      List<Aplicacion> aplicaciones = aplicacionFacade.findAll(REFRESH);
    List<Aplicacion> aplicaciones = getAplicaciones();
    List<Pagina> paginas = paginaFacade.findAll(REFRESH);
    try {//from ww w  . j a v a 2s .  com
        for (Pagina pagina : paginas) {
            generarPagina(pagina, aplicaciones);
        }
        TLC.getBitacora().info(Bundle.getString("generar.paginas.ok"), paginas.size());
    } catch (Exception ex) {
        //          TLC.getBitacora().fatal(ex);
        throw ex instanceof EJBException ? (EJBException) ex : new EJBException(ex);
    }
}

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

License:asdf

@Override
public Certificate findCertificateByFingerprint(String fingerprint) {
    if (log.isTraceEnabled()) {
        log.trace(">findCertificateByFingerprint()");
    }//from www. ja v a 2s. co  m
    Certificate ret = null;
    try {
        CertificateData res = CertificateData.findByFingerprint(entityManager, fingerprint);
        if (res != null) {
            ret = res.getCertificate(this.entityManager);
        }
    } catch (Exception e) {
        log.error("Error finding certificate with fp: " + fingerprint);
        throw new EJBException(e);
    }
    if (log.isTraceEnabled()) {
        log.trace("<findCertificateByFingerprint()");
    }
    return ret;
}

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

@TransactionAttribute(TransactionAttributeType.SUPPORTS)
@Override/*from  w w w  .j  a v  a 2 s  . c  o  m*/
public ServiceConfiguration getServiceConfiguration(AuthenticationToken admin, int id) {
    if (log.isTraceEnabled()) {
        log.trace(">getServiceConfiguration: " + id);
    }
    ServiceConfiguration returnval = null;
    try {
        ServiceData serviceData = serviceDataSession.findById(Integer.valueOf(id));
        if (serviceData != null) {
            returnval = serviceData.getServiceConfiguration();
        } else {
            if (log.isDebugEnabled()) {
                log.debug("Returnval is null for service id: " + id);
            }
        }
    } catch (Exception e) {
        // return null if we cant find it, if it is not due to underlying
        // database error
        log.debug("Got an Exception for service with id " + id + ": " + e.getMessage());
        /*
         * If we don't re-throw here it will be treated as the service id
         * does not exist and the service will not be rescheduled to run.
         */
        throw new EJBException(e);
    }
    if (log.isTraceEnabled()) {
        log.trace("<getServiceConfiguration: " + id);
    }
    return returnval;
}

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

@Override
public void createCA(final AuthenticationToken admin, final CAInfo cainfo) throws AuthorizationDeniedException,
        CAExistsException, CryptoTokenOfflineException, InvalidAlgorithmException {
    if (log.isTraceEnabled()) {
        log.trace(">createCA: " + cainfo.getName());
    }/*from w w  w  .  j av a2 s. c  o m*/
    final int caid = cainfo.getCAId();
    // Check that administrator has superadminstrator rights.
    if (!accessSession.isAuthorizedNoLogging(admin, StandardRules.ROLE_ROOT.resource())) {
        final String detailsMsg = intres.getLocalizedMessage("caadmin.notauthorizedtocreateca",
                cainfo.getName());
        auditSession.log(EventTypes.ACCESS_CONTROL, EventStatus.FAILURE, ModuleTypes.CA, ServiceTypes.CORE,
                admin.toString(), String.valueOf(caid), null, null, detailsMsg);
        throw new AuthorizationDeniedException(detailsMsg);
    }
    // Check that CA doesn't already exists
    if (caid >= 0 && caid <= CAInfo.SPECIALCAIDBORDER) {
        final String detailsMsg = intres.getLocalizedMessage("caadmin.wrongcaid", Integer.valueOf(caid));
        auditSession.log(EventTypes.CA_CREATION, EventStatus.FAILURE, ModuleTypes.CA, ServiceTypes.CORE,
                admin.toString(), String.valueOf(caid), null, null, detailsMsg);
        throw new CAExistsException(detailsMsg);
    }
    if (CAData.findById(entityManager, Integer.valueOf(caid)) != null) {
        final String detailsMsg = intres.getLocalizedMessage("caadmin.caexistsid", Integer.valueOf(caid));
        auditSession.log(EventTypes.CA_CREATION, EventStatus.FAILURE, ModuleTypes.CA, ServiceTypes.CORE,
                admin.toString(), String.valueOf(caid), null, null, detailsMsg);
        throw new CAExistsException(detailsMsg);
    }
    if (CAData.findByName(entityManager, cainfo.getName()) != null) {
        final String detailsMsg = intres.getLocalizedMessage("caadmin.caexistsname", cainfo.getName());
        auditSession.log(EventTypes.CA_CREATION, EventStatus.FAILURE, ModuleTypes.CA, ServiceTypes.CORE,
                admin.toString(), String.valueOf(caid), null, null, detailsMsg);
        throw new CAExistsException(detailsMsg);
    }
    // Check if we are creating a CVC CA, and in case we have a unique (issuerDN,serialNumber) index in the database, then fail fast.
    if ((cainfo.getCAType() == CAInfo.CATYPE_CVC)
            && certificateStoreSession.isUniqueCertificateSerialNumberIndex()) {
        throw new IllegalArgumentException(
                "Not possible to create CVC CA when there is a unique (issuerDN, serialNumber) index in the database.");
    }
    // Create CAToken
    final CAToken caToken = cainfo.getCAToken();
    int cryptoTokenId = caToken.getCryptoTokenId();
    final CryptoToken cryptoToken = cryptoTokenSession.getCryptoToken(cryptoTokenId);
    // The certificate profile used for the CAs certificate
    CertificateProfile certprofile = certificateProfileSession
            .getCertificateProfile(cainfo.getCertificateProfileId());
    // Create CA
    CA ca = createCAObject(cainfo, caToken, certprofile);

    if (cainfo.getStatus() != CAConstants.CA_UNINITIALIZED) {
        // See if CA token is OK before storing CA, but skip if no keys can be guaranteed to exist.
        try {
            cryptoToken.testKeyPair(caToken.getAliasFromPurpose(CATokenConstants.CAKEYPURPOSE_KEYTEST));
        } catch (InvalidKeyException e1) {
            throw new RuntimeException("The CA's test key alias points to an invalid key.", e1);
        }
    }
    // Store CA in database, so we can generate keys using the ca token session.
    try {
        caSession.addCA(admin, ca);
    } catch (CAExistsException e) {
        String msg = intres.getLocalizedMessage("caadmin.caexistsid", Integer.valueOf(caid));
        Map<String, Object> details = new LinkedHashMap<String, Object>();
        details.put("msg", msg);
        auditSession.log(EventTypes.CA_CREATION, EventStatus.FAILURE, ModuleTypes.CA, ServiceTypes.CORE,
                admin.toString(), String.valueOf(caid), null, null, details);
        sessionContext.setRollbackOnly(); // This is an application exception so it wont trigger a roll-back automatically
        throw e;
    }

    // Finish up and create certifiate chain etc.
    // Both code paths will audit log.
    if (cainfo.getStatus() != CAConstants.CA_UNINITIALIZED) {
        finalizeInitializedCA(admin, ca, cainfo, cryptoToken, certprofile);
    } else {
        // Special handling for uninitialized CAs
        ca.setCertificateChain(new ArrayList<Certificate>());
        ca.setStatus(CAConstants.CA_UNINITIALIZED);
        if (log.isDebugEnabled()) {
            log.debug("Setting CA status to: " + CAConstants.CA_UNINITIALIZED);
        }
        try {
            caSession.editCA(admin, ca, true);
        } catch (CADoesntExistsException e) {
            final String detailsMsg = intres.getLocalizedMessage("caadmin.canotexistsid",
                    Integer.valueOf(caid));
            auditSession.log(EventTypes.CA_EDITING, EventStatus.FAILURE, ModuleTypes.CA, ServiceTypes.CORE,
                    admin.toString(), String.valueOf(caid), null, null, detailsMsg);
            throw new EJBException(e);
        }
    }

    if (log.isTraceEnabled()) {
        log.trace("<createCA: " + cainfo.getName());
    }
}

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

/**
 * The final steps of creating a CA, which are not performed for uninitialized CAs until
 * they are initialized./*  ww w  .  ja  v a 2 s .co m*/
 * 
 * It creates a certificate chain and publishes certificate, services, CRLs, etc.
 * This method also performs audit logging.
 */
private void finalizeInitializedCA(final AuthenticationToken admin, final CA ca, final CAInfo cainfo,
        final CryptoToken cryptoToken, final CertificateProfile certprofile)
        throws CryptoTokenOfflineException, AuthorizationDeniedException {

    if (cainfo.getStatus() == CAConstants.CA_UNINITIALIZED) {
        throw new IllegalStateException("This method should never be called on uninitialized CAs");
    }

    final int caid = cainfo.getCAId();
    Collection<Certificate> certificatechain = createCertificateChain(admin, ca, cryptoToken, certprofile);
    int castatus = getCaStatus(cainfo);
    ca.setCertificateChain(certificatechain);
    if (log.isDebugEnabled()) {
        log.debug("Setting CA status to: " + castatus);
    }
    ca.setStatus(castatus);
    try {
        caSession.editCA(admin, ca, true);
    } catch (CADoesntExistsException e) {
        final String detailsMsg = intres.getLocalizedMessage("caadmin.canotexistsid", Integer.valueOf(caid));
        auditSession.log(EventTypes.CA_EDITING, EventStatus.FAILURE, ModuleTypes.CA, ServiceTypes.CORE,
                admin.toString(), String.valueOf(caid), null, null, detailsMsg);
        throw new EJBException(e);
    }
    // Publish CA certificates if CA is initialized
    publishCACertificate(admin, ca.getCertificateChain(), ca.getCRLPublishers(), ca.getSubjectDN());
    switch (castatus) {
    case CAConstants.CA_ACTIVE:
        // activate External CA Services
        activateAndPublishExternalCAServices(admin, cainfo.getExtendedCAServiceInfos(), ca);
        try {
            caSession.editCA(admin, ca, false); // store any activates CA services
            // create initial CRLs
            publishingCrlSession.forceCRL(admin, ca.getCAId());
            publishingCrlSession.forceDeltaCRL(admin, ca.getCAId());
        } catch (CADoesntExistsException e) {
            String msg = intres.getLocalizedMessage("caadmin.errorcreateca", cainfo.getName());
            Map<String, Object> details = new LinkedHashMap<String, Object>();
            details.put("msg", msg);
            details.put("error", e.getMessage());
            auditSession.log(EventTypes.CA_CREATION, EventStatus.FAILURE, ModuleTypes.CA, ServiceTypes.CORE,
                    admin.toString(), String.valueOf(caid), null, null, details);
            throw new EJBException(e);
        } catch (CAOfflineException e) {
            String msg = intres.getLocalizedMessage("caadmin.errorcreateca", cainfo.getName());
            Map<String, Object> details = new LinkedHashMap<String, Object>();
            details.put("msg", msg);
            details.put("error", e.getMessage());
            auditSession.log(EventTypes.CA_CREATION, EventStatus.FAILURE, ModuleTypes.CA, ServiceTypes.CORE,
                    admin.toString(), String.valueOf(caid), null, null, details);
            throw new EJBException(e);
        }
        break;
    default:
        log.error(
                "CA status not active when creating CA, extended services not created. CA status: " + castatus);
        break;
    }

    // Update local OCSP's CA certificate cache
    certificateStoreSession.reloadCaCertificateCache();
}

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

License:asdf

@Override
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public void revokeAllCertByCA(AuthenticationToken admin, String issuerdn, int reason)
        throws AuthorizationDeniedException {
    int revoked = 0;

    // Must be authorized to CA in order to change status is certificates issued by the CA
    String bcdn = CertTools.stringToBCDNString(issuerdn);
    int caid = bcdn.hashCode();
    authorizedToCA(admin, caid);/*  w  ww.  j  a va  2  s  . c  o  m*/

    try {
        final int maxRows = 10000;
        int firstResult = 0;
        // Revoking all non revoked certificates.

        // Update 10000 records at a time
        firstResult = 0;
        List<CertificateData> list = CertificateData.findAllNonRevokedCertificates(entityManager, bcdn,
                firstResult, maxRows);
        while (list.size() > 0) {
            for (int i = 0; i < list.size(); i++) {
                CertificateData d = list.get(i);
                d.setStatus(CertificateConstants.CERT_REVOKED);
                d.setRevocationDate(System.currentTimeMillis());
                d.setRevocationReason(reason);
                revoked++;
            }
            firstResult += maxRows;
            list = CertificateData.findAllNonRevokedCertificates(entityManager, bcdn, firstResult, maxRows);
        }
        final String msg = INTRES.getLocalizedMessage("store.revokedallbyca", issuerdn,
                Integer.valueOf(revoked), Integer.valueOf(reason));
        Map<String, Object> details = new LinkedHashMap<String, Object>();
        details.put("msg", msg);
        logSession.log(EventTypes.CERT_REVOKED, EventStatus.SUCCESS, ModuleTypes.CERTIFICATE, ServiceTypes.CORE,
                admin.toString(), String.valueOf(caid), null, null, details);
    } catch (Exception e) {
        final String msg = INTRES.getLocalizedMessage("store.errorrevokeallbyca", issuerdn);
        log.info(msg);
        throw new EJBException(e);
    }
}

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

private Collection<Certificate> createCertificateChain(AuthenticationToken authenticationToken, CA ca,
        CryptoToken cryptoToken, CertificateProfile certprofile) throws CryptoTokenOfflineException {
    final CAInfo cainfo = ca.getCAInfo();
    final CAToken caToken = cainfo.getCAToken();
    Collection<Certificate> certificatechain = null;
    final String sequence = caToken.getKeySequence(); // get from CAtoken to make sure it is fresh
    final String aliasCertSign = caToken.getAliasFromPurpose(CATokenConstants.CAKEYPURPOSE_CERTSIGN);
    int caid = cainfo.getCAId();
    if (cainfo.getSignedBy() == CAInfo.SELFSIGNED) {
        try {//  ww  w . j a  v a2 s. c  om
            // create selfsigned certificate
            Certificate cacertificate = null;
            if (log.isDebugEnabled()) {
                log.debug("CAAdminSessionBean : " + cainfo.getSubjectDN());
            }
            EndEntityInformation cadata = makeEndEntityInformation(cainfo);
            cacertificate = ca.generateCertificate(cryptoToken, cadata, cryptoToken.getPublicKey(aliasCertSign),
                    -1, null, cainfo.getValidity(), certprofile, sequence);
            if (log.isDebugEnabled()) {
                log.debug("CAAdminSessionBean : " + CertTools.getSubjectDN(cacertificate));
            }
            // Build Certificate Chain
            certificatechain = new ArrayList<Certificate>();
            certificatechain.add(cacertificate);
            // set status to active

        } catch (CryptoTokenOfflineException e) {
            final String detailsMsg = intres.getLocalizedMessage("error.catokenoffline", cainfo.getName());
            auditSession.log(EventTypes.CA_CREATION, EventStatus.FAILURE, ModuleTypes.CA, ServiceTypes.CORE,
                    authenticationToken.toString(), String.valueOf(caid), null, null, detailsMsg);
            sessionContext.setRollbackOnly(); // This is an application exception so it wont trigger a roll-back automatically
            throw e;
        } catch (Exception fe) {
            String msg = intres.getLocalizedMessage("caadmin.errorcreateca", cainfo.getName());
            Map<String, Object> details = new LinkedHashMap<String, Object>();
            details.put("msg", msg);
            details.put("error", fe.getMessage());
            auditSession.log(EventTypes.CA_CREATION, EventStatus.FAILURE, ModuleTypes.CA, ServiceTypes.CORE,
                    authenticationToken.toString(), String.valueOf(caid), null, null, details);
            throw new EJBException(fe);
        }
    } else if (cainfo.getSignedBy() == CAInfo.SIGNEDBYEXTERNALCA) {
        certificatechain = new ArrayList<Certificate>();

    } else if (cainfo.getSignedBy() > CAInfo.SPECIALCAIDBORDER || cainfo.getSignedBy() < 0) {
        // Create CA signed by other internal CA.
        try {
            final CA signca = caSession.getCAForEdit(authenticationToken,
                    Integer.valueOf(cainfo.getSignedBy()));
            // Check that the signer is valid
            assertSignerValidity(authenticationToken, signca);
            // Create CA certificate
            EndEntityInformation cadata = makeEndEntityInformation(cainfo);
            CryptoToken signCryptoToken = cryptoTokenSession
                    .getCryptoToken(signca.getCAToken().getCryptoTokenId());
            Certificate cacertificate = signca.generateCertificate(signCryptoToken, cadata,
                    cryptoToken.getPublicKey(aliasCertSign), -1, null, cainfo.getValidity(), certprofile,
                    sequence);
            // Build Certificate Chain
            Collection<Certificate> rootcachain = signca.getCertificateChain();
            certificatechain = new ArrayList<Certificate>();
            certificatechain.add(cacertificate);
            certificatechain.addAll(rootcachain);
            // set status to active

        } catch (CryptoTokenOfflineException e) {
            final String detailsMsg = intres.getLocalizedMessage("error.catokenoffline", cainfo.getName());
            auditSession.log(EventTypes.CA_CREATION, EventStatus.FAILURE, ModuleTypes.CA, ServiceTypes.CORE,
                    authenticationToken.toString(), String.valueOf(caid), null, null, detailsMsg);
            sessionContext.setRollbackOnly(); // This is an application exception so it wont trigger a roll-back automatically
            throw e;
        } catch (Exception fe) {
            String msg = intres.getLocalizedMessage("caadmin.errorcreateca", cainfo.getName());
            Map<String, Object> details = new LinkedHashMap<String, Object>();
            details.put("msg", msg);
            details.put("error", fe.getMessage());
            auditSession.log(EventTypes.CA_CREATION, EventStatus.FAILURE, ModuleTypes.CA, ServiceTypes.CORE,
                    authenticationToken.toString(), String.valueOf(caid), null, null, details);
            throw new EJBException(fe);
        }
    }
    return certificatechain;

}

From source file:com.egt.ejb.toolkit.ToolKitSessionBean.java

private void write(VelocityContext context, String tempname, String filename) throws Exception {
    try {/*from  ww  w  . j  ava 2s  . c o  m*/
        VelocityEngineer.write(context, tempname, filename);
        //      } catch (ResourceNotFoundException ex) {
        //          String msg = ex.getClass().getSimpleName() + "(" + tempname + "," + filename + ")";
        //          Bitacora.logError(msg, ex);
    } catch (Exception ex) {
        throw ex instanceof EJBException ? (EJBException) ex : new EJBException(ex);
    }
}

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

@Override
public void cleanUserCertDataSN(UserDataVO data) throws ObjectNotFoundException {
    if (log.isTraceEnabled()) {
        log.trace(">cleanUserCertDataSN: " + data.getUsername());
    }/*from  w  ww  . j a  va2 s . c o  m*/
    // This admin can be the public web user, which may not be allowed to
    // change status,
    // this is a bit ugly, but what can a man do...
    Admin statusadmin = Admin.getInternalAdmin();
    try {
        cleanUserCertDataSN(statusadmin, data.getUsername());
    } catch (FinderException e) {
        String msg = intres.getLocalizedMessage("authentication.usernotfound", data.getUsername());
        logSession.log(statusadmin, statusadmin.getCaId(), LogConstants.MODULE_CA, new Date(),
                data.getUsername(), null, LogConstants.EVENT_INFO_USERAUTHENTICATION, msg);
        throw new ObjectNotFoundException(e.getMessage());
    } catch (AuthorizationDeniedException e) {
        // Should never happen
        log.error("AuthorizationDeniedException: ", e);
        throw new EJBException(e);
    } catch (ApprovalException e) {
        // Should never happen
        log.error("ApprovalException: ", e);
        throw new EJBException(e);
    } catch (WaitingForApprovalException e) {
        // Should never happen
        log.error("ApprovalException: ", e);
        throw new EJBException(e);
    }
    if (log.isTraceEnabled()) {
        log.trace("<cleanUserCertDataSN: " + data.getUsername());
    }
}

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

License:asdf

@Override
public boolean isRevoked(String issuerDN, BigInteger serno) {
    if (log.isTraceEnabled()) {
        log.trace(">isRevoked(), dn:" + issuerDN + ", serno=" + serno.toString(16));
    }/*from  w w  w.j a v  a  2s . co  m*/
    // First make a DN in our well-known format
    String dn = CertTools.stringToBCDNString(issuerDN);
    boolean ret = false;
    try {
        Collection<CertificateData> coll = CertificateData.findByIssuerDNSerialNumber(entityManager, dn,
                serno.toString());
        if (coll.size() > 0) {
            if (coll.size() > 1) {
                final String msg = INTRES.getLocalizedMessage("store.errorseveralissuerserno", issuerDN,
                        serno.toString(16));
                log.error(msg);
            }
            Iterator<CertificateData> iter = coll.iterator();
            while (iter.hasNext()) {
                CertificateData data = iter.next();
                // if any of the certificates with this serno is revoked, return true
                if (data.getStatus() == CertificateConstants.CERT_REVOKED) {
                    ret = true;
                    break;
                }
            }
        } else {
            // If there are no certificates with this serial number, return true (=revoked). Better safe than sorry!
            ret = true;
            if (log.isTraceEnabled()) {
                log.trace("isRevoked() did not find certificate with dn " + dn + " and serno "
                        + serno.toString(16));
            }
        }
    } catch (Exception e) {
        throw new EJBException(e);
    }
    if (log.isTraceEnabled()) {
        log.trace("<isRevoked() returned " + ret);
    }
    return ret;
}