/**
  * Checks to see if there has been an override lookup declared for the maintenance field. If so,
  * the override will be used for the quickfinder and lookup utils will not be called. If no
  * override was given, LookupUtils.setFieldQuickfinder will be called to set the system generated
  * quickfinder based on the attributes relationship to the parent business object.
  *
  * @return Field with quickfinder set if one was found
  */
 public static final Field setFieldQuickfinder(
     BusinessObject businessObject,
     String attributeName,
     MaintainableFieldDefinition maintainableFieldDefinition,
     Field field,
     List<String> displayedFieldNames,
     SelectiveReferenceRefresher srr) {
   if (maintainableFieldDefinition.getOverrideLookupClass() != null
       && StringUtils.isNotBlank(maintainableFieldDefinition.getOverrideFieldConversions())) {
     field.setQuickFinderClassNameImpl(
         maintainableFieldDefinition.getOverrideLookupClass().getName());
     field.setFieldConversions(maintainableFieldDefinition.getOverrideFieldConversions());
     field.setBaseLookupUrl(LookupUtils.getBaseLookupUrl(false));
     field.setReferencesToRefresh(
         LookupUtils.convertReferencesToSelectCollectionToString(
             srr.getAffectedReferencesFromLookup(businessObject, attributeName, "")));
     return field;
   }
   if (maintainableFieldDefinition.isNoLookup()) {
     return field;
   }
   return LookupUtils.setFieldQuickfinder(
       businessObject,
       null,
       false,
       0,
       attributeName,
       field,
       displayedFieldNames,
       maintainableFieldDefinition.isNoLookup());
 }
  /**
   * @see
   *     org.kuali.kfs.module.ld.service.LaborInquiryOptionsService#isConsolidationSelected(java.util.Map,
   *     java.util.Collection)
   *     <p>KRAD Conversion: Lookupable performs checking for a particular attribute and return true
   *     or false. This method is called from BaseFundsLookupableHelperServiceImpl.java,
   *     CurrentFundsLookupableHelperServiceImpl.java, LedgerBalanceLookupableHelperServiceImpl.java
   *     in ld module
   */
  @Override
  public boolean isConsolidationSelected(Map fieldValues, Collection<Row> rows) {
    boolean isConsolidationSelected = isConsolidationSelected(fieldValues);

    if (!isConsolidationSelected) {
      Field consolidationField = getConsolidationField(rows);
      consolidationField.setPropertyValue(Constant.DETAIL);
    }
    return isConsolidationSelected;
  }
 /**
  * @see
  *     org.kuali.kfs.module.ld.service.LaborInquiryOptionsService#getConsolidationField(java.util.Collection)
  */
 @Override
 public Field getConsolidationField(Collection<Row> rows) {
   for (Row row : rows) {
     for (Field field : (row.getFields())) {
       if (field.getPropertyName().equals(getConsolidationFieldName())) {
         return field;
       }
     }
   }
   return null;
 }
 /**
  * This override is reset field definitions
  *
  * @see org.kuali.core.lookup.AbstractLookupableHelperServiceImpl#getRows()
  */
 @Override
 public List<Row> getRows() {
   List<Row> rows = super.getRows();
   for (Row row : rows) {
     for (Field field : row.getFields()) {
       if (field.getPropertyName().equals(PI_NAME)) {
         super.updateLookupField(field, PI_NAME, AwardPerson.class.getName());
       }
     }
   }
   return rows;
 }
 /** @see org.kuali.rice.kns.lookup.AbstractLookupableHelperServiceImpl#getRows() */
 @Override
 public List<Row> getRows() {
   List<Row> rows = super.getRows();
   for (Row row : rows) {
     for (Field field : row.getFields()) {
       if (field.getPropertyName().equals("person.userName")) {
         field.setFieldConversions("principalName:person.userName,principalId:personId");
       }
     }
   }
   return rows;
 }
  /**
   * This method is to test getrows. The lookup fields will be updated and make sure a few of the
   * drop down fields are set as dropdown_refresh
   */
  @Test
  public void testGetRows() {

    List<Row> rows = protocolLookupableHelperServiceImpl.getRows();
    assertEquals(NUMBER_LOOKUP_CRITERIA_FIELDS, rows.size());
    for (Row row : rows) {
      for (Field field : row.getFields()) {
        if (field.getPropertyName().equals("researchAreaCode")) {
          assertDropDownField(field, "researchAreaCode", "org.kuali.kra.irb.ResearchArea");
        }
      }
    }
  }
  /**
   * Produces legacy KNS rows to use for search attributes. This method was left intact to help ease
   * conversion until KNS is replaced with KRAD.
   */
  protected List<Row> getSearchingRows(String documentTypeName) {

    List<Row> docSearchRows = new ArrayList<Row>();

    Class boClass = DocumentHeader.class;

    Field descriptionField = FieldUtils.getPropertyField(boClass, "documentDescription", true);
    descriptionField.setFieldDataType(
        KewApiConstants.SearchableAttributeConstants.DATA_TYPE_STRING);

    Field orgDocNumberField =
        FieldUtils.getPropertyField(boClass, "organizationDocumentNumber", true);
    orgDocNumberField.setFieldDataType(
        KewApiConstants.SearchableAttributeConstants.DATA_TYPE_STRING);

    List<Field> fieldList = new ArrayList<Field>();
    fieldList.add(descriptionField);
    docSearchRows.add(new Row(fieldList));

    fieldList = new ArrayList<Field>();
    fieldList.add(orgDocNumberField);
    docSearchRows.add(new Row(fieldList));

    DocumentEntry entry =
        KRADServiceLocatorWeb.getDataDictionaryService()
            .getDataDictionary()
            .getDocumentEntry(documentTypeName);
    if (entry == null) return docSearchRows;
    if (entry instanceof MaintenanceDocumentEntry) {
      Class<? extends BusinessObject> businessObjectClass =
          getBusinessObjectClass(documentTypeName);
      Class<? extends Maintainable> maintainableClass = getMaintainableClass(documentTypeName);

      KualiGlobalMaintainableImpl globalMaintainable = null;
      try {
        globalMaintainable = (KualiGlobalMaintainableImpl) maintainableClass.newInstance();
        businessObjectClass = globalMaintainable.getPrimaryEditedBusinessObjectClass();
      } catch (Exception ie) {
        // was not a globalMaintainable.
      }

      if (businessObjectClass != null)
        docSearchRows.addAll(createFieldRowsForBusinessObject(businessObjectClass));
    }

    WorkflowAttributes workflowAttributes = entry.getWorkflowAttributes();
    if (workflowAttributes != null)
      docSearchRows.addAll(createFieldRowsForWorkflowAttributes(workflowAttributes));

    return docSearchRows;
  }
  /**
   * To disable the search icon for 'title' & 'scheduleddate' fields. These fields are referencing
   * to reference objects' fields.
   *
   * @see org.kuali.rice.kns.lookup.AbstractLookupableHelperServiceImpl#getRows()
   */
  @Override
  public List<Row> getRows() {
    List<Row> rows = super.getRows();
    for (Row row : rows) {
      for (Field field : row.getFields()) {
        if (PROTOCOL_TITLE.equals(field.getPropertyName())
            || COMMITTEE_SCHEDULE_SCHEDULE_DATE.equals(field.getPropertyName())) {

          field.setQuickFinderClassNameImpl(KRADConstants.EMPTY_STRING);
        }
      }
    }
    return rows;
  }
 private void assertFieldProperties(Field field, String keyName, String className) {
   assertEquals(field.getFieldConversions(), keyName + Constants.COLON + field.getPropertyName());
   assertTrue(field.isFieldDirectInquiryEnabled());
   assertEquals(field.getLookupParameters(), field.getPropertyName() + Constants.COLON + keyName);
   assertEquals(field.getInquiryParameters(), field.getPropertyName() + Constants.COLON + keyName);
   assertEquals(field.getQuickFinderClassNameImpl(), className);
 }
  public static final Field setFieldQuickfinder(
      BusinessObject businessObject,
      String collectionName,
      boolean addLine,
      int index,
      String attributeName,
      Field field,
      List<String> displayedFieldNames,
      Maintainable maintainable,
      MaintainableFieldDefinition maintainableFieldDefinition) {
    if (maintainableFieldDefinition.getOverrideLookupClass() != null
        && StringUtils.isNotBlank(maintainableFieldDefinition.getOverrideFieldConversions())) {
      if (maintainable != null) {
        String collectionPrefix = "";
        if (collectionName != null) {
          if (addLine) {
            collectionPrefix = KRADConstants.MAINTENANCE_ADD_PREFIX + collectionName + ".";
          } else {
            collectionPrefix = collectionName + "[" + index + "].";
          }
        }
        field.setQuickFinderClassNameImpl(
            maintainableFieldDefinition.getOverrideLookupClass().getName());

        String prefixedFieldConversions =
            prefixFieldConversionsDestinationsWithCollectionPrefix(
                maintainableFieldDefinition.getOverrideFieldConversions(), collectionPrefix);
        field.setFieldConversions(prefixedFieldConversions);
        field.setBaseLookupUrl(LookupUtils.getBaseLookupUrl(false));
        field.setReferencesToRefresh(
            LookupUtils.convertReferencesToSelectCollectionToString(
                maintainable.getAffectedReferencesFromLookup(
                    businessObject, attributeName, collectionPrefix)));
      }
      return field;
    }
    if (maintainableFieldDefinition.isNoLookup()) {
      return field;
    }
    return LookupUtils.setFieldQuickfinder(
        businessObject,
        collectionName,
        addLine,
        index,
        attributeName,
        field,
        displayedFieldNames,
        maintainable);
  }
  /**
   * Sets up the field for rendering by setting the right property name and zeroing out amounts
   * which aren't needed
   *
   * @param field the field to prepare
   * @param accountingLine the accounting line being rendered
   * @param count the count of the current line in the source lines, or null if it's a new line
   *     <p>KRAD Conversion: Customization of preparing the fields for rendering - No use of data
   *     dictionary
   */
  protected void prepareFieldForRendering(Field field, VoucherForm form, Integer count) {
    getDebitOrCreditField().setPropertyPrefix(null);

    // set the right property name
    if (count == null) {
      field.setPropertyName(getNewLineProperty());
    } else {
      final String subPropertyName = isDebit ? "debit" : "credit";
      field.setPropertyName(
          getCollectionProperty() + "[" + count.toString() + "]." + subPropertyName);
    }

    // get the value from the form
    field.setPropertyValue(ObjectUtils.getPropertyValue(form, field.getPropertyName()));
  }
  @Override
  public List<Row> getRows() {

    List<Row> rows = super.getRows();
    for (Row row : rows) {
      for (Field field : row.getFields()) {
        if (field.getPropertyName().equals(USERNAME_FIELD)) {
          field.setFieldConversions(FIELD_CONVERSIONS);
        }
        if (field.getPropertyName().equals(LOG_STATUS) && isLookupToCreateProposal()) {
          field.setPropertyValue(STATUS_PENDING);
        }
      }
    }
    return rows;
  }
  @Test
  public void testMultiCampusRows() {
    service.setBusinessObjectClass(Unit.class);
    service.setParameterService(getMockParameterService(true));
    GlobalVariables.getUserSession()
        .addObject(MultiCampusConstants.USER_CAMPUS_CODE_KEY, (Object) CAMPUS_CODE);

    List<Row> rows = service.getRows();
    assertEquals(LOOKUP_CRITERIA_FIELD_COUNT, rows.size());
    for (Row row : rows) {
      for (Field field : row.getFields()) {
        if (field.getPropertyName().equals(CAMPUS_CODE_FIELD)) {
          assertFieldProperties(field, CAMPUS_CODE_FIELD, CAMPUS_LOOKUPABLE_CLASS_NAME);
          assertEquals(CAMPUS_CODE, field.getPropertyValue());
        }
      }
    }
  }
 /**
  * This method recurses through all the fields of the list of rows and adds each field's property
  * name to the set if it starts with Constants.MAINTENANCE_NEW_MAINTAINABLE
  *
  * @param listOfRows
  * @param errorKeys
  * @see KRADConstants#MAINTENANCE_NEW_MAINTAINABLE
  */
 protected static void addRowsToErrorKeySet(List<Row> listOfRows, Set<String> errorKeys) {
   if (listOfRows == null) {
     return;
   }
   for (Row row : listOfRows) {
     List<Field> fields = row.getFields();
     if (fields == null) {
       continue;
     }
     for (Field field : fields) {
       String fieldPropertyName = field.getPropertyName();
       if (fieldPropertyName != null
           && fieldPropertyName.startsWith(KRADConstants.MAINTENANCE_NEW_MAINTAINABLE)) {
         errorKeys.add(field.getPropertyName());
       }
       addRowsToErrorKeySet(field.getContainerRows(), errorKeys);
     }
   }
 }
 /**
  * @see
  *     org.kuali.kfs.sys.document.web.RenderableElement#renderElement(javax.servlet.jsp.PageContext,
  *     javax.servlet.jsp.tagext.Tag,
  *     org.kuali.kfs.sys.document.web.AccountingLineRenderingContext)
  */
 public void renderElement(
     PageContext pageContext, Tag parentTag, AccountingLineRenderingContext renderingContext)
     throws JspException {
   if (!renderingContext.isFieldModifyable(debitOrCreditField.getPropertyName())) {
     debitOrCreditField.setReadOnly(true);
   }
   FieldRenderer renderer =
       SpringContext.getBean(AccountingLineRenderingService.class)
           .getFieldRendererForField(
               getDebitOrCreditField(), renderingContext.getAccountingLine());
   if (renderer != null) {
     prepareFieldForRendering(
         getDebitOrCreditField(),
         (VoucherForm) renderingContext.getForm(),
         renderingContext.getCurrentLineCount());
     renderer.setField(getDebitOrCreditField());
     renderer.render(pageContext, parentTag);
     renderer.clear();
   }
 }
  /**
   * Creates a list of search fields, one for each primary key of the maintained business object
   *
   * @param businessObjectClass the class of the maintained business object
   * @return a List of KEW search fields
   */
  protected List<Row> createFieldRowsForBusinessObject(
      Class<? extends BusinessObject> businessObjectClass) {
    List<Row> searchFields = new ArrayList<Row>();

    final List primaryKeyNamesAsObjects =
        KRADServiceLocatorWeb.getLegacyDataAdapter().listPrimaryKeyFieldNames(businessObjectClass);
    final BusinessObjectEntry boEntry =
        KRADServiceLocatorWeb.getDataDictionaryService()
            .getDataDictionary()
            .getBusinessObjectEntry(businessObjectClass.getName());
    final WorkflowAttributePropertyResolutionService propertyResolutionService =
        KNSServiceLocator.getWorkflowAttributePropertyResolutionService();
    for (Object primaryKeyNameAsObject : primaryKeyNamesAsObjects) {

      String attributeName = (String) primaryKeyNameAsObject;
      BusinessObject businessObject = null;
      try {
        businessObject = businessObjectClass.newInstance();
      } catch (Exception e) {
        throw new RuntimeException(e);
      }

      Field searchField = FieldUtils.getPropertyField(businessObjectClass, attributeName, false);
      String dataType =
          propertyResolutionService.determineFieldDataType(businessObjectClass, attributeName);
      searchField.setFieldDataType(dataType);
      List<Field> fieldList = new ArrayList<Field>();

      List displayedFieldNames = new ArrayList();
      displayedFieldNames.add(attributeName);
      LookupUtils.setFieldQuickfinder(
          businessObject, attributeName, searchField, displayedFieldNames);

      fieldList.add(searchField);
      searchFields.add(new Row(fieldList));
    }

    return searchFields;
  }
 /** @see org.kuali.rice.kns.lookup.AbstractLookupableHelperServiceImpl#getRows() */
 @Override
 public List<Row> getRows() {
   List<Row> superResults = super.getRows();
   if (superResults != null) {
     for (Row row : superResults) {
       for (Field field : row.getFields()) {
         if (KFSPropertyConstants.ACCOUNT_NUMBER.equals(field.getPropertyName())) {
           // because of limitations in BO Metadata service, the account quickfinder was going to
           // prior year account instead of account, therefore
           // need to force it to go to Account (or whatever's mapped to the "account" reference in
           // OJB
           Class clazz =
               getPersistenceStructureService()
                   .getBusinessObjectAttributeClass(
                       businessObjectClass, KFSPropertyConstants.ACCOUNT);
           field.setQuickFinderClassNameImpl(clazz.getName());
           return superResults;
         }
       }
     }
   }
   return superResults;
 }
 /**
  * Goes through all the rows, making sure that problematic field conversions are fixed
  *
  * <p>KRAD Conversion: Performs customization of the fields.
  */
 protected void convertOrganizationOwnerAccountField() {
   boolean foundField = false;
   int i = 0;
   while (!foundField && i < super.getRows().size()) {
     final Row r = super.getRows().get(i);
     int j = 0;
     while (!foundField && j < r.getFields().size()) {
       Field f = r.getField(j);
       if (f.getPropertyName().equals(CamsPropertyConstants.Asset.ORGANIZATION_CODE)) {
         f.setFieldConversions(fixProblematicField(f.getFieldConversions()));
         f.setLookupParameters(fixProblematicField(f.getLookupParameters()));
         foundField = true;
       }
       j += 1;
     }
     i += 1;
   }
 }
 /*
  *
  * This method is to make sure the looks fields are set up properly.
  * @param field
  * @param keyName
  * @param className
  */
 private void assertDropDownField(Field field, String keyName, String className) {
   assertEquals(field.getFieldConversions(), keyName + ":" + field.getPropertyName());
   assertEquals(field.getLookupParameters(), field.getPropertyName() + ":" + keyName);
   assertEquals(field.getInquiryParameters(), field.getPropertyName() + ":" + keyName);
   assertEquals(field.getQuickFinderClassNameImpl(), className);
 }
  /**
   * Sets the Milestone in the passed in section to be readonly if it has been copied to a CG
   * Invoice doc.
   *
   * @param section Milestone section to review and possibly set readonly
   * @param proposalNumber used to look for CG Invoice docs
   */
  private void prepareMilestonesTab(Section section, Long proposalNumber) {
    ContractsGrantsInvoiceDocumentService cgInvDocService =
        SpringContext.getBean(ContractsGrantsInvoiceDocumentService.class);

    for (Row row : section.getRows()) {
      for (Field field : row.getFields()) {
        if (field.getCONTAINER().equalsIgnoreCase(field.getFieldType())) {
          for (Row containerRow : field.getContainerRows()) {
            for (Field containerRowfield : containerRow.getFields()) {
              // a record is no longer editable if the bill has been copied to a CINV doc
              if (ObjectUtils.getNestedAttributePrimitive(containerRowfield.getPropertyName())
                  .matches(ArPropertyConstants.MilestoneFields.MILESTONE_IDENTIFIER)) {
                String milestoneId = containerRowfield.getPropertyValue();
                if (StringUtils.isNotEmpty(milestoneId)) {
                  if (cgInvDocService.hasMilestoneBeenCopiedToInvoice(
                      proposalNumber, milestoneId)) {
                    for (Field rowfield : row.getFields()) {
                      if (rowfield.getCONTAINER().equalsIgnoreCase(rowfield.getFieldType())) {
                        for (Row fieldContainerRow : rowfield.getContainerRows()) {
                          for (Field fieldContainerRowField : fieldContainerRow.getFields()) {
                            fieldContainerRowField.setReadOnly(true);
                          }
                        }
                      }
                    }
                  }
                }
              }
            }
          }
        }
      }
    }
  }
  protected List<Row> createFieldRowsForWorkflowAttributes(WorkflowAttributes attrs) {
    List<Row> searchFields = new ArrayList<Row>();

    List<SearchingTypeDefinition> searchingTypeDefinitions = attrs.getSearchingTypeDefinitions();
    final WorkflowAttributePropertyResolutionService propertyResolutionService =
        KNSServiceLocator.getWorkflowAttributePropertyResolutionService();
    for (SearchingTypeDefinition definition : searchingTypeDefinitions) {
      SearchingAttribute attr = definition.getSearchingAttribute();

      final String attributeName = attr.getAttributeName();
      final String businessObjectClassName = attr.getBusinessObjectClassName();
      Class boClass = null;
      Object businessObject = null;
      try {
        boClass = Class.forName(businessObjectClassName);
        businessObject = (Object) boClass.newInstance();
      } catch (Exception e) {
        throw new RuntimeException(e);
      }

      Field searchField = FieldUtils.getPropertyField(boClass, attributeName, false);
      // prepend all document attribute field names with "documentAttribute."
      // searchField.setPropertyName(KewApiConstants.DOCUMENT_ATTRIBUTE_FIELD_PREFIX +
      // searchField.getPropertyName());
      searchField.setColumnVisible(attr.isShowAttributeInResultSet());

      // TODO this is a workaround to hide the Field from the search criteria.
      // This should be removed once hiding the entire Row is working
      if (!attr.isShowAttributeInSearchCriteria()) {
        searchField.setFieldType(Field.HIDDEN);
      }
      String fieldDataType =
          propertyResolutionService.determineFieldDataType(boClass, attributeName);
      if (fieldDataType.equals(DataDictionarySearchableAttribute.DATA_TYPE_BOOLEAN)) {
        fieldDataType = KewApiConstants.SearchableAttributeConstants.DATA_TYPE_STRING;
      }

      // Allow inline range searching on dates and numbers
      if (fieldDataType.equals(KewApiConstants.SearchableAttributeConstants.DATA_TYPE_FLOAT)
          || fieldDataType.equals(KewApiConstants.SearchableAttributeConstants.DATA_TYPE_LONG)
          || fieldDataType.equals(KewApiConstants.SearchableAttributeConstants.DATA_TYPE_DATE)) {

        searchField.setAllowInlineRange(true);
      }
      searchField.setFieldDataType(fieldDataType);
      List displayedFieldNames = new ArrayList();
      displayedFieldNames.add(attributeName);
      LookupUtils.setFieldQuickfinder(
          businessObject, attributeName, searchField, displayedFieldNames);

      List<Field> fieldList = new ArrayList<Field>();
      fieldList.add(searchField);

      Row row = new Row(fieldList);
      if (!attr.isShowAttributeInSearchCriteria()) {
        row.setHidden(true);
      }
      searchFields.add(row);
    }

    return searchFields;
  }