@Test
 public void testGetPrincipalByPrincipalName() {
   Principal principal = identityService.getPrincipalByPrincipalName("kuluser");
   assertNotNull("principal must not be null", principal);
   assertEquals(
       "Principal ID did not match expected result", "KULUSER", principal.getPrincipalId());
 }
 protected boolean validGroupMemberPrincipalIDs(List<GroupDocumentMember> groupMembers) {
   boolean valid = true;
   List<String> principalIds = new ArrayList<String>();
   for (GroupDocumentMember groupMember : groupMembers) {
     if (StringUtils.equals(
         groupMember.getMemberTypeCode(),
         KimConstants.KimGroupMemberTypes.PRINCIPAL_MEMBER_TYPE.getCode())) {
       principalIds.add(groupMember.getMemberId());
     }
   }
   if (!principalIds.isEmpty()) {
     // retrieve valid principals/principal-ids from identity service
     List<Principal> validPrincipals = getIdentityService().getPrincipals(principalIds);
     List<String> validPrincipalIds = new ArrayList<String>(validPrincipals.size());
     for (Principal principal : validPrincipals) {
       validPrincipalIds.add(principal.getPrincipalId());
     }
     // check that there are no invalid principals in the principal list, return false
     List<String> invalidPrincipalIds =
         new ArrayList<String>(CollectionUtils.subtract(principalIds, validPrincipalIds));
     // if list is not empty add error messages and return false
     if (CollectionUtils.isNotEmpty(invalidPrincipalIds)) {
       GlobalVariables.getMessageMap()
           .putError(
               "document.member.memberId",
               RiceKeyConstants.ERROR_MEMBERID_MEMBERTYPE_MISMATCH,
               invalidPrincipalIds.toArray(new String[invalidPrincipalIds.size()]));
       valid = false;
     }
   }
   return valid;
 }
  public ActionForward addDelegationMember(
      ActionMapping mapping,
      ActionForm form,
      HttpServletRequest request,
      HttpServletResponse response)
      throws Exception {
    IdentityManagementRoleDocumentForm roleDocumentForm = (IdentityManagementRoleDocumentForm) form;
    RoleDocumentDelegationMember newDelegationMember = roleDocumentForm.getDelegationMember();

    // See if possible to add with just Group Details filled in (not returned from lookup)
    if (StringUtils.isEmpty(newDelegationMember.getMemberId())
        && StringUtils.isNotEmpty(newDelegationMember.getMemberName())
        && StringUtils.isNotEmpty(newDelegationMember.getMemberNamespaceCode())
        && StringUtils.equals(
            newDelegationMember.getMemberTypeCode(),
            KimConstants.KimGroupMemberTypes.GROUP_MEMBER_TYPE.getCode())) {
      Group tempGroup =
          KimApiServiceLocator.getGroupService()
              .getGroupByNamespaceCodeAndName(
                  newDelegationMember.getMemberNamespaceCode(),
                  newDelegationMember.getMemberName());
      if (tempGroup != null) {
        newDelegationMember.setMemberId(tempGroup.getId());
      }
    }

    // See if possible to grab details for Principal
    if (StringUtils.isEmpty(newDelegationMember.getMemberId())
        && StringUtils.isNotEmpty(newDelegationMember.getMemberName())
        && StringUtils.equals(
            newDelegationMember.getMemberTypeCode(),
            KimConstants.KimGroupMemberTypes.PRINCIPAL_MEMBER_TYPE.getCode())) {
      Principal principal =
          KimApiServiceLocator.getIdentityService()
              .getPrincipalByPrincipalName(newDelegationMember.getMemberName());
      if (principal != null) {
        newDelegationMember.setMemberId(principal.getPrincipalId());
      }
    }

    if (checkDelegationMember(newDelegationMember)
        && KRADServiceLocatorWeb.getKualiRuleService()
            .applyRules(
                new AddDelegationMemberEvent(
                    "", roleDocumentForm.getRoleDocument(), newDelegationMember))) {
      newDelegationMember.setDocumentNumber(roleDocumentForm.getDocument().getDocumentNumber());
      if (StringUtils.isEmpty(newDelegationMember.getDelegationTypeCode())) {
        newDelegationMember.setDelegationTypeCode(DelegationType.SECONDARY.getCode());
      }
      roleDocumentForm.getRoleDocument().addDelegationMember(newDelegationMember);
      roleDocumentForm.setDelegationMember(
          roleDocumentForm.getRoleDocument().getBlankDelegationMember());
    }
    return mapping.findForward(RiceConstants.MAPPING_BASIC);
  }
 @Test
 public void testGetDefaultEntityByPrincipalId() {
   String principalId = "KULUSER";
   EntityDefault info = identityService.getEntityDefaultByPrincipalId(principalId);
   assertNotNull("entity must not be null", info);
   assertNotNull("entity principals must not be null", info.getPrincipals());
   assertEquals("entity must have exactly 1 principal", 1, info.getPrincipals().size());
   for (Principal principalInfo : info.getPrincipals()) {
     assertEquals("Wrong principal id", principalId, principalInfo.getPrincipalId());
   }
   assertTrue(
       "entity external identifiers must not be null",
       (info.getExternalIdentifiers() == null) || info.getExternalIdentifiers().isEmpty());
 }
 public String getIdForPrincipalName(String principalName) {
   if (principalName == null) {
     throw new RiceIllegalArgumentException(
         "Can't lookup a principal ID for a null principal name.");
   }
   Principal principal =
       KimApiServiceLocator.getIdentityService().getPrincipalByPrincipalName(principalName);
   if (principal == null) {
     throw new RiceIllegalArgumentException(
         "Given principal name of '"
             + principalName
             + "' was invalid.  Failed to lookup a corresponding principal ID.");
   }
   return principal.getPrincipalId();
 }
  @Override
  protected List<? extends BusinessObject> getSearchResultsHelper(
      Map<String, String> fieldValues, boolean unbounded) {
    // perform the lookup on the asset representative first
    String principalName = fieldValues.get(CamsPropertyConstants.Asset.REP_USER_AUTH_ID);
    if (StringUtils.isNotBlank(principalName)) {
      Principal principal =
          KimApiServiceLocator.getIdentityService().getPrincipalByPrincipalName(principalName);

      if (principal == null) {
        return Collections.EMPTY_LIST;
      }
      // place the universal ID into the fieldValues map and remove the dummy attribute
      fieldValues.put(
          CamsPropertyConstants.Asset.REPRESENTATIVE_UNIVERSAL_IDENTIFIER,
          principal.getPrincipalId());
      fieldValues.remove(CamsPropertyConstants.Asset.REP_USER_AUTH_ID);
    }

    return super.getSearchResultsHelper(fieldValues, unbounded);
  }
  protected void addNoteAfterProcessingAgencyStagingExpense(
      MaintenanceDocument document, List<ErrorMessage> errors) {

    Principal kfsSystemUser =
        getIdentityService().getPrincipalByPrincipalName(KFSConstants.SYSTEM_USER);
    String errorText = getMessageAsString(errors);

    if (!StringUtils.isEmpty(errorText)) {
      // check maxLength on a Note and truncate if necessary
      Integer maxLength =
          getDataDictionaryService()
              .getAttributeMaxLength(Note.class, KRADConstants.NOTE_TEXT_PROPERTY_NAME);
      if (errorText.length() > maxLength) {
        LOG.warn("Adding a truncated error text to Note due to space limitations. Original text:");
        LOG.warn(errorText);
        errorText = errorText.substring(0, maxLength);
      }

      final Note newNote = getDocumentService().createNoteFromDocument(document, errorText);
      newNote.setAuthorUniversalIdentifier(kfsSystemUser.getPrincipalId());
      document.addNote(newNote);
      getNoteService().save(newNote);
    }
  }
  /**
   * @see
   *     org.kuali.kfs.module.ar.document.service.CustomerInvoiceDocumentService#getPrintableCustomerInvoiceDocumentsByInitiatorPrincipalName(java.lang.String)
   */
  @Override
  public List<CustomerInvoiceDocument> getPrintableCustomerInvoiceDocumentsByInitiatorPrincipalName(
      String initiatorPrincipalName) {
    if (StringUtils.isBlank(initiatorPrincipalName)) {
      throw new IllegalArgumentException(
          "The parameter [initiatorPrincipalName] passed in was null or blank.");
    }

    // IMPORTANT NOTES ABOUT THIS METHOD
    //
    // This method behaves differently than the other invoice printing methods. This is
    // because there's no way from within KFS to do a direct DB call to get all the invoices
    // you want. This is because workflow holds the document initiator, and you cant guarantee
    // that in a given implementation that you have access to that other db. It could be on
    // another box in another network, and you only have web-services access to the Rice box.
    //
    // Given that, we try to minimize the resource hit of this call as much as possible. First
    // we retrieve all invoices that havent been printed (ie, dont have a print date) and that
    // are marked for the USER print queue. At any given time that should be a manageable number of
    // documents.
    //
    // Then we walk through them, retrieve the full workflow-populated version of it, and only
    // return the ones that match the initiator.
    //
    // This isnt as performant a solution as the other getPrintableCustomerInvoiceBy...
    // methods, but its the best we can do in this release, and it should be manageable.

    //
    // attempt to retrieve the initiator person specified, and puke if not found
    Principal initiator =
        KimApiServiceLocator.getIdentityService()
            .getPrincipalByPrincipalName(initiatorPrincipalName);
    if (initiator == null) {
      throw new IllegalArgumentException(
          "The parameter value for initiatorPrincipalName ["
              + initiatorPrincipalName
              + "] passed in doesnt map to a person.");
    }

    // retrieve all the ready-to-print docs in the user-queue for all users
    List<String> printableUserQueueDocNumbers =
        customerInvoiceDocumentDao.getPrintableCustomerInvoiceDocumentNumbersFromUserQueue();

    // get all the documents that might be right, but this set includes documents generated
    // by the wrong user
    List<CustomerInvoiceDocument> customerInvoiceDocumentsSuperSet =
        new ArrayList<CustomerInvoiceDocument>();
    if (printableUserQueueDocNumbers.size() > 0) {
      try {
        for (Document doc :
            documentService.getDocumentsByListOfDocumentHeaderIds(
                CustomerInvoiceDocument.class, printableUserQueueDocNumbers)) {
          customerInvoiceDocumentsSuperSet.add((CustomerInvoiceDocument) doc);
        }
      } catch (WorkflowException e) {
        throw new RuntimeException("Unable to retrieve Customer Invoice Documents", e);
      }
    } else {
      customerInvoiceDocumentsSuperSet = new ArrayList<CustomerInvoiceDocument>();
    }

    // filter only the ones initiated by the correct user
    List<CustomerInvoiceDocument> customerInvoiceDocuments =
        new ArrayList<CustomerInvoiceDocument>();
    for (CustomerInvoiceDocument superSetDocument : customerInvoiceDocumentsSuperSet) {
      if (StringUtils.equalsIgnoreCase(
          superSetDocument.getDocumentHeader().getWorkflowDocument().getInitiatorPrincipalId(),
          initiator.getPrincipalId())) {
        customerInvoiceDocuments.add(superSetDocument);
      }
    }
    return customerInvoiceDocuments;
  }
  /**
   * Implements by instantiating a NotificationWorkflowDocument, which in turn interacts with
   * Workflow to set it up with an initiator of the passed in user id.
   *
   * @see
   *     org.kuali.rice.ken.service.NotificationWorkflowDocumentService#createAndAdHocRouteNotificationWorkflowDocument(org.kuali.rice.ken.bo.NotificationMessageDelivery,
   *     java.lang.String, java.lang.String, java.lang.String)
   */
  public String createAndAdHocRouteNotificationWorkflowDocument(
      NotificationMessageDelivery messageDelivery,
      String initiatorUserId,
      String recipientUserId,
      String annotation) {
    // obtain a workflow user object first
    // WorkflowIdDTO initiator = new WorkflowIdDTO(initiatorUserId);

    // now construct the workflow document, which will interact with workflow
    WorkflowDocument document;
    if (StringUtils.isNotBlank(messageDelivery.getNotification().getDocTypeName())) {
      document =
          NotificationWorkflowDocument.createNotificationDocument(
              initiatorUserId, messageDelivery.getNotification().getDocTypeName());
    } else {
      document = NotificationWorkflowDocument.createNotificationDocument(initiatorUserId);
    }

    // this is our loose foreign key to our message delivery record in notification
    document.setApplicationDocumentId(messageDelivery.getId().toString());
    // document.setAppDocId(messageDelivery.getId().toString());

    // now add the content of the notification as XML to the document
    document.setApplicationContent(
        messageContentService.generateNotificationMessage(
            messageDelivery.getNotification(), messageDelivery.getUserRecipientId()));

    if (!StringUtils.isBlank(messageDelivery.getNotification().getTitle())) {
      document.setTitle(messageDelivery.getNotification().getTitle());
    } else {
      LOG.error(
          "Encountered notification with no title set: Message Delivery #"
              + messageDelivery.getId()
              + ", Notification #"
              + messageDelivery.getNotification().getId());
    }

    // now set up the ad hoc route
    String actionRequested;
    if (NotificationConstants.DELIVERY_TYPES.ACK.equals(
        messageDelivery.getNotification().getDeliveryType())) {
      actionRequested = NotificationConstants.KEW_CONSTANTS.ACK_AD_HOC_ROUTE;
    } else {
      actionRequested = NotificationConstants.KEW_CONSTANTS.FYI_AD_HOC_ROUTE;
    }

    // Clarification of ad hoc route call
    // param 1 - actionRequested will be either ACK or FYI
    // param 2 - annotation is whatever text we pass in to describe the transaction - this will be
    // system generated
    // param 3 - recipient is the person who will receive this request
    // param 4 - this is the responsibilityParty (a.k.a the system that produced this request), so
    // we'll put the producer name in there
    // param 5 - this is the "force action" requests - if set to true, this will be delivered to the
    // recipients list regardless of
    //           whether the recipient has already taken action on this request; in our case, this
    // doesn't really apply at this point in time,
    //           so we'll set to true just to be safe

    // recipientUserId will always be a principal ID due to code changes in
    // NotificationMessageDeliveryResolverServiceImpl.buildCompleteRecipientList()
    Principal principal = KimApiServiceLocator.getIdentityService().getPrincipal(recipientUserId);

    document.adHocToPrincipal(
        ActionRequestType.fromCode(actionRequested),
        annotation,
        principal.getPrincipalId(),
        messageDelivery.getNotification().getProducer().getName(),
        true);

    // now actually route it along its way
    document.route(annotation);

    return document.getDocumentId();
  }