/**
  * 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());
 }
  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);
  }
  public ActionForward search(
      ActionMapping mapping,
      ActionForm form,
      HttpServletRequest request,
      HttpServletResponse response)
      throws Exception {
    ReportTrackingLookupForm lookupForm = (ReportTrackingLookupForm) form;

    Lookupable kualiLookupable = lookupForm.getLookupable();
    if (kualiLookupable == null) {
      LOG.error("Lookupable is null.");
      throw new RuntimeException("Lookupable is null.");
    }

    // validate search parameters
    kualiLookupable.validateSearchParameters(lookupForm.getFields());

    if (lookupForm.isViewRawResults()) {
      return super.search(mapping, lookupForm, request, response);
    } else {
      LookupUtils.preProcessRangeFields(lookupForm.getFields());
      List<ReportTracking> groupedResults =
          getReportTrackingDao()
              .getResultsGroupedBy(
                  lookupForm.getFields(),
                  lookupForm.getGroupedByFields(),
                  lookupForm.getGroupedByDisplayFields());
      lookupForm.setGroupedByResults(groupedResults);
      return mapping.findForward(Constants.MAPPING_BASIC);
    }
  }
 public static final void setFieldDirectInquiry(
     BusinessObject businessObject,
     String attributeName,
     MaintainableFieldDefinition maintainableFieldDefinition,
     Field field,
     List<String> displayedFieldNames) {
   LookupUtils.setFieldDirectInquiry(businessObject, attributeName, field);
 }
 public static final void setFieldDirectInquiry(
     BusinessObject businessObject,
     String collectionName,
     boolean addLine,
     int index,
     String attributeName,
     Field field,
     List<String> displayedFieldNames,
     Maintainable maintainable,
     MaintainableFieldDefinition maintainableFieldDefinition) {
   LookupUtils.setFieldDirectInquiry(businessObject, attributeName, field);
 }
 /**
  * @param lookupResultsSequenceNumber
  * @param personId
  * @return Set<String>
  */
 public Set<String> retrieveSetOfSelectedObjectIds(
     String lookupResultsSequenceNumber, String personId) throws Exception {
   SelectedObjectIds selectedObjectIds = retrieveSelectedObjectIds(lookupResultsSequenceNumber);
   if (!isAuthorizedToAccessSelectedObjectIds(selectedObjectIds, personId)) {
     throw new AuthorizationException(
         personId,
         "retrieve lookup results",
         "lookup sequence number " + lookupResultsSequenceNumber);
   }
   Set<String> retval =
       LookupUtils.convertStringOfObjectIdsToSet(selectedObjectIds.getSelectedObjectIds());
   return retval;
 }
 /**
  * @see org.kuali.rice.kns.lookup.LookupResultsService#persistSelectedObjectIds(java.lang.String,
  *     java.util.Set, java.lang.String)
  */
 @Override
 public void persistSelectedObjectIds(
     String lookupResultsSequenceNumber, Set<String> selectedObjectIds, String personId)
     throws Exception {
   SelectedObjectIds selectedObjectIdsBO = retrieveSelectedObjectIds(lookupResultsSequenceNumber);
   if (selectedObjectIdsBO == null) {
     selectedObjectIdsBO = new SelectedObjectIds();
     selectedObjectIdsBO.setLookupResultsSequenceNumber(lookupResultsSequenceNumber);
   }
   selectedObjectIdsBO.setLookupResultsSequenceNumber(lookupResultsSequenceNumber);
   selectedObjectIdsBO.setLookupPersonId(personId);
   selectedObjectIdsBO.setSelectedObjectIds(
       LookupUtils.convertSetOfObjectIdsToString(selectedObjectIds));
   selectedObjectIdsBO.setLookupDate(getDateTimeService().getCurrentTimestamp());
   getBusinessObjectService().save(selectedObjectIdsBO);
 }
 public ActionForward getDetails(
     ActionMapping mapping,
     ActionForm form,
     HttpServletRequest request,
     HttpServletResponse response)
     throws Exception {
   ReportTrackingLookupForm lookupForm = (ReportTrackingLookupForm) form;
   LookupUtils.preProcessRangeFields(lookupForm.getFields());
   Map<String, String> allFields = new HashMap<String, String>(lookupForm.getFields());
   populateAggregateValues(
       lookupForm.getGroupedByResults().get(lookupForm.getGroupByResultIndex()),
       allFields,
       lookupForm.getGroupedByFields());
   List<ReportTracking> detailResults =
       getReportTrackingDao().getDetailResults(allFields, lookupForm.getDetailFields());
   lookupForm.setDetailResults(detailResults);
   return mapping.findForward("ajaxDetails");
 }
  /**
   * 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;
  }
  /**
   * get the relationship metadata for the detail line fields
   *
   * @return the relationship metadata for the detail line fields
   */
  public Map<String, DataObjectRelationship> getRelationshipMetadata() {
    LOG.debug("getRelationshipMetadata() start");

    PersistenceStructureService persistenceStructureService =
        SpringContext.getBean(PersistenceStructureService.class);

    Map<String, DataObjectRelationship> relationshipMetadata =
        new HashMap<String, DataObjectRelationship>();
    for (String attributeName : this.getInquirableFieldNames()) {
      Map<String, Class<? extends BusinessObject>> primitiveReference =
          LookupUtils.getPrimitiveReference(newDetailLine, attributeName);

      if (primitiveReference != null && !primitiveReference.isEmpty()) {
        DataObjectRelationship primitiveRelationship =
            this.getPrimitiveDataObjectRelationship(
                persistenceStructureService.getRelationshipMetadata(
                    newDetailLine.getClass(), attributeName));
        relationshipMetadata.put(attributeName, primitiveRelationship);
      }
    }

    return relationshipMetadata;
  }
  /**
   * This method will remove all PO related transactions from display on GL results
   *
   * @see org.kuali.rice.kns.lookup.KualiLookupableHelperServiceImpl#getSearchResults(java.util.Map)
   */
  @Override
  public List<? extends BusinessObject> getSearchResults(Map<String, String> fieldValues) {
    // update status code from user input value to DB value.
    updateStatusCodeCriteria(fieldValues);

    List<? extends BusinessObject> searchResults = super.getSearchResults(fieldValues);
    if (searchResults == null || searchResults.isEmpty()) {
      return searchResults;
    }
    Integer searchResultsLimit = LookupUtils.getSearchResultsLimit(GeneralLedgerEntry.class);
    Long matchingResultsCount = null;
    List<GeneralLedgerEntry> newList = new ArrayList<GeneralLedgerEntry>();
    for (BusinessObject businessObject : searchResults) {
      GeneralLedgerEntry entry = (GeneralLedgerEntry) businessObject;
      if (!CabConstants.PREQ.equals(entry.getFinancialDocumentTypeCode())) {
        if (!CabConstants.CM.equals(entry.getFinancialDocumentTypeCode())) {
          newList.add(entry);
        } else if (CabConstants.CM.equals(entry.getFinancialDocumentTypeCode())) {
          Map<String, String> cmKeys = new HashMap<String, String>();
          cmKeys.put(
              CabPropertyConstants.PurchasingAccountsPayableDocument.DOCUMENT_NUMBER,
              entry.getDocumentNumber());
          // check if CAB PO document exists, if not included
          Collection<PurchasingAccountsPayableDocument> matchingCreditMemos =
              businessObjectService.findMatching(PurchasingAccountsPayableDocument.class, cmKeys);
          if (matchingCreditMemos == null || matchingCreditMemos.isEmpty()) {
            newList.add(entry);
          }
        }
      }
    }
    matchingResultsCount = Long.valueOf(newList.size());
    if (matchingResultsCount.intValue() <= searchResultsLimit.intValue()) {
      matchingResultsCount = new Long(0);
    }
    return new CollectionIncomplete(newList, matchingResultsCount);
  }
  /**
   * @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);
  }
 protected Set<String> parsePreviouslySelectedObjectIds(HttpServletRequest request) {
   String previouslySelectedObjectIds =
       request.getParameter(KRADConstants.MULTIPLE_VALUE_LOOKUP_PREVIOUSLY_SELECTED_OBJ_IDS_PARAM);
   return LookupUtils.convertStringOfObjectIdsToSet(previouslySelectedObjectIds);
 }
 /**
  * This method converts the composite object IDs into a String
  *
  * @return
  */
 public String getCompositeSelectedObjectIds() {
   return LookupUtils.convertSetOfObjectIdsToString(getCompositeObjectIdMap().keySet());
 }
  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;
  }
  @Override
  public List<? extends BusinessObject> getSearchResults(Map<String, String> fieldValues) {
    List<FunctionalFieldDescription> functionalFieldDescriptions =
        kfsBusinessObjectMetaDataService.findFunctionalFieldDescriptions(
            fieldValues.get(OLEPropertyConstants.NAMESPACE_CODE),
            fieldValues.get(
                OLEPropertyConstants
                    .FUNCTIONAL_FIELD_DESCRIPTION_BUSINESS_OBJECT_PROPERTY_COMPONENT_LABEL),
            fieldValues.get(
                OLEPropertyConstants.FUNCTIONAL_FIELD_DESCRIPTION_BUSINESS_OBJECT_PROPERTY_LABEL),
            fieldValues.get(OLEPropertyConstants.FUNCTIONAL_FIELD_DESCRIPTION_DESCRIPTION),
            "Y");
    List<BusinessObjectProperty> businessObjectProperties =
        kfsBusinessObjectMetaDataService.findBusinessObjectProperties(
            fieldValues.get(OLEPropertyConstants.NAMESPACE_CODE),
            fieldValues.get(
                OLEPropertyConstants
                    .FUNCTIONAL_FIELD_DESCRIPTION_BUSINESS_OBJECT_PROPERTY_COMPONENT_LABEL),
            fieldValues.get(
                OLEPropertyConstants.FUNCTIONAL_FIELD_DESCRIPTION_BUSINESS_OBJECT_PROPERTY_LABEL));
    Map<String, BusinessObject> matches = new HashMap<String, BusinessObject>();
    for (FunctionalFieldDescription functionalFieldDescription : functionalFieldDescriptions) {
      if (kfsBusinessObjectMetaDataService.isMatch(
          functionalFieldDescription.getComponentClass(),
          functionalFieldDescription.getPropertyName(),
          fieldValues.get(OLEPropertyConstants.TABLE_NAME),
          fieldValues.get(OLEPropertyConstants.FIELD_NAME))) {
        matches.put(
            functionalFieldDescription.getComponentClass()
                + functionalFieldDescription.getPropertyName(),
            functionalFieldDescription);
      }
    }
    if (StringUtils.isBlank(
        fieldValues.get(OLEPropertyConstants.FUNCTIONAL_FIELD_DESCRIPTION_DESCRIPTION))) {
      for (BusinessObjectProperty businessObjectProperty : businessObjectProperties) {
        if (!matches.containsKey(
                businessObjectProperty.getComponentClass()
                    + businessObjectProperty.getPropertyName())
            && kfsBusinessObjectMetaDataService.isMatch(
                businessObjectProperty.getComponentClass(),
                businessObjectProperty.getPropertyName(),
                fieldValues.get(OLEPropertyConstants.TABLE_NAME),
                fieldValues.get(OLEPropertyConstants.FIELD_NAME))) {
          matches.put(
              businessObjectProperty.getComponentClass() + businessObjectProperty.getPropertyName(),
              businessObjectProperty);
        }
      }
    }

    Map<String, DataMappingFieldDefinition> dataMappingFieldDefinitions =
        new HashMap<String, DataMappingFieldDefinition>();
    int searchResultsLimit = LookupUtils.getSearchResultsLimit(DataMappingFieldDefinition.class);
    int iterationCount = 0;
    for (BusinessObject businessObject : matches.values()) {
      if (++iterationCount <= searchResultsLimit) {
        if (businessObject instanceof FunctionalFieldDescription) {
          FunctionalFieldDescription functionalFieldDescription =
              (FunctionalFieldDescription) businessObject;
          dataMappingFieldDefinitions.put(
              functionalFieldDescription.getComponentClass()
                  + functionalFieldDescription.getPropertyName(),
              kfsBusinessObjectMetaDataService.getDataMappingFieldDefinition(
                  functionalFieldDescription));
        } else {
          BusinessObjectProperty businessObjectProperty = (BusinessObjectProperty) businessObject;
          dataMappingFieldDefinitions.put(
              businessObjectProperty.getComponentClass() + businessObjectProperty.getPropertyName(),
              kfsBusinessObjectMetaDataService.getDataMappingFieldDefinition(
                  businessObjectProperty.getComponentClass(),
                  businessObjectProperty.getPropertyName()));
        }
      } else {
        break;
      }
    }

    List<DataMappingFieldDefinition> searchResults = null;
    if (matches.size() > searchResultsLimit) {
      searchResults =
          new CollectionIncomplete(
              dataMappingFieldDefinitions.values(), Long.valueOf(matches.size()));
    } else {
      searchResults = new CollectionIncomplete(dataMappingFieldDefinitions.values(), 0L);
    }
    Collections.sort(searchResults, new BeanPropertyComparator(getSortProperties(), true));
    return searchResults;
  }