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 generarBusinessMessage() {
    try {/* w w w . jav a  2 s. co m*/
        VelocityContext context = new VelocityContext();
        String query = VelocityEngineer.write(context, "sdk-query-generar-mensajes.vm").toString();
        List<Funcion> funciones = funcionFacade.findByQuery(query, EnumTipoQuery.NATIVE, REFRESH);
        String root = ToolKitUtils.getWorkspaceDir();
        String filedir = ToolKitUtils.mkEjbSrcDir(root, EA.getLowerCaseCode() + "-ejb-business", "jms");
        String filename = filedir + "BusinessProcessBrokerBean.java";
        ToolKitUtils utils = this.getToolKitUtils();
        context.put("utils", utils);
        context.put("funciones", funciones);
        write(context, "sdk-plantilla-business-process-broker-java.vm", filename);
        generarBusinessMessage(funciones);
        TLC.getBitacora().info(Bundle.getString("generar.mensajes.ok"), funciones.size());
    } catch (Exception ex) {
        //          TLC.getBitacora().fatal(ex);
        throw ex instanceof EJBException ? (EJBException) ex : new EJBException(ex);
    }
}

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

@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
public void addIngestedFiles(Long studyId, String versionNote, List fileBeans, Long userId) {
    // if no files, then just return
    if (fileBeans.isEmpty()) {
        return;//from ww w .  j ava 2s. c  om
    }

    // first some initialization
    StudyVersion studyVersion = null;
    Study study = null;
    MD5Checksum md5Checksum = new MD5Checksum();

    study = em.find(Study.class, studyId);
    studyVersion = study.getEditVersion();
    if (studyVersion.getId() == null) {
        em.persist(studyVersion);
        em.flush();
    }

    studyVersion.setVersionNote(versionNote);

    VDCUser user = userService.find(userId);

    File newDir = new File(FileUtil.getStudyFileDir(),
            study.getAuthority() + File.separator + study.getStudyId());
    if (!newDir.exists()) {
        newDir.mkdirs();
    }

    // now iterate through fileBeans
    Iterator iter = fileBeans.iterator();
    while (iter.hasNext()) {
        StudyFileEditBean fileBean = (StudyFileEditBean) iter.next();

        // for now the logic is if the DSB does not return a file, don't copy
        // over anything; this is to cover the situation with the Ingest servlet
        // that uses takes a control card file to add a dataTable to a prexisting
        // file; this will have to change if we do this two files method at the
        // time of the original upload
        // (TODO: figure out what this comment means - ? - L.A.)
        // (is this some legacy thing? - it's talking about "ingest servlet"...)
        // (did we ever have a mechanism for adding a data table to an existing
        //  tab file?? - that's actually kinda cool)

        StudyFile f = fileBean.getStudyFile();

        // So, if there is a file: let's move it to its final destination
        // in the study directory. 
        //
        // First, if it's a subsettable or network, or any other
        // kind potentially, that gets transformed on ingest: 

        File newIngestedLocationFile = null;

        if (fileBean.getIngestedSystemFileLocation() != null) {

            String originalFileType = f.getFileType();

            // 1. move ingest-created file:

            File tempIngestedFile = new File(fileBean.getIngestedSystemFileLocation());
            newIngestedLocationFile = new File(newDir, f.getFileSystemName());
            try {
                FileUtil.copyFile(tempIngestedFile, newIngestedLocationFile);
                tempIngestedFile.delete();
                if (f instanceof TabularDataFile) {
                    f.setFileType("text/tab-separated-values");
                }
                f.setFileSystemLocation(newIngestedLocationFile.getAbsolutePath());

            } catch (IOException ex) {
                throw new EJBException(ex);
            }
            // 1b. If this is a NetworkDataFile,  move the SQLite file from the temp Ingested location to the system location
            if (f instanceof NetworkDataFile) {
                File tempSQLDataFile = new File(tempIngestedFile.getParent(), FileUtil
                        .replaceExtension(tempIngestedFile.getName(), NetworkDataServiceBean.SQLITE_EXTENSION));
                File newSQLDataFile = new File(newDir,
                        f.getFileSystemName() + "." + NetworkDataServiceBean.SQLITE_EXTENSION);

                File tempNeo4jDir = new File(tempIngestedFile.getParent(), FileUtil
                        .replaceExtension(tempIngestedFile.getName(), NetworkDataServiceBean.NEO4J_EXTENSION));
                File newNeo4jDir = new File(newDir,
                        f.getFileSystemName() + "." + NetworkDataServiceBean.NEO4J_EXTENSION);

                try {
                    FileUtil.copyFile(tempSQLDataFile, newSQLDataFile);
                    FileUtils.copyDirectory(tempNeo4jDir, newNeo4jDir);
                    tempSQLDataFile.delete();
                    FileUtils.deleteDirectory(tempNeo4jDir);
                    f.setOriginalFileType(originalFileType);

                } catch (IOException ex) {
                    throw new EJBException(ex);
                }
            }

            // 2. also move original file for archiving
            File tempOriginalFile = new File(fileBean.getTempSystemFileLocation());
            File newOriginalLocationFile = new File(newDir, "_" + f.getFileSystemName());
            try {
                if (fileBean.getControlCardSystemFileLocation() != null
                        && fileBean.getControlCardType() != null) {
                    // 2a. For the control card-based ingests (SPSS and DDI), we save
                    // a zipped bundle of both the card and the raw data file
                    // (TAB-delimited or CSV):

                    FileInputStream instream = null;
                    byte[] dataBuffer = new byte[8192];

                    ZipOutputStream zout = new ZipOutputStream(new FileOutputStream(newOriginalLocationFile));

                    // First, the control card:

                    File controlCardFile = new File(fileBean.getControlCardSystemFileLocation());

                    ZipEntry ze = new ZipEntry(controlCardFile.getName());
                    instream = new FileInputStream(controlCardFile);
                    zout.putNextEntry(ze);

                    int k = 0;
                    while ((k = instream.read(dataBuffer)) > 0) {
                        zout.write(dataBuffer, 0, k);
                        zout.flush();
                    }

                    instream.close();

                    // And then, the data file:

                    ze = new ZipEntry(tempOriginalFile.getName());
                    instream = new FileInputStream(tempOriginalFile);
                    zout.putNextEntry(ze);

                    while ((k = instream.read(dataBuffer)) > 0) {
                        zout.write(dataBuffer, 0, k);
                        zout.flush();
                    }

                    instream.close();

                    zout.close();

                    // and control card file can be deleted now:
                    controlCardFile.delete();

                    // Mime types: 
                    // These are custom, made-up types, used to identify the 
                    // type of the source data:

                    if (fileBean.getControlCardType().equals("spss")) {
                        f.setOriginalFileType("application/x-dvn-csvspss-zip");
                    } else if (fileBean.getControlCardType().equals("ddi")) {
                        f.setOriginalFileType("application/x-dvn-tabddi-zip");
                    } else {
                        logger.info("WARNING: unknown control card-based Ingest type? -- "
                                + fileBean.getControlCardType());
                        f.setOriginalFileType(originalFileType);
                    }
                    f.setMd5(md5Checksum.CalculateMD5(tempOriginalFile.getAbsolutePath()));

                } else {
                    // 2b. Otherwise, simply store the data that was used for
                    // ingest as the original:

                    FileUtil.copyFile(tempOriginalFile, newOriginalLocationFile);
                    f.setOriginalFileType(originalFileType);
                    f.setMd5(md5Checksum.CalculateMD5(newOriginalLocationFile.getAbsolutePath()));
                }
                tempOriginalFile.delete();
            } catch (IOException ex) {
                throw new EJBException(ex);
            }
        } else if (f instanceof SpecialOtherFile) {
            // "Special" OtherFiles are still OtherFiles; we just add the file
            // uploaded by the user to the study as is:

            File tempIngestedFile = new File(fileBean.getTempSystemFileLocation());
            newIngestedLocationFile = new File(newDir, f.getFileSystemName());
            try {
                FileUtil.copyFile(tempIngestedFile, newIngestedLocationFile);
                tempIngestedFile.delete();
                f.setFileSystemLocation(newIngestedLocationFile.getAbsolutePath());
                f.setMd5(md5Checksum.CalculateMD5(newIngestedLocationFile.getAbsolutePath()));
            } catch (IOException ex) {
                throw new EJBException(ex);
            }
        }

        // Finally, if the file was copied sucessfully, 
        // attach file to study version and study

        if (newIngestedLocationFile != null && newIngestedLocationFile.exists()) {

            fileBean.getFileMetadata().setStudyVersion(studyVersion);
            studyVersion.getFileMetadatas().add(fileBean.getFileMetadata());
            fileBean.getStudyFile().setStudy(study);
            // don't need to set study side, since we're no longer using persistence cache
            //study.getStudyFiles().add(fileBean.getStudyFile());
            //fileBean.addFiletoStudy(study);

            em.persist(fileBean.getStudyFile());
            em.persist(fileBean.getFileMetadata());

        } else {
            //fileBean.getStudyFile().setSubsettable(true);
            em.merge(fileBean.getStudyFile());
        }
    }
    // calcualte UNF for study version
    try {
        studyVersion.getMetadata().setUNF(new DSBWrapper().calculateUNF(studyVersion));
    } catch (IOException e) {
        throw new EJBException("Could not calculate new study UNF");
    }

    studyService.saveStudyVersion(studyVersion, user.getId());
}

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

@Override
public void addUser(Admin admin, UserDataVO userDataVO, boolean clearpwd) throws AuthorizationDeniedException,
        EjbcaException, UserDoesntFullfillEndEntityProfile, WaitingForApprovalException, PersistenceException {
    final int endEntityProfileId = userDataVO.getEndEntityProfileId();
    final int caid = userDataVO.getCAId();
    final String username = StringTools.strip(userDataVO.getUsername());
    // Check if administrator is authorized to add user to CA.
    assertAuthorizedToCA(admin, caid, username, LogConstants.EVENT_ERROR_ADDEDENDENTITY);
    final GlobalConfiguration globalConfiguration = getGlobalConfiguration(admin);
    if (globalConfiguration.getEnableEndEntityProfileLimitations()) {
        // Check if administrator is authorized to add user.
        assertAuthorizedToEndEntityProfile(admin, endEntityProfileId, AccessRulesConstants.CREATE_RIGHTS, caid,
                username, LogConstants.EVENT_ERROR_ADDEDENDENTITY);
    }/* w  w  w. j  av  a2  s  .  c  o m*/
    final String originalDN = userDataVO.getDN();
    canonicalizeUser(admin, userDataVO);
    if (log.isTraceEnabled()) {
        log.trace(">addUser(" + userDataVO.getUsername() + ", password, " + userDataVO.getDN() + ", "
                + originalDN + ", " + userDataVO.getSubjectAltName() + ", " + userDataVO.getEmail()
                + ", profileId: " + endEntityProfileId + ")");
    }
    final String endEntityProfileName = endEntityProfileSession.getEndEntityProfileName(admin,
            endEntityProfileId);
    final String dn = userDataVO.getDN();
    final String altName = userDataVO.getSubjectAltName();
    final String email = userDataVO.getEmail();
    final int type = userDataVO.getType();
    String newpassword = userDataVO.getPassword();
    EndEntityProfile profile = null; // Only look this up if we need it..
    if (userDataVO.getPassword() == null) {
        profile = endEntityProfileSession.getEndEntityProfile(admin, endEntityProfileId);
        if (profile.useAutoGeneratedPasswd()) {
            // special case used to signal regeneration of password
            newpassword = profile.getAutoGeneratedPasswd();
        }
    }
    if (globalConfiguration.getEnableEndEntityProfileLimitations()) {
        if (profile == null) {
            profile = endEntityProfileSession.getEndEntityProfile(admin, endEntityProfileId);
        }
        // Check if user fulfills it's profile.
        try {
            final String dirattrs = userDataVO.getExtendedinformation() != null
                    ? userDataVO.getExtendedinformation().getSubjectDirectoryAttributes()
                    : null;
            profile.doesUserFullfillEndEntityProfile(username, userDataVO.getPassword(), dn, altName, dirattrs,
                    email, userDataVO.getCertificateProfileId(), clearpwd,
                    (type & SecConst.USER_KEYRECOVERABLE) != 0, (type & SecConst.USER_SENDNOTIFICATION) != 0,
                    userDataVO.getTokenType(), userDataVO.getHardTokenIssuerId(), caid,
                    userDataVO.getExtendedinformation());
        } catch (UserDoesntFullfillEndEntityProfile e) {
            final String msg = intres.getLocalizedMessage("ra.errorfullfillprofile", endEntityProfileName, dn,
                    e.getMessage());
            logSession.log(admin, caid, LogConstants.MODULE_RA, new Date(), username, null,
                    LogConstants.EVENT_ERROR_ADDEDENDENTITY, msg);
            throw e;
        }
    }
    // Get CAInfo, to be able to read configuration
    final CAInfo caInfo = caAdminSession.getCAInfoOrThrowException(admin, caid);
    // Check if approvals is required. (Only do this if store users, otherwise this approval is disabled.)
    if (caInfo.isUseUserStorage()) {
        final int numOfApprovalsRequired = getNumOfApprovalRequired(admin, CAInfo.REQ_APPROVAL_ADDEDITENDENTITY,
                caid, userDataVO.getCertificateProfileId());
        if (numOfApprovalsRequired > 0) {
            AddEndEntityApprovalRequest ar = new AddEndEntityApprovalRequest(userDataVO, clearpwd, admin, null,
                    numOfApprovalsRequired, caid, endEntityProfileId);
            if (ApprovalExecutorUtil.requireApproval(ar, NONAPPROVABLECLASSNAMES_ADDUSER)) {
                approvalSession.addApprovalRequest(admin, ar, globalConfiguration);
                throw new WaitingForApprovalException(intres.getLocalizedMessage("ra.approvalad"));
            }
        }
    }
    // Check if the subjectDN serialnumber already exists.
    if (caInfo.isDoEnforceUniqueSubjectDNSerialnumber()) {
        if (caInfo.isUseUserStorage()) {
            if (!isSubjectDnSerialnumberUnique(caid, dn, username)) {
                throw new EjbcaException(ErrorCode.SUBJECTDN_SERIALNUMBER_ALREADY_EXISTS,
                        "Error: SubjectDN Serialnumber already exists.");
            }
        } else {
            log.warn(
                    "CA configured to enforce unique SubjectDN serialnumber, but not to store any user data. Check will be ignored. Please verify your configuration.");
        }
    }
    // Store a new UserData in the database, if this CA is configured to do so.
    if (caInfo.isUseUserStorage()) {
        try {
            // Create the user in one go with all parameters at once. This was important in EJB2.1 so the persistence layer only creates *one* single
            // insert statement. If we do a home.create and the some setXX, it will create one insert and one update statement to the database.
            // Probably not important in EJB3 anymore.
            final UserData userData = new UserData(username, newpassword, clearpwd, dn, caid,
                    userDataVO.getCardNumber(), altName, email, type, endEntityProfileId,
                    userDataVO.getCertificateProfileId(), userDataVO.getTokenType(),
                    userDataVO.getHardTokenIssuerId(), userDataVO.getExtendedinformation());
            // Since persist will not commit and fail if the user already exists, we need to check for this
            // Flushing the entityManager will not allow us to rollback the persisted user if this is a part of a larger transaction.
            if (UserData.findByUsername(entityManager, username) != null) {
                throw new EntityExistsException("User " + username + " already exists.");
            }
            entityManager.persist(userData);
            // Although UserDataVO should always have a null password for
            // autogenerated end entities, the notification framework
            // expect it to exist. Since nothing else but printing is done after
            // this point it is safe to set the password
            userDataVO.setPassword(newpassword);
            // Send notifications, if they should be sent
            sendNotification(admin, userDataVO, UserDataConstants.STATUS_NEW);
            if ((type & SecConst.USER_PRINT) != 0) {
                if (profile == null) {
                    profile = endEntityProfileSession.getEndEntityProfile(admin, endEntityProfileId);
                }
                print(admin, profile, userDataVO);
            }
            final String msg = intres.getLocalizedMessage("ra.addedentity", username);
            logSession.log(admin, caid, LogConstants.MODULE_RA, new Date(), username, null,
                    LogConstants.EVENT_INFO_ADDEDENDENTITY, msg);
        } catch (PersistenceException e) {
            // PersistenceException could also be caused by various database problems.
            final String msg = intres.getLocalizedMessage("ra.errorentityexist", username);
            logSession.log(admin, caid, LogConstants.MODULE_RA, new Date(), username, null,
                    LogConstants.EVENT_ERROR_ADDEDENDENTITY, msg);
            throw e;
        } catch (Exception e) {
            final String msg = intres.getLocalizedMessage("ra.erroraddentity", username);
            logSession.log(admin, caid, LogConstants.MODULE_RA, new Date(), username, null,
                    LogConstants.EVENT_ERROR_ADDEDENDENTITY, msg, e);
            log.error(msg, e);
            throw new EJBException(e);
        }
    }
    if (log.isTraceEnabled()) {
        log.trace("<addUser(" + username + ", password, " + dn + ", " + email + ")");
    }
}

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

@Override
public void generarBusinessProcess() {
    try {/*from   w  w w . java 2 s .c o m*/
        VelocityContext context = new VelocityContext();
        String query = VelocityEngineer.write(context, "sdk-query-generar-procesos.vm").toString();
        List<Dominio> dominios = dominioFacade.findByQuery(query, EnumTipoQuery.NATIVE, REFRESH);
        generarBusinessProcess(dominios);
        TLC.getBitacora().info(Bundle.getString("generar.procesos.ok"), dominios.size());
    } catch (Exception ex) {
        //          TLC.getBitacora().fatal(ex);
        throw ex instanceof EJBException ? (EJBException) ex : new EJBException(ex);
    }
}

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

@Override
public void generarPlantilla() {
    //      List<Aplicacion> aplicaciones = aplicacionFacade.findAll(REFRESH);
    List<Aplicacion> aplicaciones = aplicacionFacade.findAll(REFRESH);
    try {//from w w  w  .j a  v a 2 s  . c o  m
        generarPlantilla(aplicaciones);
        TLC.getBitacora().info(Bundle.getString("generar.aplicaciones.ok"), aplicaciones.size());
    } catch (Exception ex) {
        //          TLC.getBitacora().fatal(ex);
        throw ex instanceof EJBException ? (EJBException) ex : new EJBException(ex);
    }
}

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

@Override
public void addUser(final AuthenticationToken admin, final EndEntityInformation endEntity,
        final boolean clearpwd) throws AuthorizationDeniedException, EjbcaException, EndEntityExistsException,
        UserDoesntFullfillEndEntityProfile, WaitingForApprovalException, CADoesntExistsException {
    final int endEntityProfileId = endEntity.getEndEntityProfileId();
    final int caid = endEntity.getCAId();
    // Check if administrator is authorized to add user to CA.
    assertAuthorizedToCA(admin, caid);// www. java  2 s  . co m
    final GlobalConfiguration globalConfiguration = getGlobalConfiguration();
    if (globalConfiguration.getEnableEndEntityProfileLimitations()) {
        // Check if administrator is authorized to add user.
        assertAuthorizedToEndEntityProfile(admin, endEntityProfileId, AccessRulesConstants.CREATE_END_ENTITY,
                caid);
    }

    final String originalDN = endEntity.getDN();
    canonicalizeUser(endEntity);
    if (log.isTraceEnabled()) {
        log.trace(">addUser(" + endEntity.getUsername() + ", password, " + endEntity.getDN() + ", " + originalDN
                + ", " + endEntity.getSubjectAltName() + ", " + endEntity.getEmail() + ", profileId: "
                + endEntityProfileId + ")");
    }

    final String endEntityProfileName = endEntityProfileSession.getEndEntityProfileName(endEntityProfileId);
    final String username = endEntity.getUsername();
    final String dn = endEntity.getDN();
    final String altName = endEntity.getSubjectAltName();
    final String email = endEntity.getEmail();
    final EndEntityType type = endEntity.getType();
    String newpassword = endEntity.getPassword();
    EndEntityProfile profile = null; // Only look this up if we need it..
    if (endEntity.getPassword() == null) {
        profile = endEntityProfileSession.getEndEntityProfileNoClone(endEntityProfileId);
        if (profile.useAutoGeneratedPasswd()) {
            // special case used to signal regeneration of password
            newpassword = profile.getAutoGeneratedPasswd();
        }
    }
    if (globalConfiguration.getEnableEndEntityProfileLimitations()) {
        if (profile == null) {
            profile = endEntityProfileSession.getEndEntityProfileNoClone(endEntityProfileId);
        }
        // Check if user fulfills it's profile.
        try {
            final String dirattrs = endEntity.getExtendedinformation() != null
                    ? endEntity.getExtendedinformation().getSubjectDirectoryAttributes()
                    : null;
            profile.doesUserFullfillEndEntityProfile(username, endEntity.getPassword(), dn, altName, dirattrs,
                    email, endEntity.getCertificateProfileId(), clearpwd,
                    type.contains(EndEntityTypes.KEYRECOVERABLE),
                    type.contains(EndEntityTypes.SENDNOTIFICATION), endEntity.getTokenType(),
                    endEntity.getHardTokenIssuerId(), caid, endEntity.getExtendedinformation());
        } catch (UserDoesntFullfillEndEntityProfile e) {
            final String msg = intres.getLocalizedMessage("ra.errorfullfillprofile", endEntityProfileName, dn,
                    e.getMessage());
            Map<String, Object> details = new LinkedHashMap<String, Object>();
            details.put("msg", msg);
            auditSession.log(EjbcaEventTypes.RA_ADDENDENTITY, EventStatus.FAILURE, EjbcaModuleTypes.RA,
                    ServiceTypes.CORE, admin.toString(), String.valueOf(caid), null, username, details);
            throw e;
        }
    }
    // Get CAInfo, to be able to read configuration
    // No need to access control on the CA here just to get these flags, we have already checked above that we are authorized to the CA
    final CAInfo caInfo = caSession.getCAInfoInternal(caid, null, true);
    // Check if approvals is required. (Only do this if store users, otherwise this approval is disabled.)
    if (caInfo.isUseUserStorage()) {
        final int numOfApprovalsRequired = getNumOfApprovalRequired(CAInfo.REQ_APPROVAL_ADDEDITENDENTITY, caid,
                endEntity.getCertificateProfileId());
        if (numOfApprovalsRequired > 0) {
            AddEndEntityApprovalRequest ar = new AddEndEntityApprovalRequest(endEntity, clearpwd, admin, null,
                    numOfApprovalsRequired, caid, endEntityProfileId);
            if (ApprovalExecutorUtil.requireApproval(ar, NONAPPROVABLECLASSNAMES_ADDUSER)) {
                approvalSession.addApprovalRequest(admin, ar);
                throw new WaitingForApprovalException(intres.getLocalizedMessage("ra.approvalad"));
            }
        }
    }
    // Check if the subjectDN serialnumber already exists.
    if (caInfo.isDoEnforceUniqueSubjectDNSerialnumber()) {
        if (caInfo.isUseUserStorage()) {
            if (!isSubjectDnSerialnumberUnique(caid, dn, username)) {
                throw new EjbcaException(ErrorCode.SUBJECTDN_SERIALNUMBER_ALREADY_EXISTS,
                        "Error: SubjectDN Serialnumber already exists.");
            }
        } else {
            log.warn(
                    "CA configured to enforce unique SubjectDN serialnumber, but not to store any user data. Check will be ignored. Please verify your configuration.");
        }
    }
    // Check name constraints
    if (caInfo instanceof X509CAInfo && !caInfo.getCertificateChain().isEmpty()) {
        final X509CAInfo x509cainfo = (X509CAInfo) caInfo;
        final X509Certificate cacert = (X509Certificate) caInfo.getCertificateChain().iterator().next();
        final CertificateProfile certProfile = certificateProfileSession
                .getCertificateProfile(endEntity.getCertificateProfileId());

        final X500NameStyle nameStyle;
        if (x509cainfo.getUsePrintableStringSubjectDN()) {
            nameStyle = PrintableStringNameStyle.INSTANCE;
        } else {
            nameStyle = CeSecoreNameStyle.INSTANCE;
        }

        final boolean ldaporder;
        if (x509cainfo.getUseLdapDnOrder() && certProfile.getUseLdapDnOrder()) {
            ldaporder = true; // will cause an error to be thrown later if name constraints are used
        } else {
            ldaporder = false;
        }

        X500Name subjectDNName = CertTools.stringToBcX500Name(dn, nameStyle, ldaporder);
        GeneralNames subjectAltName = CertTools.getGeneralNamesFromAltName(altName);
        try {
            CertTools.checkNameConstraints(cacert, subjectDNName, subjectAltName);
        } catch (IllegalNameException e) {
            throw new EjbcaException(ErrorCode.NAMECONSTRAINT_VIOLATION, e.getMessage());
        }
    }
    // Store a new UserData in the database, if this CA is configured to do so.
    if (caInfo.isUseUserStorage()) {
        try {
            // Create the user in one go with all parameters at once. This was important in EJB2.1 so the persistence layer only creates *one*
            // single
            // insert statement. If we do a home.create and the some setXX, it will create one insert and one update statement to the database.
            // Probably not important in EJB3 anymore.
            final UserData userData = new UserData(username, newpassword, clearpwd, dn, caid,
                    endEntity.getCardNumber(), altName, email, type.getHexValue(), endEntityProfileId,
                    endEntity.getCertificateProfileId(), endEntity.getTokenType(),
                    endEntity.getHardTokenIssuerId(), endEntity.getExtendedinformation());
            // Since persist will not commit and fail if the user already exists, we need to check for this
            // Flushing the entityManager will not allow us to rollback the persisted user if this is a part of a larger transaction.
            if (UserData.findByUsername(entityManager, userData.getUsername()) != null) {
                throw new EndEntityExistsException("User " + userData.getUsername() + " already exists.");
            }
            entityManager.persist(userData);
            // Although EndEntityInformation should always have a null password for
            // autogenerated end entities, the notification framework
            // expect it to exist. Since nothing else but printing is done after
            // this point it is safe to set the password
            endEntity.setPassword(newpassword);
            // Send notifications, if they should be sent
            sendNotification(admin, endEntity, EndEntityConstants.STATUS_NEW);
            if (type.contains(EndEntityTypes.PRINT)) {
                if (profile == null) {
                    profile = endEntityProfileSession.getEndEntityProfileNoClone(endEntityProfileId);
                }
                print(profile, endEntity);
            } else {
                if (log.isDebugEnabled()) {
                    log.debug("Type (" + type.getHexValue()
                            + ") does not contain SecConst.USER_PRINT, no print job created.");
                }
            }
            final Map<String, Object> details = new LinkedHashMap<String, Object>();
            details.put("msg", intres.getLocalizedMessage("ra.addedentity", username));
            auditSession.log(EjbcaEventTypes.RA_ADDENDENTITY, EventStatus.SUCCESS, EjbcaModuleTypes.RA,
                    ServiceTypes.CORE, admin.toString(), String.valueOf(caid), null, username, details);
        } catch (EndEntityExistsException e) {
            final Map<String, Object> details = new LinkedHashMap<String, Object>();
            details.put("msg", intres.getLocalizedMessage("ra.errorentityexist", username));
            details.put("error", e.getMessage());
            auditSession.log(EjbcaEventTypes.RA_ADDENDENTITY, EventStatus.FAILURE, EjbcaModuleTypes.RA,
                    ServiceTypes.CORE, admin.toString(), String.valueOf(caid), null, username, details);
            throw e;
        } catch (Exception e) {
            final String msg = intres.getLocalizedMessage("ra.erroraddentity", username);
            log.error(msg, e);
            final Map<String, Object> details = new LinkedHashMap<String, Object>();
            details.put("msg", msg);
            details.put("error", e.getMessage());
            auditSession.log(EjbcaEventTypes.RA_ADDENDENTITY, EventStatus.FAILURE, EjbcaModuleTypes.RA,
                    ServiceTypes.CORE, admin.toString(), String.valueOf(caid), null, username, details);
            throw new EJBException(e);
        }
    }
    if (log.isTraceEnabled()) {
        log.trace("<addUser(" + username + ", password, " + dn + ", " + email + ")");
    }
}

From source file:edu.harvard.iq.dvn.core.harvest.HarvesterServiceBean.java

@TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED)
public Long getRecord(Logger hdLogger, HarvestingDataverse dataverse, String identifier, String metadataPrefix,
        MutableBoolean recordErrorOccurred) {

    String errMessage = null;//  w ww .  ja v  a 2  s. c  o  m
    Study harvestedStudy = null;
    String oaiUrl = dataverse.getServerUrl();
    try {
        hdLogger.log(Level.INFO, "Calling GetRecord: oaiUrl =" + oaiUrl + "?verb=GetRecord&identifier="
                + identifier + "&metadataPrefix=" + metadataPrefix);

        DvnFastGetRecord record = new DvnFastGetRecord(oaiUrl, identifier, metadataPrefix);
        errMessage = record.getErrorMessage();
        //errMessage=null;

        if (errMessage != null) {
            hdLogger.log(Level.SEVERE, "Error calling GetRecord - " + errMessage);
        } else if (record.isDeleted()) {
            hdLogger.log(Level.INFO, "Received 'deleted' status from OAI Server.");
            Study study = studyService.getStudyByHarvestInfo(dataverse.getVdc(), identifier);
            if (study != null) {
                hdLogger.log(Level.INFO, "Deleting study " + study.getGlobalId());
                studyService.deleteStudy(study.getId());
            } else {
                hdLogger.log(Level.INFO, "No study found for this record, skipping delete. ");
            }

        } else {
            hdLogger.log(Level.INFO, "Successfully retreived GetRecord response.");

            VDCUser networkAdmin = vdcNetworkService.find().getDefaultNetworkAdmin();

            harvestedStudy = studyService.importHarvestStudy(record.getMetadataFile(),
                    dataverse.getVdc().getId(), networkAdmin.getId(), identifier);
            //hdLogger.log(Level.INFO, "imported study (step 1., no data); proceeding with step 2.");
            //studyService.importHarvestStudyExperimental(harvestedStudyFile, harvestedStudy);
            hdLogger.log(Level.INFO, "Harvest Successful for identifier " + identifier);

            this.processedSizeThisBatch += record.getMetadataFile().length();
            if (this.harvestedStudyIdsThisBatch == null) {
                this.harvestedStudyIdsThisBatch = new ArrayList<Long>();
            }
            this.harvestedStudyIdsThisBatch.add(harvestedStudy.getId());

            if (this.processedSizeThisBatch > 10000000) {

                hdLogger.log(Level.INFO, "REACHED CONTENT BATCH SIZE LIMIT; calling index ("
                        + this.harvestedStudyIdsThisBatch.size() + " studies in the batch).");
                indexService.updateIndexList(this.harvestedStudyIdsThisBatch);
                hdLogger.log(Level.INFO, "REINDEX DONE.");

                this.processedSizeThisBatch = 0;
                this.harvestedStudyIdsThisBatch = null;
            }
        }
    } catch (Throwable e) {
        errMessage = "Exception processing getRecord(), oaiUrl=" + oaiUrl + ",identifier=" + identifier + " "
                + e.getClass().getName() + " " + e.getMessage();
        hdLogger.log(Level.SEVERE, errMessage);
        logException(e, hdLogger);

    }

    // If we got an Error from the OAI server or an exception happened during import, then
    // set recordErrorOccurred to true (if recordErrorOccurred is being used)
    // otherwise throw an exception (if recordErrorOccurred is not used, i.e null)
    if (errMessage != null) {
        if (recordErrorOccurred != null) {
            recordErrorOccurred.setValue(true);
        } else {
            throw new EJBException(errMessage);
        }
    }

    return harvestedStudy != null ? harvestedStudy.getId() : null;
}

From source file:edu.harvard.iq.dvn.core.harvest.HarvesterServiceBean.java

public List<String> getMetadataFormats(String oaiUrl) {
    JAXBElement unmarshalObj;/*www . jav  a 2  s  . c  o m*/
    try {

        Document doc = new ListMetadataFormats(oaiUrl).getDocument();
        JAXBContext jc = JAXBContext.newInstance("edu.harvard.hmdc.vdcnet.jaxb.oai");
        Unmarshaller unmarshaller = jc.createUnmarshaller();
        unmarshalObj = (JAXBElement) unmarshaller.unmarshal(doc);
    } catch (TransformerException ex) {
        throw new EJBException(ex);
    } catch (ParserConfigurationException ex) {
        throw new EJBException(ex);
    } catch (JAXBException ex) {
        throw new EJBException(ex);
    } catch (SAXException ex) {
        throw new EJBException(ex);
    } catch (IOException ex) {
        throw new EJBException(ex);
    }

    OAIPMHtype OAIObj = (OAIPMHtype) unmarshalObj.getValue();
    if (OAIObj.getError() != null && OAIObj.getError().size() > 0) {
        List<OAIPMHerrorType> errList = OAIObj.getError();
        String errMessage = "";
        for (OAIPMHerrorType error : OAIObj.getError()) {
            errMessage += error.getCode() + " " + error.getValue();
        }
        throw new EJBException(errMessage);
    }
    ListMetadataFormatsType listMetadataFormats = OAIObj.getListMetadataFormats();
    List<String> formats = null;
    if (listMetadataFormats != null) {
        formats = new ArrayList<String>();
        for (Iterator it = listMetadataFormats.getMetadataFormat().iterator(); it.hasNext();) {
            //  Object elem = it.next();
            MetadataFormatType elem = (MetadataFormatType) it.next();
            formats.add(elem.getMetadataPrefix());
        }
    }
    return formats;
}

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

@Override
public void changeUser(final Admin admin, final UserDataVO userDataVO, final boolean clearpwd,
        final boolean fromWebService) throws AuthorizationDeniedException, UserDoesntFullfillEndEntityProfile,
        WaitingForApprovalException, CADoesntExistsException, EjbcaException {
    final int endEntityProfileId = userDataVO.getEndEntityProfileId();
    final int caid = userDataVO.getCAId();
    final String username = userDataVO.getUsername();
    // Check if administrator is authorized to edit user to CA.
    assertAuthorizedToCA(admin, caid, username, LogConstants.EVENT_INFO_CHANGEDENDENTITY);
    final GlobalConfiguration globalConfiguration = getGlobalConfiguration(admin);
    if (globalConfiguration.getEnableEndEntityProfileLimitations()) {
        // Check if administrator is authorized to edit user.
        assertAuthorizedToEndEntityProfile(admin, endEntityProfileId, AccessRulesConstants.EDIT_RIGHTS, caid,
                username, LogConstants.EVENT_INFO_CHANGEDENDENTITY);
    }//from  w ww  .ja va 2s . c  o m
    try {
        FieldValidator.validate(userDataVO, endEntityProfileId,
                endEntityProfileSession.getEndEntityProfileName(admin, endEntityProfileId));
    } catch (CustomFieldException e) {
        throw new EjbcaException(ErrorCode.FIELD_VALUE_NOT_VALID, e.getMessage(), e);
    }
    String dn = CertTools.stringToBCDNString(StringTools.strip(userDataVO.getDN()));
    String altName = userDataVO.getSubjectAltName();
    if (log.isTraceEnabled()) {
        log.trace(">changeUser(" + username + ", " + dn + ", " + userDataVO.getEmail() + ")");
    }
    final UserData userData = UserData.findByUsername(entityManager, username);
    if (userData == null) {
        final String msg = intres.getLocalizedMessage("ra.erroreditentity", username);
        logSession.log(admin, caid, LogConstants.MODULE_RA, new Date(), username, null,
                LogConstants.EVENT_ERROR_CHANGEDENDENTITY, msg);
        log.error(msg);
        throw new EJBException(msg);
    }
    final EndEntityProfile profile = endEntityProfileSession.getEndEntityProfile(admin, endEntityProfileId);
    // if required, we merge the existing user dn into the dn provided by the web service.
    if (fromWebService && profile.getAllowMergeDnWebServices()) {
        if (userData != null) {
            if (userData.getSubjectDN() != null) {
                final Map<String, String> dnMap = new HashMap<String, String>();
                if (profile.getUse(DnComponents.DNEMAIL, 0)) {
                    dnMap.put(DnComponents.DNEMAIL, userDataVO.getEmail());
                }
                try {
                    dn = (new DistinguishedName(userData.getSubjectDN()))
                            .mergeDN(new DistinguishedName(dn), true, dnMap).toString();
                } catch (InvalidNameException e) {
                    log.debug("Invalid dn. We make it empty");
                    dn = "";
                }
            }
            if (userData.getSubjectAltName() != null) {
                final Map<String, String> dnMap = new HashMap<String, String>();
                if (profile.getUse(DnComponents.RFC822NAME, 0)) {
                    dnMap.put(DnComponents.RFC822NAME, userDataVO.getEmail());
                }
                try {
                    // SubjectAltName is not mandatory so
                    if (altName == null) {
                        altName = "";
                    }
                    altName = (new DistinguishedName(userData.getSubjectAltName()))
                            .mergeDN(new DistinguishedName(altName), true, dnMap).toString();
                } catch (InvalidNameException e) {
                    log.debug("Invalid altName. We make it empty");
                    altName = "";
                }
            }
        }
    }
    String newpassword = userDataVO.getPassword();
    if (profile.useAutoGeneratedPasswd() && newpassword != null) {
        // special case used to signal regeneraton of password
        newpassword = profile.getAutoGeneratedPasswd();
    }

    final int type = userDataVO.getType();
    final ExtendedInformation ei = userDataVO.getExtendedinformation();
    // Check if user fulfills it's profile.
    if (globalConfiguration.getEnableEndEntityProfileLimitations()) {
        try {
            String dirattrs = null;
            if (ei != null) {
                dirattrs = ei.getSubjectDirectoryAttributes();
            }
            // It is only meaningful to verify the password if we change it in some way, and if we are not autogenerating it
            if (!profile.useAutoGeneratedPasswd() && StringUtils.isNotEmpty(newpassword)) {
                profile.doesUserFullfillEndEntityProfile(username, userDataVO.getPassword(), dn, altName,
                        dirattrs, userDataVO.getEmail(), userDataVO.getCertificateProfileId(), clearpwd,
                        (type & SecConst.USER_KEYRECOVERABLE) != 0,
                        (type & SecConst.USER_SENDNOTIFICATION) != 0, userDataVO.getTokenType(),
                        userDataVO.getHardTokenIssuerId(), caid, ei);
            } else {
                profile.doesUserFullfillEndEntityProfileWithoutPassword(username, dn, altName, dirattrs,
                        userDataVO.getEmail(), userDataVO.getCertificateProfileId(),
                        (type & SecConst.USER_KEYRECOVERABLE) != 0,
                        (type & SecConst.USER_SENDNOTIFICATION) != 0, userDataVO.getTokenType(),
                        userDataVO.getHardTokenIssuerId(), caid, ei);
            }
        } catch (UserDoesntFullfillEndEntityProfile e) {
            final String msg = intres.getLocalizedMessage("ra.errorfullfillprofile",
                    Integer.valueOf(endEntityProfileId), dn, e.getMessage());
            logSession.log(admin, caid, LogConstants.MODULE_RA, new Date(), username, null,
                    LogConstants.EVENT_INFO_CHANGEDENDENTITY, msg);
            throw e;
        }
    }
    // Check if approvals is required.
    final int numOfApprovalsRequired = getNumOfApprovalRequired(admin, CAInfo.REQ_APPROVAL_ADDEDITENDENTITY,
            caid, userDataVO.getCertificateProfileId());
    if (numOfApprovalsRequired > 0) {
        final UserDataVO orguserdata = userData.toUserDataVO();
        final EditEndEntityApprovalRequest ar = new EditEndEntityApprovalRequest(userDataVO, clearpwd,
                orguserdata, admin, null, numOfApprovalsRequired, caid, endEntityProfileId);
        if (ApprovalExecutorUtil.requireApproval(ar, NONAPPROVABLECLASSNAMES_CHANGEUSER)) {
            approvalSession.addApprovalRequest(admin, ar, getGlobalConfiguration(admin));
            throw new WaitingForApprovalException(intres.getLocalizedMessage("ra.approvaledit"));
        }
    }
    // Check if the subjectDN serialnumber already exists.
    if (caAdminSession.getCAInfoOrThrowException(admin, caid).isDoEnforceUniqueSubjectDNSerialnumber()) {
        if (!isSubjectDnSerialnumberUnique(caid, dn, username)) {
            throw new EjbcaException(ErrorCode.SUBJECTDN_SERIALNUMBER_ALREADY_EXISTS,
                    "Error: SubjectDN Serialnumber already exists.");
        }
    }
    try {
        userData.setDN(dn);
        userData.setSubjectAltName(altName);
        userData.setSubjectEmail(userDataVO.getEmail());
        userData.setCaId(caid);
        userData.setType(type);
        userData.setEndEntityProfileId(endEntityProfileId);
        userData.setCertificateProfileId(userDataVO.getCertificateProfileId());
        userData.setTokenType(userDataVO.getTokenType());
        userData.setHardTokenIssuerId(userDataVO.getHardTokenIssuerId());
        userData.setCardNumber(userDataVO.getCardNumber());
        final int newstatus = userDataVO.getStatus();
        final int oldstatus = userData.getStatus();
        if (oldstatus == UserDataConstants.STATUS_KEYRECOVERY
                && newstatus != UserDataConstants.STATUS_KEYRECOVERY
                && newstatus != UserDataConstants.STATUS_INPROCESS) {
            keyRecoverySession.unmarkUser(admin, username);
        }
        if (ei != null) {
            final String requestCounter = ei.getCustomData(ExtendedInformation.CUSTOM_REQUESTCOUNTER);
            if (StringUtils.equals(requestCounter, "0") && newstatus == UserDataConstants.STATUS_NEW
                    && oldstatus != UserDataConstants.STATUS_NEW) {
                // If status is set to new, we should re-set the allowed request counter to the default values
                // But we only do this if no value is specified already, i.e. 0 or null
                resetRequestCounter(admin, false, ei, username, endEntityProfileId);
            } else {
                // If status is not new, we will only remove the counter if the profile does not use it
                resetRequestCounter(admin, true, ei, username, endEntityProfileId);
            }
        }
        userData.setExtendedInformation(ei);
        userData.setStatus(newstatus);
        if (StringUtils.isNotEmpty(newpassword)) {
            if (clearpwd) {
                try {
                    userData.setOpenPassword(newpassword);
                } catch (NoSuchAlgorithmException e) {
                    log.debug("NoSuchAlgorithmException while setting password for user " + username);
                    throw new EJBException(e);
                }
            } else {
                userData.setPassword(newpassword);
            }
        }
        // We want to create this object before re-setting the time modified, because we may want to
        // use the old time modified in any notifications
        final UserDataVO notificationUserDataVO = userData.toUserDataVO();
        userData.setTimeModified(new Date().getTime());
        // We also want to be able to handle non-clear generated passwords in the notification, although UserDataVO
        // should always have a null password for autogenerated end entities the notification framework expects it to
        // exist.
        if (newpassword != null) {
            notificationUserDataVO.setPassword(newpassword);
        }
        // Send notification if it should be sent.
        sendNotification(admin, notificationUserDataVO, newstatus);
        if (newstatus != oldstatus) {
            // Only print stuff on a printer on the same conditions as for
            // notifications, we also only print if the status changes, not for
            // every time we press save
            if ((type & SecConst.USER_PRINT) != 0 && (newstatus == UserDataConstants.STATUS_NEW
                    || newstatus == UserDataConstants.STATUS_KEYRECOVERY
                    || newstatus == UserDataConstants.STATUS_INITIALIZED)) {
                print(admin, profile, userDataVO);
            }
            final String msg = intres.getLocalizedMessage("ra.editedentitystatus", username,
                    Integer.valueOf(newstatus));
            logSession.log(admin, caid, LogConstants.MODULE_RA, new Date(), username, null,
                    LogConstants.EVENT_INFO_CHANGEDENDENTITY, msg);
        } else {
            final String msg = intres.getLocalizedMessage("ra.editedentity", username);
            logSession.log(admin, caid, LogConstants.MODULE_RA, new Date(), username, null,
                    LogConstants.EVENT_INFO_CHANGEDENDENTITY, msg);
        }
    } catch (Exception e) {
        final String msg = intres.getLocalizedMessage("ra.erroreditentity", username);
        logSession.log(admin, caid, LogConstants.MODULE_RA, new Date(), username, null,
                LogConstants.EVENT_ERROR_CHANGEDENDENTITY, msg);
        log.error("ChangeUser:", e);
        throw new EJBException(e);
    }
    if (log.isTraceEnabled()) {
        log.trace("<changeUser(" + username + ", password, " + dn + ", " + userDataVO.getEmail() + ")");
    }
}

From source file:org.ejbca.core.ejb.ca.store.CertificateStoreSessionBean.java

@TransactionAttribute(TransactionAttributeType.REQUIRED)
@Override//  w  w  w . j  a v a  2s .  c  o m
// TODO: Does not publish revocations to publishers!!!
// TODO: Enforce or drop Admin parameter
public void revokeAllCertByCA(Admin admin, String issuerdn, int reason) {
    int temprevoked = 0;
    int revoked = 0;
    String bcdn = CertTools.stringToBCDNString(issuerdn);
    try {
        // Change all temporaty revoked certificates to permanently revoked certificates
        temprevoked = CertificateData.revokeOnHoldPermanently(entityManager, bcdn);
        // Revoking all non revoked certificates.
        revoked = CertificateData.revokeAllNonRevokedCertificates(entityManager, bcdn, reason);
        String msg = intres.getLocalizedMessage("store.revokedallbyca", issuerdn,
                Integer.valueOf(revoked + temprevoked), Integer.valueOf(reason));
        logSession.log(admin, bcdn.hashCode(), LogConstants.MODULE_CA, new java.util.Date(), null, null,
                LogConstants.EVENT_INFO_REVOKEDCERT, msg);
    } catch (Exception e) {
        String msg = intres.getLocalizedMessage("store.errorrevokeallbyca", issuerdn);
        logSession.log(admin, bcdn.hashCode(), LogConstants.MODULE_CA, new java.util.Date(), null, null,
                LogConstants.EVENT_ERROR_REVOKEDCERT, msg, e);
        throw new EJBException(e);
    }
}