Package org.ejbca.core.model.approval

Examples of org.ejbca.core.model.approval.ApprovalRequest


    Admin admin = ejbhelper.getAdmin(true);
    int endEntityProfileId = 0;
    boolean hardTokenExists = false;
    boolean userExists = false;
   
    ApprovalRequest ar = null;
    boolean approvalSuccessfullStep1 = false;
    boolean isRejectedStep1 = false;

    // Get Significant user Id
    final CAInfo significantcAInfo;
    final ArrayList<java.security.cert.Certificate> genCertificates = new ArrayList<java.security.cert.Certificate>();
    final IPatternLogger logger = TransactionLogger.getPatternLogger();
        logAdminName(admin,logger);
    try {
      significantcAInfo = caAdminSession.getCAInfoOrThrowException(intAdmin, userDataWS.getCaName());
    if(significantcAInfo == null){
      throw EjbcaWSHelper.getEjbcaException("Error the given CA : " + userDataWS.getCaName() + " couldn't be found.",
          logger, ErrorCode.CA_NOT_EXISTS, null);
    }
   
      UserDataVO userDataVO = userAdminSession.findUser(intAdmin, userDataWS.getUsername());
      if(userDataVO != null){
        endEntityProfileId = userDataVO.getEndEntityProfileId();
        userExists = true;
      }else{
        endEntityProfileId = endEntityProfileSession.getEndEntityProfileId(intAdmin, userDataWS.getEndEntityProfileName());         
        if(endEntityProfileId == 0){
          throw EjbcaWSHelper.getEjbcaException("Error given end entity profile : " + userDataWS.getEndEntityProfileName() +" couldn't be found",
            logger, ErrorCode.EE_PROFILE_NOT_EXISTS, null);
        }
      }
     
     
      if(ejbhelper.isAdmin()){     
       
                if (!authorizationSession.isAuthorizedNoLog(admin, AccessRulesConstants.REGULAR_CREATECERTIFICATE)) {
                    Authorizer.throwAuthorizationException(admin, AccessRulesConstants.REGULAR_CREATECERTIFICATE, null);
                }
                if (!authorizationSession.isAuthorizedNoLog(admin, AccessRulesConstants.HARDTOKEN_ISSUEHARDTOKENS)) {
                    Authorizer.throwAuthorizationException(admin, AccessRulesConstants.HARDTOKEN_ISSUEHARDTOKENS, null);
                }
                if (!authorizationSession.isAuthorizedNoLog(admin, AccessRulesConstants.CAPREFIX + significantcAInfo.getCAId())) {
                    throw new AuthorizationDeniedException("Admin " + admin + " was not authorized to resource " + AccessRulesConstants.CAPREFIX
                            + significantcAInfo.getCAId());
                }
                if (userExists) {
                    if (!authorizationSession.isAuthorizedNoLog(admin, AccessRulesConstants.REGULAR_EDITENDENTITY)) {
                        Authorizer.throwAuthorizationException(admin, AccessRulesConstants.REGULAR_EDITENDENTITY, null);
                    }
                    endEntityProfileId = userDataVO.getEndEntityProfileId();
                    if (!authorizationSession.isAuthorizedNoLog(admin, AccessRulesConstants.ENDENTITYPROFILEPREFIX + endEntityProfileId
                            + AccessRulesConstants.EDIT_RIGHTS)) {
                        Authorizer.throwAuthorizationException(admin, AccessRulesConstants.ENDENTITYPROFILEPREFIX + endEntityProfileId
                                + AccessRulesConstants.EDIT_RIGHTS, null);
                    }

                    if (overwriteExistingSN) {
                        if (!authorizationSession.isAuthorizedNoLog(admin, AccessRulesConstants.REGULAR_REVOKEENDENTITY)) {
                            Authorizer.throwAuthorizationException(admin, AccessRulesConstants.REGULAR_REVOKEENDENTITY, null);
                        }
                        if (!authorizationSession.isAuthorizedNoLog(admin, AccessRulesConstants.ENDENTITYPROFILEPREFIX + endEntityProfileId
                                + AccessRulesConstants.REVOKE_RIGHTS)) {
                            Authorizer.throwAuthorizationException(admin, AccessRulesConstants.ENDENTITYPROFILEPREFIX + endEntityProfileId
                                    + AccessRulesConstants.REVOKE_RIGHTS, null);
                        }
                    }
                } else {
                    if (!authorizationSession.isAuthorizedNoLog(admin, AccessRulesConstants.REGULAR_CREATEENDENTITY)) {
                        Authorizer.throwAuthorizationException(admin, AccessRulesConstants.REGULAR_CREATEENDENTITY, null);
                    }
                    if (!authorizationSession.isAuthorizedNoLog(admin, AccessRulesConstants.ENDENTITYPROFILEPREFIX + endEntityProfileId
                            + AccessRulesConstants.CREATE_RIGHTS)) {
                        Authorizer.throwAuthorizationException(admin, AccessRulesConstants.ENDENTITYPROFILEPREFIX + endEntityProfileId
                                + AccessRulesConstants.CREATE_RIGHTS, null);
                    }
                    if (overwriteExistingSN) {
                        if (!authorizationSession.isAuthorizedNoLog(admin, AccessRulesConstants.REGULAR_REVOKEENDENTITY)) {
                            Authorizer.throwAuthorizationException(admin, AccessRulesConstants.REGULAR_REVOKEENDENTITY, null);
                        }
                        if (!authorizationSession.isAuthorizedNoLog(admin, AccessRulesConstants.ENDENTITYPROFILEPREFIX + endEntityProfileId
                                + AccessRulesConstants.REVOKE_RIGHTS)) {
                            Authorizer.throwAuthorizationException(admin, AccessRulesConstants.ENDENTITYPROFILEPREFIX + endEntityProfileId
                                    + AccessRulesConstants.REVOKE_RIGHTS, null);
                        }
                    }
                }

      }else{
        if(WebServiceConfiguration.getApprovalForGenTokenCertificates()){
          ar = new GenerateTokenApprovalRequest(userDataWS.getUsername(), userDataWS.getSubjectDN(), hardTokenDataWS.getLabel(),admin,null,WebServiceConfiguration.getNumberOfRequiredApprovals(),significantcAInfo.getCAId(),endEntityProfileId);
          int status = ApprovalDataVO.STATUS_REJECTED;          
          try{
            status = approvalSession.isApproved(admin, ar.generateApprovalId(), 1);
            approvalSuccessfullStep1 =  status == ApprovalDataVO.STATUS_APPROVED;
            if(approvalSuccessfullStep1){
              ApprovalDataVO approvalDataVO = approvalSession.findNonExpiredApprovalRequest(intAdmin, ar.generateApprovalId());
              String originalDN = ((GenerateTokenApprovalRequest) approvalDataVO.getApprovalRequest()).getDN();
              userDataWS.setSubjectDN(originalDN); // replace requested DN with original DN to make sure nothing have changed.
            }
            isRejectedStep1 = status == ApprovalDataVO.STATUS_REJECTED;
            if(   status == ApprovalDataVO.STATUS_EXPIREDANDNOTIFIED
               || status == ApprovalDataVO.STATUS_EXPIRED){
              throw new ApprovalException("");
            }
          }catch(ApprovalException e){
            approvalSession.addApprovalRequest(admin, ar, globalConfigurationSession.getCachedGlobalConfiguration(admin));
            throw new WaitingForApprovalException("Approval request with id " + ar.generateApprovalId() + " have been added for approval.",ar.generateApprovalId());
          }
        }else{
          throw new AuthorizationDeniedException();
        }
      }

    if(ar != null && isRejectedStep1){
      throw new ApprovalRequestExecutionException("The approval for id " + ar.generateApprovalId() + " have been rejected.");
    }
   
    if(ar != null && !approvalSuccessfullStep1){
      throw new WaitingForApprovalException("The approval for id " + ar.generateApprovalId() + " have not yet been approved", ar.generateApprovalId());
    }
   
    if(ar != null){
      admin = new ApprovedActionAdmin(admin.getAdminInformation().getX509Certificate(), admin.getUsername(), admin.getEmail());
    }
   
      hardTokenExists = hardTokenSession.existsHardToken(admin, hardTokenDataWS.getHardTokenSN());
      if(hardTokenExists){
        if(overwriteExistingSN){
          // fetch all old certificates and revoke them.
          Collection<java.security.cert.Certificate> currentCertificates = hardTokenSession.findCertificatesInHardToken(admin, hardTokenDataWS.getHardTokenSN());
          HardTokenData currentHardToken = hardTokenSession.getHardToken(admin, hardTokenDataWS.getHardTokenSN(), false);
          Iterator<java.security.cert.Certificate> iter = currentCertificates.iterator();
          while(iter.hasNext()){
            java.security.cert.X509Certificate nextCert = (java.security.cert.X509Certificate) iter.next();
            try {
              userAdminSession.revokeCert(admin, CertTools.getSerialNumber(nextCert), CertTools.getIssuerDN(nextCert), RevokedCertInfo.REVOCATION_REASON_SUPERSEDED);
            } catch (AlreadyRevokedException e) {
              // Ignore previously revoked certificates
            } catch (FinderException e) {
                            throw EjbcaWSHelper.getEjbcaException("Error revoking old certificate, the user : " + currentHardToken.getUsername() + " of the old certificate couldn't be found in database.",
                                                    logger, ErrorCode.USER_NOT_FOUND, null);
            }
          }

        }else{
          throw new HardTokenExistsException("Error hard token with sn " + hardTokenDataWS.getHardTokenSN() + " already exists.");
        }

      }


      if(revokePreviousCards){
        List<HardTokenDataWS> htd = getHardTokenDatas(admin,userDataWS.getUsername(), false, true, logger);
        Iterator<HardTokenDataWS> htdIter = htd.iterator();

        while(htdIter.hasNext()) {
          HardTokenDataWS toRevoke = htdIter.next();
          try{
              if(hardTokenDataWS.getLabel().equals(HardTokenConstants.LABEL_TEMPORARYCARD) && toRevoke.getLabel() != null && !toRevoke.getLabel().equals(HardTokenConstants.LABEL_TEMPORARYCARD)){

                // Token have extended key usage MS Logon, don't revoke it
                Iterator<java.security.cert.Certificate> revokeCerts = hardTokenSession.findCertificatesInHardToken(admin, toRevoke.getHardTokenSN()).iterator();

                while(revokeCerts.hasNext()){
                  X509Certificate next = (X509Certificate) revokeCerts.next();              
                  try{
                    if(WebServiceConfiguration.getSuspendAllCertificates() || next.getExtendedKeyUsage() == null || !next.getExtendedKeyUsage().contains(KeyPurposeId.id_kp_smartcardlogon.getId())){
                      userAdminSession.revokeCert(admin,next.getSerialNumber(), CertTools.getIssuerDN(next), RevokedCertInfo.REVOCATION_REASON_CERTIFICATEHOLD);
                    }
                  }catch(CertificateParsingException e){
                    log.error(e);
                  } catch (FinderException e) {
                    log.error(e);
                 
                }
           

            }else{
              revokeToken(admin, toRevoke.getHardTokenSN(), RevokedCertInfo.REVOCATION_REASON_UNSPECIFIED, logger);
            }
          }catch(AlreadyRevokedException e){
            // Do nothing
          }
        }
      }
   
    try{
      // Check if the userdata exist and edit/add it depending on which
      String password = PasswordGeneratorFactory.getInstance(PasswordGeneratorFactory.PASSWORDTYPE_ALLPRINTABLE).getNewPassword(8, 8);
      UserDataVO userData = ejbhelper.convertUserDataVOWS(admin, userDataWS);
      userData.setPassword(password);
      if(userExists){
        userAdminSession.changeUser(admin, userData, true);
      }else{
        userAdminSession.addUser(admin, userData, true);
      }

      Date bDate = new Date(System.currentTimeMillis() - (10 * 60 * 1000));
     
      Iterator<TokenCertificateRequestWS> iter = tokenRequests.iterator();
      while(iter.hasNext()){
        TokenCertificateRequestWS next = iter.next();

        int certificateProfileId = certificateProfileSession.getCertificateProfileId(admin, next.getCertificateProfileName());
        if(certificateProfileId == 0){
                    EjbcaWSHelper.getEjbcaException("Error the given Certificate Profile : " + next.getCertificateProfileName() + " couldn't be found.",
                                      logger, ErrorCode.CERT_PROFILE_NOT_EXISTS, null);
        }
       
        Date eDate = null;
       
        if(next.getValidityIdDays() != null ){
          try{
            long validity = Long.parseLong(next.getValidityIdDays());
            eDate = new Date(System.currentTimeMillis() + (validity  * 3600 *24 * 1000));
          }catch (NumberFormatException e){
                        EjbcaWSHelper.getEjbcaException("Error : Validity in Days must be a number",
                                          logger, ErrorCode.BAD_VALIDITY_FORMAT, null);
          }
        }
       
        CAInfo cAInfo = caAdminSession.getCAInfo(admin, next.getCAName());
        if(cAInfo == null){
          throw EjbcaWSHelper.getEjbcaException("Error the given CA : " + next.getCAName() + " couldn't be found.",
            logger, ErrorCode.CA_NOT_EXISTS, null);
        }

        if(!authorizationSession.isAuthorizedNoLog(admin, AccessRulesConstants.CAPREFIX + cAInfo.getCAId())) {
            Authorizer.throwAuthorizationException(admin, AccessRulesConstants.CAPREFIX + cAInfo.getCAId(), null);
        }
        if(next.getType() == HardTokenConstants.REQUESTTYPE_PKCS10_REQUEST){           
          userData.setCertificateProfileId(certificateProfileId);
          userData.setCAId(cAInfo.getCAId());
          userData.setPassword(password);
          userData.setStatus(UserDataConstants.STATUS_NEW);
          userAdminSession.changeUser(admin, userData, false);
          PKCS10RequestMessage pkcs10req = new PKCS10RequestMessage(next.getPkcs10Data());
          java.security.cert.Certificate cert;
          if(eDate == null){
              cert =  signSession.createCertificate(admin,userData.getUsername(),password, pkcs10req.getRequestPublicKey());
          }else{
            cert =  signSession.createCertificate(admin,userData.getUsername(),password, pkcs10req.getRequestPublicKey(), -1, bDate, eDate);
          }
         
          genCertificates.add(cert);
          retval.add(new TokenCertificateResponseWS(new Certificate(cert)));
        }else
          if(next.getType() == HardTokenConstants.REQUESTTYPE_KEYSTORE_REQUEST){

            if(!next.getTokenType().equals(HardTokenConstants.TOKENTYPE_PKCS12)){
              throw EjbcaWSHelper.getEjbcaException("Unsupported Key Store Type : " + next.getTokenType() + " only " + HardTokenConstants.TOKENTYPE_PKCS12 + " is supported",
                                                        logger, ErrorCode.NOT_SUPPORTED_KEY_STORE, null);
            }
            KeyPair keys = KeyTools.genKeys(next.getKeyspec(), next.getKeyalg());               
            userData.setCertificateProfileId(certificateProfileId);
            userData.setCAId(cAInfo.getCAId());
            userData.setPassword(password);
            userData.setStatus(UserDataConstants.STATUS_NEW);
            userAdminSession.changeUser(admin, userData, true);
            X509Certificate cert;
            if(eDate == null){
                cert =  (X509Certificate) signSession.createCertificate(admin,userData.getUsername(),password, keys.getPublic());
            }else{
              cert =  (X509Certificate) signSession.createCertificate(admin,userData.getUsername(),password, keys.getPublic(), -1, bDate, eDate);
            }
           
            genCertificates.add(cert);     
            // Generate Keystore
            // Fetch CA Cert Chain.         
            Collection<java.security.cert.Certificate> chain =  caAdminSession.getCAInfo(admin, cAInfo.getCAId()).getCertificateChain();
            String alias = CertTools.getPartFromDN(CertTools.getSubjectDN(cert), "CN");
            if (alias == null){
              alias = userData.getUsername();
            }               
            java.security.KeyStore pkcs12 = KeyTools.createP12(alias, keys.getPrivate(), cert, chain);

            retval.add(new TokenCertificateResponseWS(new KeyStore(pkcs12, userDataWS.getPassword())));
          }else{
            throw EjbcaWSHelper.getEjbcaException("Error in request, only REQUESTTYPE_PKCS10_REQUEST and REQUESTTYPE_KEYSTORE_REQUEST are supported token requests.",
              logger, ErrorCode.NOT_SUPPORTED_REQUEST_TYPE, null);
          }
      }

    } catch(Exception e){
            throw EjbcaWSHelper.getInternalException(e, logger);
    } finally{
      userAdminSession.setUserStatus(admin, userDataWS.getUsername(), UserDataConstants.STATUS_GENERATED);
    }

    // Add hard token data
    HardToken hardToken;
    String signatureInitialPIN = "";
    String signaturePUK = "";
    String basicInitialPIN = "";
    String basicPUK = "";
    Iterator<PinDataWS> iter = hardTokenDataWS.getPinDatas().iterator();
    while(iter.hasNext()){
      PinDataWS pinData = iter.next();
      switch(pinData.getType()){
      case HardTokenConstants.PINTYPE_BASIC :
        basicInitialPIN = pinData.getInitialPIN();
        basicPUK = pinData.getPUK();
        break;
      case HardTokenConstants.PINTYPE_SIGNATURE :
        signatureInitialPIN = pinData.getInitialPIN();
        signaturePUK = pinData.getPUK();
        break;
      default :
        throw EjbcaWSHelper.getEjbcaException("Unsupported PIN Type " + pinData.getType(),
          logger, ErrorCode.NOT_SUPPORTED_PIN_TYPE, null);
      }
    }
    int tokenType = SwedishEIDHardToken.THIS_TOKENTYPE;
    switch (hardTokenDataWS.getTokenType()){
    case HardTokenConstants.TOKENTYPE_SWEDISHEID :
      hardToken = new SwedishEIDHardToken(basicInitialPIN,basicPUK,signatureInitialPIN,signaturePUK,0)
      break;
    case HardTokenConstants.TOKENTYPE_ENHANCEDEID :
      hardToken = new EnhancedEIDHardToken(signatureInitialPIN,signaturePUK,basicInitialPIN,basicPUK,false,0);
      tokenType = EnhancedEIDHardToken.THIS_TOKENTYPE;
      break;
    default:
      throw EjbcaWSHelper.getEjbcaException("Unsupported Token Type : " + hardTokenDataWS.getTokenType(),
        logger, ErrorCode.NOT_SUPPORTED_TOKEN_TYPE, null);

    }

    hardToken.setLabel(hardTokenDataWS.getLabel());
      if(overwriteExistingSN){
        if(hardTokenExists){
          try {
            hardTokenSession.removeHardToken(admin, hardTokenDataWS.getHardTokenSN());
          } catch (HardTokenDoesntExistsException e) {
            throw EjbcaWSHelper.getEjbcaException(e, logger, ErrorCode.HARD_TOKEN_NOT_EXISTS, Level.ERROR);
          }
        }
      }
      hardTokenSession.addHardToken(admin, hardTokenDataWS.getHardTokenSN(), userDataWS.getUsername(), significantcAInfo.getSubjectDN(), tokenType, hardToken, genCertificates, hardTokenDataWS.getCopyOfSN());

      if(ar!= null){
        approvalSession.markAsStepDone(admin, ar.generateApprovalId(), GenerateTokenApprovalRequest.STEP_1_GENERATETOKEN);
      }
        } catch( EjbcaException e) {
            throw e;
        } catch (FinderException e) {
            throw EjbcaWSHelper.getInternalException(e, logger);
View Full Code Here


  public HardTokenDataWS getHardTokenData(String hardTokenSN, boolean viewPUKData, boolean onlyValidCertificates)
    throws CADoesntExistsException, AuthorizationDeniedException, HardTokenDoesntExistsException, NotFoundException, ApprovalRequestExpiredException, WaitingForApprovalException, ApprovalRequestExecutionException, EjbcaException {
    HardTokenDataWS retval = null;
    EjbcaWSHelper ejbhelper = new EjbcaWSHelper(wsContext, authorizationSession, caAdminSession, certificateProfileSession, certificateStoreSession, endEntityProfileSession, hardTokenSession, userAdminSession);
    Admin admin = ejbhelper.getAdmin(true);
    ApprovalRequest ar = null;
    boolean isApprovedStep0 = false;
    boolean isRejectedStep0 = false;

    HardTokenData hardTokenData = null;
    final IPatternLogger logger = TransactionLogger.getPatternLogger();
        logAdminName(admin,logger);
        try {
    try{
      hardTokenData = hardTokenSession.getHardToken(admin, hardTokenSN, viewPUKData);
      if(hardTokenData == null){
        throw new HardTokenDoesntExistsException("Error, hard token with SN " + hardTokenSN + " doesn't exist.");
      }
      ejbhelper.isAuthorizedToHardTokenData(admin, hardTokenData.getUsername(), viewPUKData);
    }catch(AuthorizationDeniedException e){
      boolean genNewRequest = false;
      if(WebServiceConfiguration.getApprovalForHardTokenData()){
        // Check Approvals
        // Exists an GenTokenCertificates
          Admin intAdmin = Admin.getInternalAdmin();
          UserDataVO userData = userAdminSession.findUser(intAdmin, hardTokenData.getUsername());
          if (userData == null) {
            String msg = intres.getLocalizedMessage("ra.errorentitynotexist", hardTokenData.getUsername());             
            throw new NotFoundException(msg);
          }
          int caid = userData.getCAId();
          caAdminSession.verifyExistenceOfCA(caid);
          ar = new GenerateTokenApprovalRequest(userData.getUsername(), userData.getDN(), hardTokenData.getHardToken().getLabel(),admin,null,WebServiceConfiguration.getNumberOfRequiredApprovals(),caid,userData.getEndEntityProfileId());
          int status = ApprovalDataVO.STATUS_REJECTED;          
          try{
            if(!WebServiceConfiguration.getApprovalForGenTokenCertificates()){
              throw new ApprovalException("");
            }
            status = approvalSession.isApproved(admin, ar.generateApprovalId(), 0);
            isApprovedStep0 =  status == ApprovalDataVO.STATUS_APPROVED;
           
            if(   status == ApprovalDataVO.STATUS_EXPIREDANDNOTIFIED
                || status == ApprovalDataVO.STATUS_EXPIRED
                || status == ApprovalDataVO.STATUS_REJECTED){
              throw new ApprovalException("");
            }
          }catch(ApprovalException e2){
            // GenTokenCertificates approval doesn't exists, try a getHardTokenData request
            if(!WebServiceConfiguration.getApprovalForHardTokenData()){
                throw new AuthorizationDeniedException("JaxWS isn't configured for getHardTokenData approvals.");
            }
            ar = new ViewHardTokenDataApprovalRequest(userData.getUsername(), userData.getDN(), hardTokenSN, true,admin,null,WebServiceConfiguration.getNumberOfRequiredApprovals(),userData.getCAId(),userData.getEndEntityProfileId());
            try{
              status = approvalSession.isApproved(admin, ar.generateApprovalId());
              isApprovedStep0 = status == ApprovalDataVO.STATUS_APPROVED;
              isRejectedStep0 =  status == ApprovalDataVO.STATUS_REJECTED;
              if(   status == ApprovalDataVO.STATUS_EXPIREDANDNOTIFIED
                     || status == ApprovalDataVO.STATUS_EXPIRED){
                throw new ApprovalException("");
              }
            }catch(ApprovalException e3){
              genNewRequest = true;
            }catch(ApprovalRequestExpiredException e3){
              genNewRequest = true;
            }
            if(genNewRequest){
                            //  Add approval Request
              try{
                approvalSession.addApprovalRequest(admin, ar, globalConfigurationSession.getCachedGlobalConfiguration(admin));
                throw new WaitingForApprovalException("Adding approval to view hard token data with id " + ar.generateApprovalId(), ar.generateApprovalId());
              }catch(ApprovalException e4){
                throw EjbcaWSHelper.getEjbcaException(e4, logger, ErrorCode.APPROVAL_ALREADY_EXISTS, null);
              }
            }
          }   
      }else{
        throw e;
      }
    }
   
    if(ar != null && isRejectedStep0){
      throw new ApprovalRequestExecutionException("The approval for id " + ar.generateApprovalId() + " have been rejected.");
    }
   
    if(ar != null && ! isApprovedStep0){
      throw new WaitingForApprovalException("The approval for id " + ar.generateApprovalId() + " have not yet been approved", ar.generateApprovalId());
    }
   
      Collection<java.security.cert.Certificate> certs = hardTokenSession.findCertificatesInHardToken(admin, hardTokenSN);

      if(onlyValidCertificates){
        certs = ejbhelper.returnOnlyValidCertificates(admin, certs);
      }

      retval = ejbhelper.convertHardTokenToWS(hardTokenData,certs,viewPUKData);   

      if(ar != null){
        try {
          approvalSession.markAsStepDone(admin, ar.generateApprovalId(), 0);
        } catch (ApprovalException e) {
          throw EjbcaWSHelper.getEjbcaException(e, logger, ErrorCode.APPROVAL_REQUEST_ID_NOT_EXIST, null);
        }
      }
        } catch (RuntimeException e) {  // EJBException, ...
View Full Code Here

        final String serialNumber = "12344711";

        setUpNonAdmin();
        setupApprovals();

        ApprovalRequest approvalRequest = new ViewHardTokenDataApprovalRequest(TEST_NONADMIN_USERNAME, TEST_NONADMIN_CN, serialNumber, true, reqadmin, null, 1,
                0, 0);

        // Setup the test
        if (!hardTokenSessionRemote.existsHardToken(reqadmin, serialNumber)) {
            /*
             * Add an arbitrary token for the below two tests to wait for
             * (should such a token not already exist due to sloppy cleanup).
             */
            hardTokenSessionRemote.addHardToken(reqadmin, serialNumber, TEST_NONADMIN_USERNAME, TEST_NONADMIN_CN, SecConst.TOKEN_SWEDISHEID,
                    new SwedishEIDHardToken("1234", "12345678", "5678", "23456789", 1), new ArrayList<Certificate>(), null);

        }

        // Make sure that the ApprovalSession is clean.
        cleanApprovalRequestFromApprovalSession(approvalRequest, reqadmin);

        try {

            try {
                getHardTokenData(serialNumber, true);
                assertTrue(false);
            } catch (WaitingForApprovalException_Exception e) {
            }

            try {
                getHardTokenData(serialNumber, true);
                assertTrue(false);
            } catch (WaitingForApprovalException_Exception e) {
            }

            Approval approval1 = new Approval("ap1test");
            try {
                approvalExecutionSession.approve(admin1, approvalRequest.generateApprovalId(), approval1, gc);
                getHardTokenData(serialNumber, true);
                try {
                    getHardTokenData(serialNumber, true);
                    assertTrue(false);
                } catch (WaitingForApprovalException_Exception e) {
                }
                approvalSession.reject(admin1, approvalRequest.generateApprovalId(), approval1, gc);
                try {
                    getHardTokenData(serialNumber, true);
                    assertTrue(false);
                } catch (ApprovalRequestExecutionException_Exception e) {
                }
View Full Code Here

        }
    }

    public void test03CleanGetHardTokenDataWithApprovals() throws Exception {
        setupApprovals();
        ApprovalRequest ar = new ViewHardTokenDataApprovalRequest("WSTESTTOKENUSER1", "CN=WSTESTTOKENUSER1", "12345678", true, reqadmin, null, 1, 0, 0);

        Collection<ApprovalDataVO> result = approvalSession.findApprovalDataVO(intAdmin, ar.generateApprovalId());
        Iterator<ApprovalDataVO> iter = result.iterator();
        while (iter.hasNext()) {
            ApprovalDataVO next = iter.next();
            approvalSession.removeApprovalRequest(admin1, next.getId());
        }
View Full Code Here

        } catch (WaitingForApprovalException_Exception e) {
        }

        Approval approval1 = new Approval("ap1test");

        ApprovalRequest ar = new GenerateTokenApprovalRequest("WSTESTTOKENUSER1", "CN=WSTESTTOKENUSER1", HardToken.LABEL_PROJECTCARD, reqadmin, null, 1, 0, 0);
        approvalExecutionSession.approve(admin1, ar.generateApprovalId(), approval1, gc);

        genTokenCertificates(true);

        try {
            getHardTokenData("12345678", true);
            assertTrue(false);
        } catch (WaitingForApprovalException_Exception e) {
        }

        try {
            genTokenCertificates(true);
            assertTrue(false);
        } catch (WaitingForApprovalException_Exception e) {
        }

        approvalSession.reject(admin1, ar.generateApprovalId(), approval1, gc);

        try {
            genTokenCertificates(true);
            assertTrue(false);
        } catch (ApprovalRequestExecutionException_Exception e) {
View Full Code Here

        removeApprovalAdmins();
    }

    public void test05CleanGenTokenCertificatesWithApprovals() throws Exception {
        setupApprovals();
        ApprovalRequest ar = new GenerateTokenApprovalRequest("WSTESTTOKENUSER1", "CN=WSTESTTOKENUSER1", HardToken.LABEL_PROJECTCARD, reqadmin, null, 1, 0, 0);

        Collection<ApprovalDataVO> result = approvalSession.findApprovalDataVO(intAdmin, ar.generateApprovalId());
        Iterator<ApprovalDataVO> iter = result.iterator();
        while (iter.hasNext()) {
            ApprovalDataVO next = iter.next();
            approvalSession.removeApprovalRequest(admin1, next.getId());
        }

        ar = new ViewHardTokenDataApprovalRequest("WSTESTTOKENUSER1", "CN=WSTESTTOKENUSER1", "12345678", true, reqadmin, null, 1, 0, 0);

        result = approvalSession.findApprovalDataVO(intAdmin, ar.generateApprovalId());
        iter = result.iterator();
        while (iter.hasNext()) {
            ApprovalDataVO next = iter.next();
            approvalSession.removeApprovalRequest(admin1, next.getId());
        }
View Full Code Here

        }
        return retval;
    }
   
    private List<ApprovalDataText> getNewRequestDataAsText() {
      ApprovalRequest approvalRequest = data.getApprovalRequest();
      Admin admin = EjbcaJSFHelper.getBean().getAdmin();
      if (approvalRequest instanceof EditEndEntityApprovalRequest) {
        return ((EditEndEntityApprovalRequest)approvalRequest).getNewRequestDataAsText(admin, ejb.getCaAdminSession(),
            ejb.getEndEntityProfileSession(), ejb.getCertificateProfileSession(), ejb.getHardTokenSession());
      } else if (approvalRequest instanceof AddEndEntityApprovalRequest) {
        return ((AddEndEntityApprovalRequest)approvalRequest).getNewRequestDataAsText(admin, ejb.getCaAdminSession(),
            ejb.getEndEntityProfileSession(), ejb.getCertificateProfileSession(), ejb.getHardTokenSession());
      } else {
        return approvalRequest.getNewRequestDataAsText(admin);
      }
    }
View Full Code Here

        return approvalRequest.getNewRequestDataAsText(admin);
      }
    }

    private List<ApprovalDataText> getOldRequestDataAsText() {
      ApprovalRequest approvalRequest = data.getApprovalRequest();
      Admin admin = EjbcaJSFHelper.getBean().getAdmin();
      if (approvalRequest instanceof EditEndEntityApprovalRequest) {
        return ((EditEndEntityApprovalRequest)approvalRequest).getOldRequestDataAsText(admin, ejb.getCaAdminSession(),
            ejb.getEndEntityProfileSession(), ejb.getCertificateProfileSession(), ejb.getHardTokenSession());
      } else {
        return approvalRequest.getOldRequestDataAsText(admin);
      }
    }
View Full Code Here

   * expired.
   *
   * @throws ApprovalRequestExpiredException if the step have already been executed
   */
  private void markStepAsDone(final ApprovalData approvalData, final int step) throws ApprovalRequestExpiredException {
    final ApprovalRequest ar = getApprovalRequest(approvalData);
    if (!ar.isExecutable() && approvalData.getStatus() == ApprovalDataVO.STATUS_APPROVED) {
      if (!ar.isStepDone(step)) {
        ar.markStepAsDone(step);
        setApprovalRequest(approvalData, ar);
        if (step == ar.getNumberOfApprovalSteps()-1) {
          approvalData.setStatus(ApprovalDataVO.STATUS_EXPIRED);
        }
      } else {
        throw new ApprovalRequestExpiredException("Error step " + step + " of approval with id " + approvalData.getApprovalid() + " have alread been performed");
      }
View Full Code Here

    approvalData.setRemainingapprovals(numberofapprovalsleft);
    final Collection<Approval> approvals = approvalSession.getApprovals(approvalData);
    approvals.add(approval);
    approvalSession.setApprovals(approvalData, approvals);
    if(numberofapprovalsleft == 0){
      final ApprovalRequest approvalRequest = approvalSession.getApprovalRequest(approvalData);
      if(approvalRequest.isExecutable()){
        try{
          if (approvalRequest instanceof ActivateCATokenApprovalRequest) {
            ((ActivateCATokenApprovalRequest)approvalRequest).execute(caAdminSession);
          } else if (approvalRequest instanceof AddEndEntityApprovalRequest) {
            ((AddEndEntityApprovalRequest)approvalRequest).execute(userAdminSession);
          } else if (approvalRequest instanceof ChangeStatusEndEntityApprovalRequest) {
            ((ChangeStatusEndEntityApprovalRequest)approvalRequest).execute(userAdminSession);
          } else if (approvalRequest instanceof EditEndEntityApprovalRequest) {
            ((EditEndEntityApprovalRequest)approvalRequest).execute(userAdminSession);
          } else if (approvalRequest instanceof KeyRecoveryApprovalRequest) {
            ((KeyRecoveryApprovalRequest)approvalRequest).execute(userAdminSession);
          } else if (approvalRequest instanceof RevocationApprovalRequest) {
            ((RevocationApprovalRequest)approvalRequest).execute(userAdminSession);
          } else {
            approvalRequest.execute();
          }
          approvalData.setStatus(ApprovalDataVO.STATUS_EXECUTED);
        } catch(ApprovalRequestExecutionException e){
          approvalData.setStatus(ApprovalDataVO.STATUS_EXECUTIONFAILED);
          throw e;
        }
        approvalData.setStatus(ApprovalDataVO.STATUS_EXECUTED);
        approvalData.setExpireDate(new Date());
      }else{
        approvalData.setStatus(ApprovalDataVO.STATUS_APPROVED);
        approvalData.setExpiredate((new Date()).getTime() + approvalRequest.getApprovalValidity());
      }
    }
  }
View Full Code Here

TOP

Related Classes of org.ejbca.core.model.approval.ApprovalRequest

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.