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:org.cesecore.certificates.certificate.CertificateStoreSessionBean.java

License:asdf

@Override
public CertificateStatus getStatus(String issuerDN, BigInteger serno) {
    if (log.isTraceEnabled()) {
        log.trace(">getStatus(), dn:" + issuerDN + ", serno=" + serno.toString(16));
    }//  w  ww .  j  a va  2s . com
    // First make a DN in our well-known format
    final String dn = CertTools.stringToBCDNString(issuerDN);

    try {
        Collection<CertificateData> coll = CertificateData.findByIssuerDNSerialNumber(entityManager, dn,
                serno.toString());
        if (coll.size() > 1) {
            final String msg = INTRES.getLocalizedMessage("store.errorseveralissuerserno", issuerDN,
                    serno.toString(16));
            log.error(msg);
        }

        for (CertificateData data : coll) {
            final CertificateStatus result = getCertificateStatus(data);
            if (log.isTraceEnabled()) {
                log.trace("<getStatus() returned " + result + " for cert number " + serno.toString(16));
            }
            return result;
        }
        if (log.isTraceEnabled()) {
            log.trace(
                    "<getStatus() did not find certificate with dn " + dn + " and serno " + serno.toString(16));
        }
    } catch (Exception e) {
        throw new EJBException(e);
    }
    return CertificateStatus.NOT_AVAILABLE;
}

From source file:edu.harvard.iq.dvn.core.study.StudyServiceBean.java

public void exportStudyFilesToLegacySystem(String lastUpdateTime, String authority) {
    // Get list of studies that have been updated yesterday,
    // and export them to legacy VDC system

    Logger logger = null;//from   www.  j a v  a  2 s .co  m

    String exportLogDirStr = System.getProperty("vdc.export.log.dir");
    if (exportLogDirStr == null) {
        System.out.println("Missing system property: vdc.export.log.dir.  Please add to JVM options");
        return;
    }
    File exportLogDir = new File(exportLogDirStr);
    if (!exportLogDir.exists()) {
        exportLogDir.mkdir();
    }

    logger = Logger.getLogger("edu.harvard.iq.dvn.core.web.servlet.VDCExportServlet");

    // Everytime export runs, we want to write to a separate log file (handler).
    // So if export has run previously, remove the previous handler
    if (logger.getHandlers() != null && logger.getHandlers().length > 0) {
        int numHandlers = logger.getHandlers().length;
        for (int i = 0; i < numHandlers; i++) {
            logger.removeHandler(logger.getHandlers()[i]);
        }
    }

    SimpleDateFormat formatter = new SimpleDateFormat("yyyy_MM_dd");
    FileHandler handler = null;
    try {
        handler = new FileHandler(
                exportLogDirStr + File.separator + "export_" + formatter.format(new Date()) + ".log");
    } catch (IOException e) {
        throw new EJBException(e);
    }

    // Add handler to the desired logger
    logger.addHandler(handler);

    logger.info("Begin Exporting Studies");
    int studyCount = 0;
    int deletedStudyCount = 0;
    try {

        /* THIS IS LEGACY CODE AND SHOULD BE DELETED
        // For all studies that have been deleted in the dataverse since last export, remove study directory in VDC
                
        String query = "SELECT s from DeletedStudy s where s.authority = '" + authority + "' ";
        List deletedStudies = em.createQuery(query).getResultList();
        for (Iterator it = deletedStudies.iterator(); it.hasNext();) {
        DeletedStudy deletedStudy = (DeletedStudy) it.next();
                
        logger.info("Deleting study " + deletedStudy.getGlobalId());
        Study study = em.find(Study.class, deletedStudy.getId());
        File legacyStudyDir = new File(FileUtil.getLegacyFileDir() + File.separatorChar + study.getAuthority() + File.separatorChar + study.getStudyId());
                
        // Remove files in the directory, then delete the directory.
        File[] studyFiles = legacyStudyDir.listFiles();
        if (studyFiles != null) {
            for (int i = 0; i < studyFiles.length; i++) {
                studyFiles[i].delete();
            }
        }
        legacyStudyDir.delete();
        deletedStudyCount++;
                
        em.remove(deletedStudy);
        }
        */

        // Do export of all studies updated at "lastUpdateTime""

        if (authority == null) {
            authority = vdcNetworkService.find().getAuthority();
        }
        String beginTime = null;
        String endTime = null;
        if (lastUpdateTime == null) {
            Calendar cal = Calendar.getInstance();
            cal.add(Calendar.DAY_OF_YEAR, -1);
            beginTime = new SimpleDateFormat("yyyy-MM-dd").format(cal.getTime()); // Use yesterday as default value
            cal.add(Calendar.DAY_OF_YEAR, 1);
            endTime = new SimpleDateFormat("yyyy-MM-dd").format(cal.getTime());
        } else {
            beginTime = lastUpdateTime;
            Date date = new SimpleDateFormat("yyyy-MM-dd").parse(lastUpdateTime);
            Calendar cal = Calendar.getInstance();
            cal.setTime(date);
            cal.add(Calendar.DAY_OF_YEAR, 1);
            endTime = new SimpleDateFormat("yyyy-MM-dd").format(cal.getTime());
        }
        String query = "SELECT s from Study s where s.authority = '" + authority + "' ";
        query += " and s.lastUpdateTime >'" + beginTime + "'";
        //    query+=" and s.lastUpdateTime <'" +endTime+"'";
        query += " order by s.studyId";
        List updatedStudies = em.createQuery(query).getResultList();

        for (Iterator it = updatedStudies.iterator(); it.hasNext();) {
            Study study = (Study) it.next();
            logger.info("Exporting study " + study.getStudyId());

            exportStudyToLegacySystem(study, authority);
            studyCount++;

        }
    } catch (Exception e) {
        logger.severe(e.getMessage());

        String stackTrace = "StackTrace: \n";
        logger.severe("Exception caused by: " + e + "\n");
        StackTraceElement[] ste = e.getStackTrace();
        for (int m = 0; m < ste.length; m++) {
            stackTrace += ste[m].toString() + "\n";
        }
        logger.severe(stackTrace);
    }

    logger.info("End export, " + studyCount + " studies successfully exported, " + deletedStudyCount
            + " studies deleted.");
}

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

@Override
public void cleanUserCertDataSN(EndEntityInformation data) throws ObjectNotFoundException {
    if (log.isTraceEnabled()) {
        log.trace(">cleanUserCertDataSN: " + data.getUsername());
    }/* w ww.j  a  v a2 s .c  o m*/
    try {
        cleanUserCertDataSN(data.getUsername());
    } catch (FinderException e) {
        String msg = intres.getLocalizedMessage("authentication.usernotfound", data.getUsername());
        log.info(msg);
        throw new ObjectNotFoundException(e.getMessage());
    } catch (ApprovalException e) {
        // Should never happen
        log.error("ApprovalException: ", e);
        throw new EJBException(e);
    } catch (WaitingForApprovalException e) {
        // Should never happen
        log.error("WaitingForApprovalException: ", e);
        throw new EJBException(e);
    }
    if (log.isTraceEnabled()) {
        log.trace("<cleanUserCertDataSN: " + data.getUsername());
    }
}

From source file:edu.harvard.iq.dvn.core.study.StudyServiceBean.java

private void exportStudyToLegacySystem(Study study, String authority) throws IOException, JAXBException {

    throw new EJBException("This feature is no longer supported!!");
    /*/*from  w  w  w. jav a 2 s  .c o  m*/
    // For each study
    // update study file locations for legacy system
    // Write ddi to an output stream
    // If data file dir exists, delete everything from it
    // copy ddi to study.xml,
    // copy study files.
    File studyDir = new File(FileUtil.getStudyFileDir() + File.separatorChar + authority + File.separatorChar + study.getStudyId());
    File legacyStudyDir = new File(FileUtil.getLegacyFileDir() + File.separatorChar + authority + File.separatorChar + study.getStudyId());
            
    // If the directory exists in the legacy system, then clear out all the files contained in it
    if (legacyStudyDir.exists() && legacyStudyDir.isDirectory()) {
    File[] files = legacyStudyDir.listFiles();
    for (int i = 0; i < files.length; i++) {
    files[i].delete();
    }
    } else {
    legacyStudyDir.mkdirs();
    }
            
    // Export the study to study.xml in the legacy directory
    FileWriter fileWriter = new FileWriter(new File(legacyStudyDir, "study.xml"));
    try {
    ddiService.exportStudy(study, fileWriter, true, true);
    fileWriter.flush();
    } finally {
    fileWriter.close();
    }
            
    // Copy all the study files to the legacy directory
            
    for (Iterator it = study.getStudyFiles().iterator(); it.hasNext();) {
    StudyFile studyFile = (StudyFile) it.next();
    FileUtil.copyFile(new File(studyDir, studyFile.getFileSystemName()), new File(legacyStudyDir, studyFile.getFileSystemName()));
    }
     */

}

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

@Override
public void editCA(AuthenticationToken admin, CAInfo cainfo) throws AuthorizationDeniedException {
    boolean xkmsrenewcert = false;
    boolean cmsrenewcert = false;
    final int caid = cainfo.getCAId();
    // Check authorization
    if (!accessSession.isAuthorizedNoLogging(admin, StandardRules.ROLE_ROOT.resource())) {
        String msg = intres.getLocalizedMessage("caadmin.notauthorizedtoeditca", cainfo.getName());
        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(), String.valueOf(caid), null, null, details);
        throw new AuthorizationDeniedException(msg);
    }//from ww w. j ava  2  s .  c om

    // In uninitialized CAs, the Subject DN might change, and then
    // we need to update the CA ID as well.
    if (cainfo.getStatus() == CAConstants.CA_UNINITIALIZED) {
        int calculatedCAId = CertTools.stringToBCDNString(cainfo.getSubjectDN()).hashCode();
        int currentCAId = cainfo.getCAId();
        if (calculatedCAId != currentCAId) {
            caSession.removeCA(admin, currentCAId);
            cainfo.setCAId(calculatedCAId);
            updateCAIds(admin, currentCAId, calculatedCAId, cainfo.getSubjectDN());
            rebuildExtendedServices(admin, cainfo);
            try {
                createCA(admin, cainfo);
            } catch (CAExistsException e) {
                throw new IllegalStateException(e);
            } catch (CryptoTokenOfflineException e) {
                throw new IllegalStateException(e);
            } catch (InvalidAlgorithmException e) {
                throw new IllegalStateException(e);
            }
        }
    }

    // Check if extended service certificates are about to be renewed.
    if (cainfo.getStatus() != CAConstants.CA_UNINITIALIZED) {
        final Collection<ExtendedCAServiceInfo> extendedCAServiceInfos = cainfo.getExtendedCAServiceInfos();
        if (extendedCAServiceInfos != null) {
            for (final ExtendedCAServiceInfo extendedCAServiceInfo : extendedCAServiceInfos) {
                if (extendedCAServiceInfo instanceof XKMSCAServiceInfo) {
                    final BaseSigningCAServiceInfo signingInfo = (BaseSigningCAServiceInfo) extendedCAServiceInfo;
                    xkmsrenewcert = signingInfo.getRenewFlag() || (signingInfo.getCertificatePath() == null
                            && signingInfo.getStatus() == ExtendedCAServiceInfo.STATUS_ACTIVE);
                } else if (extendedCAServiceInfo instanceof CmsCAServiceInfo) {
                    final BaseSigningCAServiceInfo signingInfo = (BaseSigningCAServiceInfo) extendedCAServiceInfo;
                    cmsrenewcert = signingInfo.getRenewFlag() || (signingInfo.getCertificatePath() == null
                            && signingInfo.getStatus() == ExtendedCAServiceInfo.STATUS_ACTIVE);
                }
            }
        }
    }

    // Get CA from database
    try {
        caSession.editCA(admin, cainfo);
        CA ca = caSession.getCA(admin, cainfo.getCAId());
        if (cainfo.getStatus() != CAConstants.CA_UNINITIALIZED) {
            // No OCSP Certificate exists that can be renewed.
            if (xkmsrenewcert) {
                XKMSCAServiceInfo info = (XKMSCAServiceInfo) ca
                        .getExtendedCAServiceInfo(ExtendedCAServiceTypes.TYPE_XKMSEXTENDEDSERVICE);
                // Publish the extended service certificate, but only for active services
                if (info.getStatus() == ExtendedCAServiceInfo.STATUS_ACTIVE) {
                    final ArrayList<Certificate> xkmscertificate = new ArrayList<Certificate>();
                    xkmscertificate.add(info.getCertificatePath().get(0));
                    publishCACertificate(admin, xkmscertificate, ca.getCRLPublishers(), ca.getSubjectDN());
                }
            }
            if (cmsrenewcert) {
                CmsCAServiceInfo info = (CmsCAServiceInfo) ca
                        .getExtendedCAServiceInfo(ExtendedCAServiceTypes.TYPE_CMSEXTENDEDSERVICE);
                if (info.getStatus() == ExtendedCAServiceInfo.STATUS_ACTIVE) {
                    final ArrayList<Certificate> cmscertificate = new ArrayList<Certificate>();
                    cmscertificate.add(info.getCertificatePath().get(0));
                    // Publish the extended service certificate, but only for active services
                    publishCACertificate(admin, cmscertificate, ca.getCRLPublishers(), ca.getSubjectDN());
                }
            }
        }
        // Log Action was done by caSession
    } catch (Exception fe) {
        String msg = intres.getLocalizedMessage("caadmin.erroreditca", cainfo.getName());
        log.error(msg, fe);
        Map<String, Object> details = new LinkedHashMap<String, Object>();
        details.put("msg", msg);
        auditSession.log(EventTypes.CA_EDITING, EventStatus.FAILURE, ModuleTypes.CA, ServiceTypes.CORE,
                admin.toString(), String.valueOf(caid), null, null, details);
        throw new EJBException(fe);
    }
}

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

/**
 * Sets a password, hashed or clear text, for a user.
 * //from   w  ww  .j ava 2s.  c  o m
 * @param admin the administrator pwrforming the action
 * @param username the unique username.
 * @param password the new password to be stored in clear text. Setting
 *            password to 'null' effectively deletes any previous clear
 *            text password.
 * @param cleartext true gives cleartext password, false hashed
 */
private void setPassword(final Admin admin, final String username, final String password,
        final boolean cleartext)
        throws UserDoesntFullfillEndEntityProfile, AuthorizationDeniedException, FinderException {
    if (log.isTraceEnabled()) {
        log.trace(">setPassword(" + username + ", hiddenpwd), " + cleartext);
    }
    // Find user
    String newpasswd = password;
    final UserData data = UserData.findByUsername(entityManager, username);
    if (data == null) {
        throw new FinderException("Could not find user " + username);
    }
    final int caid = data.getCaId();
    final String dn = data.getSubjectDN();
    final int endEntityProfileId = data.getEndEntityProfileId();

    final EndEntityProfile profile = endEntityProfileSession.getEndEntityProfile(admin, endEntityProfileId);

    if (profile.useAutoGeneratedPasswd()) {
        newpasswd = profile.getAutoGeneratedPasswd();
    }
    if (getGlobalConfiguration(admin).getEnableEndEntityProfileLimitations()) {
        // Check if user fulfills it's profile.
        try {
            profile.doesPasswordFulfillEndEntityProfile(password, true);
        } catch (UserDoesntFullfillEndEntityProfile ufe) {
            final String msg = intres.getLocalizedMessage("ra.errorfullfillprofile",
                    Integer.valueOf(endEntityProfileId), dn, ufe.getMessage());
            logSession.log(admin, caid, LogConstants.MODULE_RA, new Date(), username, null,
                    LogConstants.EVENT_INFO_CHANGEDENDENTITY, msg);
            throw ufe;
        }
        // Check if administrator is authorized to edit user.
        assertAuthorizedToEndEntityProfile(admin, data.getEndEntityProfileId(),
                AccessRulesConstants.EDIT_RIGHTS, caid, username, LogConstants.EVENT_INFO_CHANGEDENDENTITY);
    }
    assertAuthorizedToCA(admin, caid, username, LogConstants.EVENT_INFO_CHANGEDENDENTITY);
    try {
        final Date now = new Date();
        if ((newpasswd == null) && (cleartext)) {
            data.setClearPassword("");
            data.setTimeModified(now.getTime());
        } else {
            if (cleartext) {
                data.setOpenPassword(newpasswd);
            } else {
                data.setPassword(newpasswd);
            }
            data.setTimeModified(now.getTime());
        }
        final String msg = intres.getLocalizedMessage("ra.editpwdentity", username);
        logSession.log(admin, caid, LogConstants.MODULE_RA, now, username, null,
                LogConstants.EVENT_INFO_CHANGEDENDENTITY, msg);
    } catch (NoSuchAlgorithmException nsae) {
        log.error("NoSuchAlgorithmException while setting password for user " + username);
        throw new EJBException(nsae);
    }
    if (log.isTraceEnabled()) {
        log.trace("<setPassword(" + username + ", hiddenpwd), " + cleartext);
    }
}

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

@Override
public boolean verifyPassword(Admin admin, String username, String password)
        throws UserDoesntFullfillEndEntityProfile, AuthorizationDeniedException, FinderException {
    if (log.isTraceEnabled()) {
        log.trace(">verifyPassword(" + username + ", hiddenpwd)");
    }/*  w  w  w . j  a  v  a2 s. c  o m*/
    boolean ret = false;
    // Find user
    UserData data = UserData.findByUsername(entityManager, username);
    if (data == null) {
        throw new FinderException("Could not find user " + username);
    }
    int caid = data.getCaId();
    if (getGlobalConfiguration(admin).getEnableEndEntityProfileLimitations()) {
        // Check if administrator is authorized to edit user.
        assertAuthorizedToEndEntityProfile(admin, data.getEndEntityProfileId(),
                AccessRulesConstants.EDIT_RIGHTS, caid, username, LogConstants.EVENT_INFO_CHANGEDENDENTITY);
    }
    assertAuthorizedToCA(admin, caid, username, LogConstants.EVENT_INFO_CHANGEDENDENTITY);
    try {
        ret = data.comparePassword(password);
    } catch (NoSuchAlgorithmException nsae) {
        log.debug("NoSuchAlgorithmException while verifying password for user " + username);
        throw new EJBException(nsae);
    }
    if (log.isTraceEnabled()) {
        log.trace("<verifyPassword(" + username + ", hiddenpwd)");
    }
    return ret;
}

From source file:edu.harvard.iq.dvn.core.study.StudyServiceBean.java

public Study getStudyByGlobalId(String identifier) {
    String protocol = null;/*from   w w  w.  j  a  va 2 s  .c  o  m*/
    String authority = null;
    String studyId = null;
    int index1 = identifier.indexOf(':');
    int index2 = identifier.indexOf('/');
    int index3 = 0;
    if (index1 == -1) {
        throw new EJBException("Error parsing identifier: " + identifier + ". ':' not found in string");
    } else {
        protocol = identifier.substring(0, index1);
    }
    if (index2 == -1) {
        throw new EJBException("Error parsing identifier: " + identifier + ". '/' not found in string");

    } else {
        authority = identifier.substring(index1 + 1, index2);
    }
    if (protocol.equals("doi")) {
        index3 = identifier.indexOf('/', index2 + 1);
        if (index3 == -1) {
            studyId = identifier.substring(index2 + 1).toUpperCase();
        } else {
            authority = identifier.substring(index1 + 1, index3);
            studyId = identifier.substring(index3 + 1).toUpperCase();
        }
    } else {
        studyId = identifier.substring(index2 + 1).toUpperCase();
    }

    String queryStr = "SELECT s from Study s where s.studyId = :studyId  and s.protocol= :protocol and s.authority= :authority";

    Study study = null;
    try {
        Query query = em.createQuery(queryStr);
        query.setParameter("studyId", studyId);
        query.setParameter("protocol", protocol);
        query.setParameter("authority", authority);
        study = (Study) query.getSingleResult();
    } catch (javax.persistence.NoResultException e) {
        // DO nothing, just return null.
    }
    return study;
}

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

@Override
public byte[] makeRequest(AuthenticationToken authenticationToken, int caid, Collection<?> certChain,
        String nextSignKeyAlias)/*from www  .  j ava  2  s.com*/
        throws AuthorizationDeniedException, CertPathValidatorException, CryptoTokenOfflineException {
    if (log.isTraceEnabled()) {
        log.trace(">makeRequest: " + caid + ", certChain=" + certChain + ", nextSignKeyAlias="
                + nextSignKeyAlias);
    }
    byte[] returnval = null;
    if (!accessSession.isAuthorizedNoLogging(authenticationToken, AccessRulesConstants.REGULAR_RENEWCA)) {
        final String detailsMsg = intres.getLocalizedMessage("caadmin.notauthorizedtocertreq",
                Integer.valueOf(caid));
        auditSession.log(EventTypes.ACCESS_CONTROL, EventStatus.FAILURE, ModuleTypes.CA, ServiceTypes.CORE,
                authenticationToken.toString(), String.valueOf(caid), null, null, detailsMsg);
        throw new AuthorizationDeniedException(detailsMsg);
    }
    try {
        final CA ca = caSession.getCAForEdit(authenticationToken, caid);
        final List<Certificate> chain = new ArrayList<Certificate>();
        if (certChain != null && certChain.size() > 0) {
            chain.addAll(CertTools.createCertChain(certChain));
            log.debug("Setting request certificate chain of size: " + chain.size());
            ca.setRequestCertificateChain(chain);
        }
        // AR+ patch to make SPOC independent of external CVCA certificates for automatic renewals
        // i.e. if we don't pass a CA certificate as parameter we try to find a suitable CA certificate in the database, among existing CAs
        // (can be a simple imported CA-certificate of external CA)
        if (chain.isEmpty() && ca.getCAType() == CAInfo.CATYPE_CVC
                && ca.getSignedBy() == CAInfo.SIGNEDBYEXTERNALCA && ca.getStatus() == CAConstants.CA_ACTIVE) {
            final CardVerifiableCertificate dvcert = (CardVerifiableCertificate) ca.getCACertificate();
            final String ca_ref = dvcert.getCVCertificate().getCertificateBody().getAuthorityReference()
                    .getConcatenated();
            log.debug("DV renewal missing CVCA cert, try finding CA for:" + ca_ref);
            for (final Integer availableCaId : caSession.getAuthorizedCaIds(authenticationToken)) {
                final CA cvca = caSession.getCA(authenticationToken, availableCaId);
                if (cvca.getCAType() == CAInfo.CATYPE_CVC && cvca.getSignedBy() == CAInfo.SELFSIGNED) {
                    final CardVerifiableCertificate cvccert = (CardVerifiableCertificate) cvca
                            .getCACertificate();
                    if (ca_ref.equals(cvccert.getCVCertificate().getCertificateBody().getHolderReference()
                            .getConcatenated())) {
                        log.debug("Added missing CVCA to rewnewal request: " + cvca.getName());
                        chain.add(cvccert);
                        break;
                    }
                }
            }
            if (chain.isEmpty()) {
                log.info("Failed finding suitable CVCA, forgot to import it?");
            }
        }
        // AR-

        // Generate new certificate signing request.
        final CAToken caToken = ca.getCAToken();
        final String signatureAlgorithm = caToken.getSignatureAlgorithm();
        if (log.isDebugEnabled()) {
            log.debug("Using signing algorithm: " + signatureAlgorithm + " for the CSR.");
        }
        final Properties oldprop = caToken.getProperties();
        final String oldsequence = caToken.getKeySequence();
        // If no alias is supplied we use the CAs current signature key and the KeySequence to generate a new one
        if (nextSignKeyAlias == null || nextSignKeyAlias.length() == 0) {
            nextSignKeyAlias = caToken.generateNextSignKeyAlias();
        }
        caToken.setNextCertSignKey(nextSignKeyAlias);
        final int cryptoTokenId = caToken.getCryptoTokenId();
        try {
            // Test if key already exists
            cryptoTokenManagementSession.testKeyPair(authenticationToken, cryptoTokenId, nextSignKeyAlias);
        } catch (Exception e) {
            try {
                final String currentSignKeyAlias = caToken
                        .getAliasFromPurpose(CATokenConstants.CAKEYPURPOSE_CERTSIGN);
                cryptoTokenManagementSession.createKeyPairWithSameKeySpec(authenticationToken, cryptoTokenId,
                        currentSignKeyAlias, nextSignKeyAlias);
                // Audit log CA key generation
                final Map<String, Object> details = new LinkedHashMap<String, Object>();
                details.put("msg", intres.getLocalizedMessage("catoken.generatedkeys", caid, true, false));
                details.put("oldproperties", oldprop);
                details.put("oldsequence", oldsequence);
                details.put("properties", caToken.getProperties());
                details.put("sequence", caToken.getKeySequence());
                auditSession.log(EventTypes.CA_KEYGEN, EventStatus.SUCCESS, ModuleTypes.CA, ServiceTypes.CORE,
                        authenticationToken.toString(), String.valueOf(caid), null, null, details);

            } catch (AuthorizationDeniedException e2) {
                throw e2;
            } catch (CryptoTokenOfflineException e2) {
                throw e2;
            } catch (Exception e2) {
                throw new RuntimeException(e2);
            }
        }
        ca.setCAToken(caToken);
        // The CA certificate signing this request is the first in the certificate chain
        final Certificate caCert = chain.size() == 0 ? null : chain.get(0);
        final CryptoToken cryptoToken = cryptoTokenManagementSession.getCryptoToken(cryptoTokenId);
        byte[] request = ca.createRequest(cryptoToken, null, signatureAlgorithm, caCert,
                CATokenConstants.CAKEYPURPOSE_CERTSIGN_NEXT);
        if (ca.getCAType() == CAInfo.CATYPE_CVC) {
            /*
             * If this is a CVC CA renewal request, we need to sign it to make an authenticated
             * request. The CVC CAs current signing certificate will always be the right one,
             * because it is the "previous" signing certificate until we have imported a new
             * one as response to the request we create here.
             */
            // Sign the request with the current sign key making it an CVCAuthenticatedRequest
            final byte[] authCertSignRequest = ca.createAuthCertSignRequest(cryptoToken, request);
            if (authCertSignRequest != null) {
                returnval = authCertSignRequest;
            } else {
                // This is expected if we try to generate another CSR from a CA which has not yet recieved a response.
                log.debug("Unable to create authorization signature on CSR. Returning a regular request.");
                returnval = request;
            }
        } else {
            returnval = request;
        }
        caSession.editCA(authenticationToken, ca, true);
        // Log information about the event
        final String detailsMsg = intres.getLocalizedMessage("caadmin.certreqcreated", ca.getName(),
                Integer.valueOf(caid));
        auditSession.log(EventTypes.CA_EDITING, EventStatus.SUCCESS, ModuleTypes.CA, ServiceTypes.CORE,
                authenticationToken.toString(), String.valueOf(caid), null, null, detailsMsg);
    } catch (CertPathValidatorException e) {
        final String detailsMsg = intres.getLocalizedMessage("caadmin.errorcertreq", Integer.valueOf(caid));
        auditSession.log(EventTypes.CA_EDITING, EventStatus.FAILURE, ModuleTypes.CA, ServiceTypes.CORE,
                authenticationToken.toString(), String.valueOf(caid), null, null, detailsMsg);
        throw e;
    } catch (CryptoTokenOfflineException e) {
        final String detailsMsg = intres.getLocalizedMessage("caadmin.errorcertreq", Integer.valueOf(caid));
        auditSession.log(EventTypes.CA_EDITING, EventStatus.FAILURE, ModuleTypes.CA, ServiceTypes.CORE,
                authenticationToken.toString(), String.valueOf(caid), null, null, detailsMsg);
        throw e;
    } catch (Exception e) {
        final String detailsMsg = intres.getLocalizedMessage("caadmin.errorcertreq", Integer.valueOf(caid));
        auditSession.log(EventTypes.CA_EDITING, EventStatus.FAILURE, ModuleTypes.CA, ServiceTypes.CORE,
                authenticationToken.toString(), String.valueOf(caid), null, null, detailsMsg);
        throw new EJBException(e);
    }
    if (log.isTraceEnabled()) {
        log.trace("<makeRequest: " + caid);
    }
    return returnval;
}

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

/**
 * Sets a password, hashed or clear text, for a user.
 * //from   w  ww . j a va 2  s. c  om
 * @param admin the administrator performing the action
 * @param username the unique username.
 * @param password the new password to be stored in clear text. Setting password to 'null' effectively deletes any previous clear text password.
 * @param cleartext true gives cleartext password, false hashed
 */
private void setPassword(final AuthenticationToken admin, final String username, final String password,
        final boolean cleartext)
        throws UserDoesntFullfillEndEntityProfile, AuthorizationDeniedException, FinderException {
    if (log.isTraceEnabled()) {
        log.trace(">setPassword(" + username + ", hiddenpwd), " + cleartext);
    }
    // Find user
    String newpasswd = password;
    final UserData data = UserData.findByUsername(entityManager, username);
    if (data == null) {
        throw new FinderException("Could not find user " + username);
    }
    final int caid = data.getCaId();
    final String dn = data.getSubjectDN();
    final int endEntityProfileId = data.getEndEntityProfileId();

    final EndEntityProfile profile = endEntityProfileSession.getEndEntityProfileNoClone(endEntityProfileId);

    if (profile.useAutoGeneratedPasswd()) {
        newpasswd = profile.getAutoGeneratedPasswd();
    }
    if (getGlobalConfiguration().getEnableEndEntityProfileLimitations()) {
        // Check if user fulfills it's profile.
        try {
            profile.doesPasswordFulfillEndEntityProfile(password, true);
        } catch (UserDoesntFullfillEndEntityProfile ufe) {
            final String msg = intres.getLocalizedMessage("ra.errorfullfillprofile",
                    Integer.valueOf(endEntityProfileId), dn, ufe.getMessage());
            Map<String, Object> details = new LinkedHashMap<String, Object>();
            details.put("msg", msg);
            auditSession.log(EjbcaEventTypes.RA_EDITENDENTITY, EventStatus.FAILURE, EjbcaModuleTypes.RA,
                    ServiceTypes.CORE, admin.toString(), String.valueOf(caid), null, username, details);
            throw ufe;
        }
        // Check if administrator is authorized to edit user.
        assertAuthorizedToEndEntityProfile(admin, data.getEndEntityProfileId(),
                AccessRulesConstants.EDIT_END_ENTITY, caid);
    }
    assertAuthorizedToCA(admin, caid);
    try {
        final Date now = new Date();
        if ((newpasswd == null) && (cleartext)) {
            data.setClearPassword("");
            data.setPasswordHash("");
            data.setTimeModified(now.getTime());
        } else {
            if (cleartext) {
                data.setOpenPassword(newpasswd);
            } else {
                data.setPassword(newpasswd);
            }
            data.setTimeModified(now.getTime());
        }
        final String msg = intres.getLocalizedMessage("ra.editpwdentity", username);
        Map<String, Object> details = new LinkedHashMap<String, Object>();
        details.put("msg", msg);
        auditSession.log(EjbcaEventTypes.RA_EDITENDENTITY, EventStatus.SUCCESS, EjbcaModuleTypes.RA,
                ServiceTypes.CORE, admin.toString(), String.valueOf(caid), null, username, details);
    } catch (NoSuchAlgorithmException nsae) {
        log.error("NoSuchAlgorithmException while setting password for user " + username);
        throw new EJBException(nsae);
    }
    if (log.isTraceEnabled()) {
        log.trace("<setPassword(" + username + ", hiddenpwd), " + cleartext);
    }
}