protected void populateRoutingExceptionResponsibility(DocumentConfigurationViewForm form) {
    DocumentType docType = form.getDocumentType();
    List<ResponsibilityForDisplay> responsibilities = new ArrayList<ResponsibilityForDisplay>();
    while (docType != null) {
      QueryByCriteria.Builder builder = QueryByCriteria.Builder.create();
      Predicate p =
          and(
              equal("template.namespaceCode", KRADConstants.KUALI_RICE_WORKFLOW_NAMESPACE),
              equal(
                  "template.name", KewApiConstants.EXCEPTION_ROUTING_RESPONSIBILITY_TEMPLATE_NAME),
              equal("active", "Y"),
              equal("attributes[documentTypeName]", docType.getName()));
      builder.setPredicates(p);
      List<Responsibility> resps =
          getResponsibilityService().findResponsibilities(builder.build()).getResults();

      for (Responsibility r : resps) {
        if (responsibilities.isEmpty()) {
          responsibilities.add(new ResponsibilityForDisplay(r, false));
        } else {
          responsibilities.add(new ResponsibilityForDisplay(r, true));
        }
      }
      docType = docType.getParentDocType();
    }
    form.setExceptionResponsibilities(responsibilities);
    for (ResponsibilityForDisplay responsibility : responsibilities) {
      List<String> roleIds =
          getResponsibilityService().getRoleIdsForResponsibility(responsibility.getResp().getId());
      if (!roleIds.isEmpty()) {
        form.getResponsibilityRoles()
            .put(responsibility.getResponsibilityId(), getRoleService().getRoles(roleIds));
      }
    }
  }
 @Override
 public List<StateInfo> performSearch(
     LookupForm lookupForm, Map<String, String> searchCriteria, boolean bounded) {
   QueryByCriteria.Builder qBuilder = QueryByCriteria.Builder.create();
   List<Predicate> pList = new ArrayList<Predicate>();
   // Code Changed for JIRA-8997 - SONAR Critical issues - Performance - Inefficient use of keySet
   // iterator instead of entrySet iterator
   for (Map.Entry<String, String> entry : searchCriteria.entrySet()) {
     String fieldName = entry.getKey();
     String value = entry.getValue();
     if (value != null && !value.isEmpty()) {
       if (fieldName.equals("maxResultsToReturn")) {
         qBuilder.setMaxResults(Integer.parseInt(value));
         continue;
       }
       pList.add(PredicateFactory.equal(fieldName, value));
     }
   }
   if (!pList.isEmpty()) {
     qBuilder.setPredicates(PredicateFactory.and(pList.toArray(new Predicate[pList.size()])));
   }
   try {
     return this.getStateService().searchForStates(qBuilder.build(), getContextInfo());
   } catch (Exception ex) {
     throw new RuntimeException(ex);
   }
 }
  protected PeopleFlowBo getPeopleFlowBoByName(String namespaceCode, String name) {
    if (StringUtils.isBlank(namespaceCode)) {
      throw new RiceIllegalArgumentException("namespaceCode was a null or blank value");
    }
    if (StringUtils.isBlank(name)) {
      throw new RiceIllegalArgumentException("name was a null or blank value");
    }

    QueryByCriteria.Builder criteria = QueryByCriteria.Builder.create();
    criteria.setPredicates(
        equal(KewImplConstants.PropertyConstants.NAMESPACE_CODE, namespaceCode),
        equal(KewImplConstants.PropertyConstants.NAME, name));
    Collection<PeopleFlowBo> peopleFlows =
        dataObjectService.findMatching(PeopleFlowBo.class, criteria.build()).getResults();

    if (CollectionUtils.isEmpty(peopleFlows)) {
      return null;
    } else if (peopleFlows.size() > 1) {
      throw new RiceIllegalStateException(
          "Found more than one PeopleFlow with the given namespace code '"
              + namespaceCode
              + "' and name '"
              + name
              + "'");
    }
    return peopleFlows.iterator().next();
  }
  protected static List<String> getOptionKeys(
      CourseOfferingCreateWrapper createWrapper, CourseOfferingInfo existingCO) {

    List<String> optionKeys =
        getDefaultOptionKeysService().getDefaultOptionKeysForCopySingleCourseOffering();

    if (createWrapper.isExcludeInstructorInformation()) {
      optionKeys.add(CourseOfferingSetServiceConstants.NO_INSTRUCTORS_OPTION_KEY);
    }

    if (createWrapper.isExcludeSchedulingInformation()) {
      optionKeys.add(CourseOfferingSetServiceConstants.NO_SCHEDULE_OPTION_KEY);
    }

    if (createWrapper.isExcludeCancelledActivityOfferings()) {
      optionKeys.add(CourseOfferingSetServiceConstants.IGNORE_CANCELLED_AO_OPTION_KEY);
    }

    ContextInfo contextInfo = ContextUtils.createDefaultContextInfo();

    try {
      // if source term differs from target term determine if add suffix or not
      if (StringUtils.equals(existingCO.getTermId(), createWrapper.getTerm().getId())) {
        optionKeys.add(CourseOfferingServiceConstants.APPEND_COURSE_OFFERING_IN_SUFFIX_OPTION_KEY);
      } else {
        QueryByCriteria.Builder qbcBuilder = QueryByCriteria.Builder.create();
        qbcBuilder.setPredicates(
            PredicateFactory.and(
                PredicateFactory.like(
                    "courseOfferingCode", existingCO.getCourseOfferingCode() + "%"),
                PredicateFactory.equalIgnoreCase("atpId", createWrapper.getTerm().getId())));
        QueryByCriteria criteria = qbcBuilder.build();
        List<String> courseOfferingIds =
            CourseOfferingManagementUtil.getCourseOfferingService()
                .searchForCourseOfferingIds(criteria, contextInfo);

        if (courseOfferingIds.size() > 0) {
          optionKeys.add(
              CourseOfferingServiceConstants.APPEND_COURSE_OFFERING_IN_SUFFIX_OPTION_KEY);
        }
      }
    } catch (Exception e) {
      throw new RuntimeException(e);
    }

    //  According to Jira 4353 copy the title from CO instead of CLU. So set the property not to
    // copy from CLU
    optionKeys.add(CourseOfferingSetServiceConstants.NOT_COURSE_TITLE_OPTION_KEY);
    return optionKeys;
  }
  /** @see BulkUpdateMaintainable#generateUpdatableObjects() */
  @Override
  public List<Object> generateUpdatableObjects() {
    List<Object> updatableObjects = new ArrayList<Object>();

    BulkUpdateMaintenanceDataObject bulkUpdateMaintenanceDataObject =
        (BulkUpdateMaintenanceDataObject) getDataObject();
    List<?> targetUpdateDataObjects = bulkUpdateMaintenanceDataObject.getTargetUpdateDataObjects();

    for (Object targetUpdateDataObject : targetUpdateDataObjects) {
      Map<String, Object> primaryKeys =
          getDataObjectService().wrap(targetUpdateDataObject).getPrimaryKeyValues();
      Object updatableObject =
          getDataObjectService()
              .findUnique(
                  targetUpdateDataObject.getClass(),
                  QueryByCriteria.Builder.andAttributes(primaryKeys).build());

      for (Map.Entry<String, ?> updateFieldValue :
          bulkUpdateMaintenanceDataObject.getUpdateFieldValues().entrySet()) {
        String propertyName = updateFieldValue.getKey();
        Object propertyValue = updateFieldValue.getValue();

        if (ObjectPropertyUtils.isWritableProperty(updatableObject, propertyName)) {
          ObjectPropertyUtils.setPropertyValue(updatableObject, propertyName, propertyValue);
          updatableObjects.add(updatableObject);
        }
      }
    }

    return updatableObjects;
  }
  public void populatePermissions(DocumentConfigurationViewForm form) {

    DocumentType docType = form.getDocumentType();
    Map<String, List<Role>> permRoles = new HashMap<String, List<Role>>();
    // loop over the document hierarchy
    Set<String> seenDocumentPermissions = new HashSet<String>();
    while (docType != null) {
      String documentTypeName = docType.getName();
      Predicate p =
          and(
              equal("active", "Y"),
              equal(
                  "attributes[" + KimConstants.AttributeConstants.DOCUMENT_TYPE_NAME + "]",
                  docType.getName()));
      List<Permission> perms =
          getPermissionService()
              .findPermissions(QueryByCriteria.Builder.fromPredicates(p))
              .getResults();
      for (Permission perm : perms) {
        PermissionBo permBo = PermissionBo.from(perm);
        List<String> roleIds =
            getPermissionService().getRoleIdsForPermission(perm.getNamespaceCode(), perm.getName());
        if (!roleIds.isEmpty()) {
          permRoles.put(perm.getId(), getRoleService().getRoles(roleIds));
        }
        for (String attributeName : permBo.getDetails().keySet()) {
          addAttributeLabel(form, attributeName);
        }
      }
      // show the section if the current document or permissions exist
      if (perms.size() > 0 || documentTypeName.equals(form.getDocumentTypeName())) {
        ArrayList<PermissionForDisplay> dispPerms =
            new ArrayList<PermissionForDisplay>(perms.size());
        for (Permission perm : perms) {
          PermissionBo permBo = PermissionBo.from(perm);
          if (permBo.getDetails().size() == 1) { // only the document type
            // this is a document type-specific permission, check if seen earlier
            if (seenDocumentPermissions.contains(
                perm.getTemplate().getNamespaceCode() + "|" + perm.getTemplate().getName())) {
              dispPerms.add(new PermissionForDisplay(permBo, true));
            } else {
              dispPerms.add(new PermissionForDisplay(permBo, false));
              seenDocumentPermissions.add(
                  perm.getTemplate().getNamespaceCode() + "|" + perm.getTemplate().getName());
            }
          } else {
            // other attributes, can't determine whether this is overridden at another level
            dispPerms.add(new PermissionForDisplay(permBo, false));
          }
        }
        form.setPermissionsForDocumentType(documentTypeName, dispPerms);
        form.addDocumentType(documentTypeName);
      }
      docType = docType.getParentDocType();
    }

    form.setPermissionRoles(permRoles);
  }
 protected QueryByCriteria setUpEntityLookupCriteria(String principalId) {
   PersonServiceImpl personServiceImpl =
       (PersonServiceImpl)
           KIMServiceLocatorInternal.getService(KimApiServiceLocator.KIM_PERSON_SERVICE);
   Map<String, String> criteria = new HashMap<String, String>(1);
   criteria.put(KIMPropertyConstants.Person.PRINCIPAL_ID, principalId);
   Map<String, String> entityCriteria =
       personServiceImpl.convertPersonPropertiesToEntityProperties(criteria);
   entityCriteria.put("entityTypeContactInfos.entityTypeCode", "PERSON");
   QueryByCriteria.Builder query = QueryByCriteria.Builder.create();
   List<Predicate> predicates = new ArrayList<Predicate>();
   for (String key : entityCriteria.keySet()) {
     predicates.add(like(key, entityCriteria.get(key)));
   }
   if (!predicates.isEmpty()) {
     query.setPredicates(and(predicates.toArray(new Predicate[predicates.size()])));
   }
   return query.build();
 }
 public void refreshBudgetDocumentVersions() {
   final List<BudgetDocumentVersion> v =
       getDataObjectService()
           .findMatching(
               BudgetDocumentVersion.class,
               QueryByCriteria.Builder.andAttributes(
                       Collections.singletonMap("parentDocumentKey", documentNumber))
                   .build())
           .getResults();
   budgetDocumentVersions = v;
 }
  /**
   * @param dataObjectClass the dataobject class
   * @param formProperties the incoming lookup form properties
   * @param unbounded whether the search is unbounded
   * @param searchResultsLimit the searchResultsLimit; null implies use of default KNS value if set
   *     for the class
   * @param <T> the data object type
   * @return collection of lookup results
   */
  protected <T> Collection<T> performDataObjectServiceLookup(
      Class<T> dataObjectClass,
      Map<String, String> formProperties,
      boolean unbounded,
      boolean allPrimaryKeyValuesPresentAndNotWildcard,
      Integer searchResultsLimit) {
    if (!unbounded && searchResultsLimit == null) {
      // use KRAD LookupUtils.getSearchResultsLimit instead of KNS version. we have no LookupForm,
      // so pass null, only the class will be used
      // searchResultsLimit = LookupUtils.getSearchResultsLimit(example, null);
      searchResultsLimit =
          org.kuali.rice.kns.lookup.LookupUtils.getSearchResultsLimit(dataObjectClass);
    }
    QueryByCriteria.Builder query =
        lookupCriteriaGenerator.generateCriteria(
            dataObjectClass, formProperties, allPrimaryKeyValuesPresentAndNotWildcard);
    if (!unbounded && searchResultsLimit != null) {
      query.setMaxResults(searchResultsLimit);
    }

    Collection<T> results =
        dataObjectService.findMatching(dataObjectClass, query.build()).getResults();
    return filterCurrentDataObjects(dataObjectClass, results, formProperties);
  }
 private void updatePersonCertificationInfo(ProposalPerson person, String proposalNumber) {
   // Update certified by and certified time with current info
   Map<String, Object> criteria = new HashMap<>();
   criteria.put(DEVELOPMENT_PROPOSAL_NUMBER, proposalNumber);
   QueryResults<ProposalPerson> currentPersons =
       getDataObjectService()
           .findMatching(
               ProposalPerson.class, QueryByCriteria.Builder.andAttributes(criteria).build());
   for (ProposalPerson currentPerson : currentPersons.getResults()) {
     if (currentPerson.getUniqueId().equals(person.getUniqueId())) {
       person.setCertifiedBy(currentPerson.getCertifiedBy());
       person.setCertifiedTime(currentPerson.getCertifiedTime());
       break;
     }
   }
 }
  /**
   * Helper method to get the role member objects.
   *
   * @param principalId The person to get the role for
   * @param roleIds The role
   * @param asOfDate The effective date of the role
   * @param activeOnly Whether or not to consider only active role members
   * @return the list of role member objects
   */
  private List<RoleMember> getPrincipalIdRoleMembers(
      String principalId, List<String> roleIds, DateTime asOfDate, boolean activeOnly) {
    List<String> groupIds = getGroupService().getGroupIdsByPrincipalId(principalId);

    List<Predicate> predicates = new ArrayList<Predicate>();
    predicates.add(
        in(
            KimConstants.PrimaryKeyConstants.SUB_ROLE_ID,
            roleIds.toArray(new String[roleIds.size()])));

    List<Predicate> principalPredicates = new ArrayList<Predicate>();
    principalPredicates.add(
        equal(KIMPropertyConstants.RoleMember.MEMBER_TYPE_CODE, MemberType.PRINCIPAL.getCode()));
    if (principalId != null) {
      principalPredicates.add(equal(KIMPropertyConstants.RoleMember.MEMBER_ID, principalId));
    }
    Predicate principalPredicate = and(principalPredicates.toArray(new Predicate[] {}));

    Predicate rolePredicate =
        equal(KIMPropertyConstants.RoleMember.MEMBER_TYPE_CODE, MemberType.ROLE.getCode());

    List<Predicate> groupPredicates = new ArrayList<Predicate>();
    groupPredicates.add(
        equal(KIMPropertyConstants.RoleMember.MEMBER_TYPE_CODE, MemberType.GROUP.getCode()));
    if (CollectionUtils.isNotEmpty(groupIds)) {
      groupPredicates.add(
          in(KIMPropertyConstants.RoleMember.MEMBER_ID, groupIds.toArray(new String[] {})));
    }
    Predicate groupPredicate = and(groupPredicates.toArray(new Predicate[] {}));

    predicates.add(or(principalPredicate, rolePredicate, groupPredicate));

    if (activeOnly) {
      predicates.add(
          or(isNull("activeFromDateValue"), lessThanOrEqual("activeFromDateValue", asOfDate)));
      predicates.add(or(isNull("activeToDateValue"), greaterThan("activeToDateValue", asOfDate)));
    }

    return getRoleService()
        .findRoleMembers(
            QueryByCriteria.Builder.fromPredicates(predicates.toArray(new Predicate[] {})))
        .getResults();
  }
  protected List<RoleMember> getPrimaryRoleMembers(
      Role role, Map<String, String> qualification, DateTime asOfDate, boolean isActiveOnly) {
    // define the return value
    List<RoleMember> primaryRoleMembers = new ArrayList<RoleMember>();

    if (role != null) {
      RoleTypeService roleTypeService = getRoleTypeService(role);
      // use predicate based filtering only on non-derived role.
      if (roleTypeService == null || !roleTypeService.isDerivedRoleType()) {
        List<Predicate> predicates = new ArrayList<Predicate>();
        predicates.add(equal(KimConstants.PrimaryKeyConstants.SUB_ROLE_ID, role.getId()));
        if (isActiveOnly) {
          predicates.add(
              or(isNull("activeFromDateValue"), lessThanOrEqual("activeFromDateValue", asOfDate)));
          predicates.add(
              or(isNull("activeToDateValue"), greaterThan("activeToDateValue", asOfDate)));
        }

        // LookupCustomizer<RoleMemberBo> lookupCustomizer = builder.build();
        // guard for default type roles
        if (roleTypeService != null) {
          if (MapUtils.isEmpty(qualification)) {
            primaryRoleMembers =
                getRoleService()
                    .findRoleMembers(
                        QueryByCriteria.Builder.fromPredicates(
                            predicates.toArray(new Predicate[predicates.size()])))
                    .getResults();
          } else {
            // get the keys (name) of the qualifiers needed for membership in this role
            List<String> attributesForExactMatch = roleTypeService.getQualifiersForExactMatch();
            if (CollectionUtils.isNotEmpty(attributesForExactMatch)) {
              if (attributesForExactMatch.size() <= 1) {
                for (Map.Entry<String, String> qualificationEntry : qualification.entrySet()) {
                  // do not add a qualification predicate for an attribute unless it is required for
                  // matching

                  if (attributesForExactMatch.contains(qualificationEntry.getKey())) {
                    predicates.add(
                        equal(
                            "attributes[" + qualificationEntry.getKey() + "]",
                            qualificationEntry.getValue()));
                  }
                }
                primaryRoleMembers =
                    getRoleService()
                        .findRoleMembers(
                            QueryByCriteria.Builder.fromPredicates(
                                predicates.toArray(new Predicate[predicates.size()])))
                        .getResults();

              } else {
                // rice's transformation doesn't work with more than one attribute.
                // here is a terrible hack
                List<RoleMember> intersectedMembers = null;
                for (Map.Entry<String, String> qualificationEntry : qualification.entrySet()) {
                  // do not add a qualification predicate for an attribute unless it is required for
                  // matching

                  if (attributesForExactMatch.contains(qualificationEntry.getKey())) {
                    Predicate attrPredicates =
                        equal(
                            "attributes[" + qualificationEntry.getKey() + "]",
                            qualificationEntry.getValue());
                    Predicate[] tempPredicates =
                        predicates.toArray(new Predicate[predicates.size() + 1]);
                    tempPredicates[predicates.size()] = attrPredicates;
                    List<RoleMember> tempMembers =
                        new ArrayList<RoleMember>(
                            getRoleService()
                                .findRoleMembers(
                                    QueryByCriteria.Builder.fromPredicates(tempPredicates))
                                .getResults());
                    if (intersectedMembers == null) {
                      intersectedMembers = new ArrayList<>();
                      intersectedMembers.addAll(tempMembers);
                    } else {
                      intersectedMembers = intersect(intersectedMembers, tempMembers);
                    }
                  }
                }
                primaryRoleMembers = intersectedMembers;
              }
            }
          }
        }
      } else {
        // for derived roles just add the as-of date and active only flag to a copy of the
        // qualification
        Map<String, String> derivedRoleQualification = new HashMap<String, String>(qualification);
        derivedRoleQualification.put("asOfDate", asOfDate.toString());
        derivedRoleQualification.put("activeOnly", String.valueOf(isActiveOnly));
        List<RoleMembership> derivedRoleMembers =
            roleTypeService.getRoleMembersFromDerivedRole(
                role.getNamespaceCode(), role.getName(), derivedRoleQualification);
        // convert the role memberships into role members
        for (RoleMembership derivedRoleMember : derivedRoleMembers) {
          RoleMember roleMember =
              RoleMember.Builder.create(
                      derivedRoleMember.getRoleId(),
                      derivedRoleMember.getId(),
                      derivedRoleMember.getMemberId(),
                      derivedRoleMember.getType(),
                      null,
                      null,
                      derivedRoleMember.getQualifier(),
                      role.getName(),
                      role.getNamespaceCode())
                  .build();

          primaryRoleMembers.add(roleMember);
        }
      }
    }

    return primaryRoleMembers;
  }
  @Override
  protected void prepareData(ProposalDevelopmentDocument document) throws Exception {

    Organization organization =
        getService(DataObjectService.class)
            .findUnique(
                Organization.class,
                QueryByCriteria.Builder.forAttribute("organizationId", "000001").build());
    document.getDevelopmentProposal().getApplicantOrganization().setOrganization(organization);

    NarrativeAttachment narrativeAttachment = new NarrativeAttachment();
    DefaultResourceLoader resourceLoader =
        new DefaultResourceLoader(ClassLoaderUtils.getDefaultClassLoader());
    Resource resource = resourceLoader.getResource(S2STestConstants.ATT_PACKAGE + "/exercise2.pdf");
    InputStream inputStream = resource.getInputStream();
    BufferedInputStream bis = new BufferedInputStream(inputStream);
    byte[] narrativePdf = new byte[bis.available()];
    narrativeAttachment.setData(narrativePdf);
    narrativeAttachment.setName("exercise1");
    Narrative narrative = new Narrative();
    List<Narrative> narrativeList = new ArrayList<Narrative>();
    narrative.setDevelopmentProposal(document.getDevelopmentProposal());
    NarrativeType narrativeType =
        getService(DataObjectService.class)
            .findUnique(
                NarrativeType.class, QueryByCriteria.Builder.forAttribute("code", "7").build());
    narrative.setName("exercise1");
    narrative.setNarrativeType(narrativeType);
    narrative.setNarrativeTypeCode(narrativeType.getCode());
    narrative.setNarrativeAttachment(narrativeAttachment);
    narrative.setModuleNumber(1);
    narrative.setModuleSequenceNumber(1);
    narrative.setModuleStatusCode("C");
    narrativeList.add(narrative);
    document.getDevelopmentProposal().setNarratives(narrativeList);

    List<ProposalPerson> proposalPersons = new ArrayList<ProposalPerson>();
    ProposalPerson principalInvestigator = new ProposalPerson();
    principalInvestigator.setFirstName("ALAN");
    principalInvestigator.setLastName("MCAFEE");
    principalInvestigator.setProposalPersonRoleId("PI");
    principalInvestigator.setPersonId("0001");
    principalInvestigator.setRolodexId(0010);
    principalInvestigator.setProposalPersonNumber(1);
    principalInvestigator.setDevelopmentProposal(document.getDevelopmentProposal());
    proposalPersons.add(principalInvestigator);
    document.getDevelopmentProposal().setProposalPersons(proposalPersons);

    ProposalDevelopmentBudgetExt proposalDevelopmentBudgetExt = new ProposalDevelopmentBudgetExt();
    proposalDevelopmentBudgetExt.setDevelopmentProposal(document.getDevelopmentProposal());
    proposalDevelopmentBudgetExt.setBudgetVersionNumber(1);
    proposalDevelopmentBudgetExt.setBudgetStatus("1");
    proposalDevelopmentBudgetExt.setBudgetId(1L);
    proposalDevelopmentBudgetExt.setName("test Document Description");
    proposalDevelopmentBudgetExt.setOnOffCampusFlag("Y");
    proposalDevelopmentBudgetExt.setStartDate(new Date(new Long("1183316613046")));
    proposalDevelopmentBudgetExt.setEndDate(new Date(new Long("1214852613046")));
    proposalDevelopmentBudgetExt.setOhRateTypeCode("1");
    proposalDevelopmentBudgetExt.setOhRateClassCode("1");
    proposalDevelopmentBudgetExt.setModularBudgetFlag(false);
    proposalDevelopmentBudgetExt.setUrRateClassCode("1");

    List<BudgetPeriod> budgetPeriods = new ArrayList<BudgetPeriod>();
    BudgetPeriod budgetPeriod = new BudgetPeriod();
    budgetPeriod.setBudgetPeriodId(1L);
    budgetPeriod.setStartDate(new Date(new Long("1183316613046")));
    budgetPeriod.setEndDate(new Date(new Long("1214852613046")));
    budgetPeriod.setBudgetPeriod(1);

    budgetPeriod.setBudget(proposalDevelopmentBudgetExt);
    budgetPeriods.add(budgetPeriod);
    proposalDevelopmentBudgetExt.setBudgetPeriods(budgetPeriods);

    List<ProposalDevelopmentBudgetExt> proposalDevelopmentBudgetExtList =
        new ArrayList<ProposalDevelopmentBudgetExt>();
    proposalDevelopmentBudgetExtList.add(proposalDevelopmentBudgetExt);
    document.getDevelopmentProposal().setBudgets(proposalDevelopmentBudgetExtList);
    document.getDevelopmentProposal().setFinalBudget(proposalDevelopmentBudgetExt);
  }
 protected ScienceKeyword getScienceKeyword(Object element) {
   return getDataObjectService()
       .findUnique(
           ScienceKeyword.class, QueryByCriteria.Builder.forAttribute("code", element).build());
 }
 protected ExemptionType getExemptionType(Object element) {
   return getDataObjectService()
       .findUnique(
           ExemptionType.class, QueryByCriteria.Builder.forAttribute("code", element).build());
 }
  protected PropAwardPersonRoleServiceImpl getPropAwardPersonRoleService() {
    final PropAwardPersonRoleServiceImpl roleService = new PropAwardPersonRoleServiceImpl();
    final DataObjectService dataObjectService = context.mock(DataObjectService.class);
    final ParameterService parameterService = context.mock(ParameterService.class);
    final SponsorHierarchyService hierarchyService = context.mock(SponsorHierarchyService.class);

    context.checking(
        new Expectations() {
          {
            one(parameterService)
                .getParameterValueAsBoolean(
                    Constants.MODULE_NAMESPACE_PROPOSAL_DEVELOPMENT,
                    Constants.PARAMETER_COMPONENT_DOCUMENT,
                    PropAwardPersonRoleServiceImpl.ALL_SPONSOR_HIERARCHY_NIH_MULTI_PI);
            will(returnValue(true));
            one(dataObjectService)
                .findMatching(
                    PropAwardPersonRole.class,
                    QueryByCriteria.Builder.forAttribute(
                            "sponsorHierarchyName",
                            PropAwardPersonRoleServiceImpl.NIH_MULTIPLE_PI_HIERARCHY)
                        .build());
            will(returnValue(roleListBuilder.build()));
          }
        });

    final QueryByCriteria.Builder criteriaCoInvestigator1 =
        QueryByCriteria.Builder.create()
            .setPredicates(
                PredicateFactory.equal("code", ContactRole.COI_CODE),
                PredicateFactory.equal(
                    "sponsorHierarchyName",
                    PropAwardPersonRoleServiceImpl.NIH_MULTIPLE_PI_HIERARCHY));
    final PropAwardPersonRole roleCoInvestigator1 =
        createTestRole(
            3L, ContactRole.COI_CODE, PropAwardPersonRoleServiceImpl.NIH_MULTIPLE_PI_HIERARCHY);
    context.checking(
        new Expectations() {
          {
            one(parameterService)
                .getParameterValueAsBoolean(
                    Constants.MODULE_NAMESPACE_PROPOSAL_DEVELOPMENT,
                    Constants.PARAMETER_COMPONENT_DOCUMENT,
                    PropAwardPersonRoleServiceImpl.ALL_SPONSOR_HIERARCHY_NIH_MULTI_PI);
            will(returnValue(true));
            one(dataObjectService)
                .findUnique(PropAwardPersonRole.class, criteriaCoInvestigator1.build());
            will(returnValue(roleCoInvestigator1));
          }
        });

    final QueryByCriteria.Builder criteriaCoInvestigator2 =
        QueryByCriteria.Builder.create()
            .setPredicates(
                PredicateFactory.equal("code", ContactRole.COI_CODE),
                PredicateFactory.equal(
                    "sponsorHierarchyName",
                    PropAwardPersonRoleServiceImpl.NIH_MULTIPLE_PI_HIERARCHY));
    final PropAwardPersonRole roleCoInvestigator2 =
        createTestRole(
            3L, ContactRole.COI_CODE, PropAwardPersonRoleServiceImpl.NIH_MULTIPLE_PI_HIERARCHY);
    context.checking(
        new Expectations() {
          {
            one(parameterService)
                .getParameterValueAsBoolean(
                    Constants.MODULE_NAMESPACE_PROPOSAL_DEVELOPMENT,
                    Constants.PARAMETER_COMPONENT_DOCUMENT,
                    PropAwardPersonRoleServiceImpl.ALL_SPONSOR_HIERARCHY_NIH_MULTI_PI);
            will(returnValue(true));
            one(dataObjectService)
                .findUnique(PropAwardPersonRole.class, criteriaCoInvestigator2.build());
            will(returnValue(roleCoInvestigator2));
          }
        });

    final QueryByCriteria.Builder criteriaKeyPerson1 =
        QueryByCriteria.Builder.create()
            .setPredicates(
                PredicateFactory.equal("code", ContactRole.KEY_PERSON_CODE),
                PredicateFactory.equal(
                    "sponsorHierarchyName",
                    PropAwardPersonRoleServiceImpl.NIH_MULTIPLE_PI_HIERARCHY));
    final PropAwardPersonRole roleKeyPerson1 =
        createTestRole(
            3L,
            ContactRole.KEY_PERSON_CODE,
            PropAwardPersonRoleServiceImpl.NIH_MULTIPLE_PI_HIERARCHY);
    context.checking(
        new Expectations() {
          {
            one(parameterService)
                .getParameterValueAsBoolean(
                    Constants.MODULE_NAMESPACE_PROPOSAL_DEVELOPMENT,
                    Constants.PARAMETER_COMPONENT_DOCUMENT,
                    PropAwardPersonRoleServiceImpl.ALL_SPONSOR_HIERARCHY_NIH_MULTI_PI);
            will(returnValue(true));
            one(dataObjectService)
                .findUnique(PropAwardPersonRole.class, criteriaKeyPerson1.build());
            will(returnValue(roleKeyPerson1));
          }
        });

    final QueryByCriteria.Builder criteriaKeyPerson2 =
        QueryByCriteria.Builder.create()
            .setPredicates(
                PredicateFactory.equal("code", ContactRole.KEY_PERSON_CODE),
                PredicateFactory.equal(
                    "sponsorHierarchyName",
                    PropAwardPersonRoleServiceImpl.NIH_MULTIPLE_PI_HIERARCHY));
    final PropAwardPersonRole roleKeyPerson2 =
        createTestRole(
            3L,
            ContactRole.KEY_PERSON_CODE,
            PropAwardPersonRoleServiceImpl.NIH_MULTIPLE_PI_HIERARCHY);
    context.checking(
        new Expectations() {
          {
            one(parameterService)
                .getParameterValueAsBoolean(
                    Constants.MODULE_NAMESPACE_PROPOSAL_DEVELOPMENT,
                    Constants.PARAMETER_COMPONENT_DOCUMENT,
                    PropAwardPersonRoleServiceImpl.ALL_SPONSOR_HIERARCHY_NIH_MULTI_PI);
            will(returnValue(true));
            one(dataObjectService)
                .findUnique(PropAwardPersonRole.class, criteriaKeyPerson2.build());
            will(returnValue(roleKeyPerson2));
          }
        });

    final QueryByCriteria.Builder criteriaKeyPerson3 =
        QueryByCriteria.Builder.create()
            .setPredicates(
                PredicateFactory.equal("code", ContactRole.KEY_PERSON_CODE),
                PredicateFactory.equal(
                    "sponsorHierarchyName",
                    PropAwardPersonRoleServiceImpl.NIH_MULTIPLE_PI_HIERARCHY));
    final PropAwardPersonRole roleKeyPerson3 =
        createTestRole(
            3L,
            ContactRole.KEY_PERSON_CODE,
            PropAwardPersonRoleServiceImpl.NIH_MULTIPLE_PI_HIERARCHY);
    context.checking(
        new Expectations() {
          {
            one(parameterService)
                .getParameterValueAsBoolean(
                    Constants.MODULE_NAMESPACE_PROPOSAL_DEVELOPMENT,
                    Constants.PARAMETER_COMPONENT_DOCUMENT,
                    PropAwardPersonRoleServiceImpl.ALL_SPONSOR_HIERARCHY_NIH_MULTI_PI);
            will(returnValue(true));
            one(dataObjectService)
                .findUnique(PropAwardPersonRole.class, criteriaKeyPerson3.build());
            will(returnValue(roleKeyPerson3));
          }
        });

    final QueryByCriteria.Builder criteriaKeyPerson4 =
        QueryByCriteria.Builder.create()
            .setPredicates(
                PredicateFactory.equal("code", ContactRole.KEY_PERSON_CODE),
                PredicateFactory.equal(
                    "sponsorHierarchyName",
                    PropAwardPersonRoleServiceImpl.NIH_MULTIPLE_PI_HIERARCHY));
    final PropAwardPersonRole roleKeyPerson4 =
        createTestRole(
            3L,
            ContactRole.KEY_PERSON_CODE,
            PropAwardPersonRoleServiceImpl.NIH_MULTIPLE_PI_HIERARCHY);
    context.checking(
        new Expectations() {
          {
            one(parameterService)
                .getParameterValueAsBoolean(
                    Constants.MODULE_NAMESPACE_PROPOSAL_DEVELOPMENT,
                    Constants.PARAMETER_COMPONENT_DOCUMENT,
                    PropAwardPersonRoleServiceImpl.ALL_SPONSOR_HIERARCHY_NIH_MULTI_PI);
            will(returnValue(true));
            one(dataObjectService)
                .findUnique(PropAwardPersonRole.class, criteriaKeyPerson4.build());
            will(returnValue(roleKeyPerson4));
          }
        });

    final QueryByCriteria.Builder criteriaKeyPerson5 =
        QueryByCriteria.Builder.create()
            .setPredicates(
                PredicateFactory.equal("code", ContactRole.KEY_PERSON_CODE),
                PredicateFactory.equal(
                    "sponsorHierarchyName",
                    PropAwardPersonRoleServiceImpl.NIH_MULTIPLE_PI_HIERARCHY));
    final PropAwardPersonRole roleKeyPerson5 =
        createTestRole(
            3L,
            ContactRole.KEY_PERSON_CODE,
            PropAwardPersonRoleServiceImpl.NIH_MULTIPLE_PI_HIERARCHY);
    context.checking(
        new Expectations() {
          {
            one(parameterService)
                .getParameterValueAsBoolean(
                    Constants.MODULE_NAMESPACE_PROPOSAL_DEVELOPMENT,
                    Constants.PARAMETER_COMPONENT_DOCUMENT,
                    PropAwardPersonRoleServiceImpl.ALL_SPONSOR_HIERARCHY_NIH_MULTI_PI);
            will(returnValue(true));
            one(dataObjectService)
                .findUnique(PropAwardPersonRole.class, criteriaKeyPerson5.build());
            will(returnValue(roleKeyPerson5));
          }
        });

    final QueryByCriteria.Builder criteriaPrincipalInvestigator1 =
        QueryByCriteria.Builder.create()
            .setPredicates(
                PredicateFactory.equal("code", ContactRole.PI_CODE),
                PredicateFactory.equal(
                    "sponsorHierarchyName",
                    PropAwardPersonRoleServiceImpl.NIH_MULTIPLE_PI_HIERARCHY));
    final PropAwardPersonRole rolePrincipalInvestigator1 =
        createTestRole(
            3L, ContactRole.PI_CODE, PropAwardPersonRoleServiceImpl.NIH_MULTIPLE_PI_HIERARCHY);
    context.checking(
        new Expectations() {
          {
            one(parameterService)
                .getParameterValueAsBoolean(
                    Constants.MODULE_NAMESPACE_PROPOSAL_DEVELOPMENT,
                    Constants.PARAMETER_COMPONENT_DOCUMENT,
                    PropAwardPersonRoleServiceImpl.ALL_SPONSOR_HIERARCHY_NIH_MULTI_PI);
            will(returnValue(true));
            one(dataObjectService)
                .findUnique(PropAwardPersonRole.class, criteriaPrincipalInvestigator1.build());
            will(returnValue(rolePrincipalInvestigator1));
          }
        });

    final QueryByCriteria.Builder criteriaPrincipalInvestigator2 =
        QueryByCriteria.Builder.create()
            .setPredicates(
                PredicateFactory.equal("code", ContactRole.PI_CODE),
                PredicateFactory.equal(
                    "sponsorHierarchyName",
                    PropAwardPersonRoleServiceImpl.NIH_MULTIPLE_PI_HIERARCHY));
    final PropAwardPersonRole rolePrincipalInvestigator2 =
        createTestRole(
            3L, ContactRole.PI_CODE, PropAwardPersonRoleServiceImpl.NIH_MULTIPLE_PI_HIERARCHY);
    context.checking(
        new Expectations() {
          {
            one(parameterService)
                .getParameterValueAsBoolean(
                    Constants.MODULE_NAMESPACE_PROPOSAL_DEVELOPMENT,
                    Constants.PARAMETER_COMPONENT_DOCUMENT,
                    PropAwardPersonRoleServiceImpl.ALL_SPONSOR_HIERARCHY_NIH_MULTI_PI);
            will(returnValue(true));
            one(dataObjectService)
                .findUnique(PropAwardPersonRole.class, criteriaPrincipalInvestigator2.build());
            will(returnValue(rolePrincipalInvestigator2));
          }
        });

    final QueryByCriteria.Builder criteriaPrincipalInvestigator3 =
        QueryByCriteria.Builder.create()
            .setPredicates(
                PredicateFactory.equal("code", ContactRole.PI_CODE),
                PredicateFactory.equal(
                    "sponsorHierarchyName",
                    PropAwardPersonRoleServiceImpl.NIH_MULTIPLE_PI_HIERARCHY));
    final PropAwardPersonRole rolePrincipalInvestigator3 =
        createTestRole(
            3L, ContactRole.PI_CODE, PropAwardPersonRoleServiceImpl.NIH_MULTIPLE_PI_HIERARCHY);
    context.checking(
        new Expectations() {
          {
            one(parameterService)
                .getParameterValueAsBoolean(
                    Constants.MODULE_NAMESPACE_PROPOSAL_DEVELOPMENT,
                    Constants.PARAMETER_COMPONENT_DOCUMENT,
                    PropAwardPersonRoleServiceImpl.ALL_SPONSOR_HIERARCHY_NIH_MULTI_PI);
            will(returnValue(true));
            one(dataObjectService)
                .findUnique(PropAwardPersonRole.class, criteriaPrincipalInvestigator3.build());
            will(returnValue(rolePrincipalInvestigator3));
          }
        });

    roleService.setDataObjectService(dataObjectService);
    roleService.setSponsorHierarchyService(hierarchyService);
    roleService.setParameterService(parameterService);
    return roleService;
  }
  @SuppressWarnings("unchecked")
  public void populateRoutingResponsibilities(DocumentConfigurationViewForm form) {
    // pull all the responsibilities
    // merge the data and attach to route levels
    // pull the route levels and store on form
    // List<RouteNode> routeNodes = getRouteNodeService().getFlattenedNodes(form.getDocumentType(),
    // true);
    Map<String, List<Role>> respToRoleMap = new HashMap<String, List<Role>>();
    List<ProcessDefinitionBo> processes =
        (List<ProcessDefinitionBo>) form.getDocumentType().getProcesses();
    if (!(processes.isEmpty())) {
      RouteNode rootNode = processes.get(0).getInitialRouteNode();
      LinkedHashMap<String, RouteNode> routeNodeMap = new LinkedHashMap<String, RouteNode>();
      flattenRouteNodes(rootNode, routeNodeMap);

      form.setRouteNodes(new ArrayList<RouteNode>(routeNodeMap.values()));
      // pull all the responsibilities and store into a map for use by the JSP

      // FILTER TO THE "Review" template only
      // pull responsibility roles
      DocumentType docType = form.getDocumentType();
      Set<Responsibility> responsibilities = new HashSet<Responsibility>();
      Map<String, List<ResponsibilityForDisplay>> nodeToRespMap =
          new LinkedHashMap<String, List<ResponsibilityForDisplay>>();
      while (docType != null) {
        QueryByCriteria.Builder builder = QueryByCriteria.Builder.create();
        Predicate p =
            and(
                equal("template.namespaceCode", KRADConstants.KUALI_RICE_WORKFLOW_NAMESPACE),
                equal("template.name", KewApiConstants.DEFAULT_RESPONSIBILITY_TEMPLATE_NAME),
                equal("active", "Y"),
                equal("attributes[documentTypeName]", docType.getName()));
        builder.setPredicates(p);
        List<Responsibility> resps =
            getResponsibilityService().findResponsibilities(builder.build()).getResults();

        for (Responsibility r : resps) {
          String routeNodeName =
              r.getAttributes().get(KimConstants.AttributeConstants.ROUTE_NODE_NAME);
          if (StringUtils.isNotBlank(routeNodeName)) {
            if (!nodeToRespMap.containsKey(routeNodeName)) {
              nodeToRespMap.put(routeNodeName, new ArrayList<ResponsibilityForDisplay>());
              nodeToRespMap.get(routeNodeName).add(new ResponsibilityForDisplay(r, false));
            } else {
              // check if the responsibility in the existing list is for the current document
              // if so, OK to add.  Otherwise, a lower level document has overridden this
              // responsibility (since we are walking up the hierarchy
              if (nodeToRespMap
                  .get(routeNodeName)
                  .get(0)
                  .getDetails()
                  .get(KimConstants.AttributeConstants.DOCUMENT_TYPE_NAME)
                  .equals(docType.getName())) {
                nodeToRespMap.get(routeNodeName).add(new ResponsibilityForDisplay(r, false));
              } else { // doc type name did not match, mark as overridden
                nodeToRespMap.get(routeNodeName).add(new ResponsibilityForDisplay(r, true));
              }
            }
            responsibilities.add(r);
          }
        }
        docType = docType.getParentDocType();
      }
      form.setResponsibilityMap(nodeToRespMap);

      for (Responsibility responsibility : responsibilities) {
        List<String> roleIds =
            getResponsibilityService().getRoleIdsForResponsibility(responsibility.getId());
        if (!roleIds.isEmpty()) {
          respToRoleMap.put(responsibility.getId(), getRoleService().getRoles(roleIds));
        }
      }
    }
    form.setResponsibilityRoles(respToRoleMap);
  }