Package com.sourcetap.sfa.ui

Source Code of com.sourcetap.sfa.ui.UIUtility

/*
*
* Copyright (c) 2004 SourceTap - www.sourcetap.com
*
*  The contents of this file are subject to the SourceTap Public License
* ("License"); You may not use this file except in compliance with the
* License. You may obtain a copy of the License at http://www.sourcetap.com/license.htm
* Software distributed under the License is distributed on an  "AS IS"  basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for
* the specific language governing rights and limitations under the License.
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
*/

package com.sourcetap.sfa.ui;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;
import java.util.Vector;

import org.ofbiz.base.util.Debug;
import org.ofbiz.base.util.UtilMisc;
import org.ofbiz.entity.GenericDelegator;
import org.ofbiz.entity.GenericEntityException;
import org.ofbiz.entity.GenericPK;
import org.ofbiz.entity.GenericValue;
import org.ofbiz.entity.condition.EntityComparisonOperator;
import org.ofbiz.entity.condition.EntityCondition;
import org.ofbiz.entity.condition.EntityConditionList;
import org.ofbiz.entity.condition.EntityExpr;
import org.ofbiz.entity.condition.EntityOperator;
import org.ofbiz.entity.model.DynamicViewEntity;
import org.ofbiz.entity.model.ModelEntity;
import org.ofbiz.entity.model.ModelKeyMap;

import com.sourcetap.sfa.event.GenericEventProcessor;
import com.sourcetap.sfa.util.EntityHelper;
import com.sourcetap.sfa.util.QueryInfo;


/**
* DOCUMENT ME!
*
*/
public class UIUtility {
  public static final String module = UIUtility.class.getName();

    /**
     * DOCUMENT ME!
     *
     * @param entityDisplayDef
     * @param genericValueVector
     * @param currentAttibuteName
     *
     * @return
     */
    public static String decodeEntityDisplayDef(String entityDisplayDef,
        Vector genericValueVector, String currentAttibuteName) {
        if (entityDisplayDef == null) {
            Debug.logError("entityDisplayDef is null", module);

            return "ERROR";
        }

        if (genericValueVector.size() == 0) {
            Debug.logError("genericValueVector is empty.", module);

            return "ERROR";
        }

        if (currentAttibuteName == null) {
            Debug.logError("currentAttibuteName is null", module);

            return "ERROR";
        }

        Debug.logVerbose("[decodeEntityDisplayDef] entityDisplayDef: " +
                entityDisplayDef, module);

        Debug.logVerbose("[decodeEntityDisplayDef] genericValueVector: " +
                genericValueVector.toString(), module);

        Debug.logVerbose("[decodeEntityDisplayDef] currentAttibuteName: " +
                currentAttibuteName, module);

        // Dissect the display definition.
        // Example:
        // *  attribEntityDisplayDef = 'sicCodeId;" - ";SicCode.sicCodeDescription'
        // *  Resulting Display Value = '2074 - Cottonseed Oil Mills'
        String displayItem = "";
        StringTokenizer tokSemicolon = new StringTokenizer(entityDisplayDef, ";");
        GenericValue genericValue = null;
        String attributeName = "";

        while (tokSemicolon.hasMoreTokens()) {
            String valueDef = tokSemicolon.nextToken();

            Debug.logVerbose("valueDef = " + valueDef, module);

            if (valueDef.indexOf("\"") != -1) {
                // This is a literal string. Get the part between the 2 quotes and append it
                // directly onto the display value.
                int startPos = valueDef.indexOf("\"");
                int endPos = valueDef.lastIndexOf("\"");

                if ((startPos < 0) || (startPos >= (valueDef.length() - 1))) {
                    startPos = 0; // Missing first quote
                }

                if (endPos < (valueDef.length() - 1)) {
                    endPos = valueDef.length() - 1; // Missing last quote
                }

                Debug.logVerbose("startPos = " + String.valueOf(startPos), module);

                Debug.logVerbose("endPos = " + String.valueOf(endPos), module);

                displayItem += valueDef.substring(startPos + 1, endPos);
            } else {
                if (valueDef.indexOf(".") != -1) {

                    Debug.logVerbose("Found a period.", module);

                    StringTokenizer tokPeriod = new StringTokenizer(valueDef,
                            ".");
                    String entityName = tokPeriod.nextToken();
                    attributeName = tokPeriod.nextToken();

                    Debug.logVerbose("entityName = " + entityName, module);

                    Debug.logVerbose("attributeName = " + attributeName, module);

                    Iterator genericValueVectorI = genericValueVector.iterator();

                    while (genericValueVectorI.hasNext()) {
                        GenericValue testGV = (GenericValue) genericValueVectorI.next();

                        if (testGV.getEntityName().equals(entityName)) {

                            Debug.logVerbose("Found generic value with entity name " +
                                    entityName, module);

                            genericValue = testGV;
                        }
                    }
                } else {
                    Debug.logVerbose("Did not find a period.", module);

                    genericValue = (GenericValue) genericValueVector.get(0);
                    attributeName = valueDef;
                }

                // This is not a literal.  Treat it as an attribute name.
                if (attributeName.equals("#currentField")) {
                    attributeName = (currentAttibuteName == null) ? ""
                                                                  : currentAttibuteName;
                }

                try {
                    displayItem += ((genericValue.get(attributeName) != null)
                    ? String.valueOf(genericValue.get(attributeName)) : "");
                } catch (Exception e) {
                    //          throw new GenericEntityException("");
                    Debug.logError(e.getMessage(),module);
                    Debug.logError("Entity display definition \"" +
                        entityDisplayDef + "\" not valid", module);

                    //                         for genericValue " + genericValue.toString() +
                    //            ".  Error message: " + e.toString());
                    return "ERROR";
                }
            }
        }

        return displayItem;
    }

    /**
     * DOCUMENT ME!
     *
     * @param entityFindDef
     * @param entityDetailsVector
     * @param currentAttibuteName
     *
     * @return
     */
    public static HashMap decodeEntityFindDef(String entityFindDef,
        Vector entityDetailsVector, String currentAttributeName) {
        // Split the entity find definition into pieces.  Example:
        // * attribEntityFindDef:
        //     * sectionId:sectionId;partyId:"-1"
        // * Resulting find map pairs:
        //     * sectionId:43
        //     * partyId:-1
        // * Resulting find logic:
        //     * sectionId = 43 AND partyId = -1
        String findAttributeValue = "";
        HashMap entityFindMap = new HashMap();
        StringTokenizer tokSemicolon = new StringTokenizer(entityFindDef, ";");
        String entityName = "";

        Debug.logVerbose(
                "-->[UIUtility.decodeEntityFindDef] Inside decodeEntityFindDef method.  Find def is '" +
                entityFindDef + "'.", module);

        while (tokSemicolon.hasMoreTokens()) {
            Debug.logVerbose(
                    "-->[UIUtility.decodeEntityFindDef] Found a semicolon", module);

            String pair = tokSemicolon.nextToken();
            StringTokenizer tokColon = new StringTokenizer(pair, ":");

            if (tokColon.countTokens() != 2) {
                Debug.logWarning(
                        "-->[UIUtility.decodeEntityFindDef] No colon found in '" +
                        pair + "'", module);
               

                Debug.logWarning(
                    "[UIUtility.decodeEntityFindDef]: Problem with entity find definition \"" +
                    entityFindDef + "\":", module);
                Debug.logWarning(
                    "There must be 2 items in each pair separated by colons.", module);

                return entityFindMap;
            } else {
                Debug.logVerbose(
                        "-->[UIUtility.decodeEntityFindDef] Colon found in '" +
                        pair + "'", module);

                String findAttributeName = tokColon.nextToken();
                if ( findAttributeName.equals("#currentField"))
                  findAttributeName = currentAttributeName;

                //        String screenAttributeString = tokColon.nextToken();
                String attributeValueSource = tokColon.nextToken();

                try {
                    findAttributeValue = decodeAttributeValue(attributeValueSource,
                            entityDetailsVector, currentAttributeName);
                } catch (GenericEntityException e) {
                    Debug.logError(
                        "[UIUtility.decodeFieldValue]: Problem with entity find definition \"" +
                        entityFindDef + "\": " + e.getLocalizedMessage(), module);
                    entityFindMap = null;

                    return entityFindMap;
                }

                //jmn start

                /*
                                                GenericValue screenEntityDetails = null;
                                                if(screenAttributeString.indexOf("\"") == -1) {
                                                        // There are no quote marks in the attribute name, so it is really an attribute name.  Get the value of this
                                                        // attribute from the screen entity.

                                                        // If there is a "." in the attribute name, split off the entity name.
                                                        StringTokenizer tokPeriod = new StringTokenizer(screenAttributeString, ".");
                                                        if(tokPeriod.countTokens() == 1) {
                                                                // There is no "." in the attribute string.  Assume we need to use the primary screen entity.
                                                                screenEntityName = ((GenericValue)(entityDetailsVector.get(0))).getEntityName();
                                                                screenAttributeName = screenAttributeString;
                                                        } else {
                                                                // Need to get the entity specified before the "." in the attribute name string.
                                                                screenEntityName = tokPeriod.nextToken();
                                                                screenAttributeName = tokPeriod.nextToken();
                                                        }
                                                        tokPeriod = null;
                                                        if (screenAttributeName.equals("#currentField")) {
                                                                screenAttributeName = currentAttibuteName==null ? "" : currentAttibuteName;
                                                        }

                                                        // Get the specified screen entity from the vector.
                                                        Iterator entityDetailsIterator = entityDetailsVector.iterator();
                                                        while (entityDetailsIterator.hasNext()) {
                                                                GenericValue testEntity = (GenericValue)entityDetailsIterator.next();
                                                                if (testEntity.getEntityName().equals(screenEntityName)) {
                                                                        screenEntityDetails = testEntity;
                                                                }
                                                        }
                                                        try {
                                                                String dummy = String.valueOf(screenEntityDetails.get(screenAttributeName));
                                                        }
                                                        catch (IllegalArgumentException e) {
                                                                Debug.logWarning("[UIUtility.decodeEntityFindDef]: Problem with entity find definition \"" + entityFindDef + "\":");
                                                                Debug.logWarning(e.getMessage());
                                                                entityFindMap = null;
                                                                return entityFindMap;
                                                        }
                                                        findAttributeValue = screenEntityDetails.getString(screenAttributeName);
                                                } else {
                                                        // This is a literal value because it has quote marks around it.
                                                        findAttributeValue = screenAttributeString.substring(screenAttributeString.indexOf("\"") + 1, screenAttributeString.lastIndexOf("\""));
                                                }
                */

                //jmn end
                // Put the attribute name and the screen value to which we are comparing into the find map.
                Debug.logVerbose(
                        "-->[UIUtility.decodeEntityFindDef] Appending onto entityFindMap: " +
                        findAttributeName + "/" + findAttributeValue, module);

                entityFindMap.put(findAttributeName, findAttributeValue);
            }

            tokColon = null;
        }

        tokSemicolon = null;

        return entityFindMap;
    }

    /**
     * Instantiates UIDropDown or one of its descendant classes.
     *
     * @param className The class to be instantiated
     *
     * @return Object of class specified by className parameter
     *
     * @see com.sourcetap.sfa.ui.UIDropDown
     */
    public static UIDropDown getUIDropDown(String className) {
        Class uiDropDownClass = null;
        UIDropDown uiDropdown = null;

        if ((className.length() > 0) && !className.equals("null")) {
            try {
                uiDropDownClass = Class.forName(className);
            } catch (ClassNotFoundException e) {
                Debug.logError("[UIUtility.getUIDropDown] Class \"" +
                    className +
                    "\" specified in display object could not be found.", module);
                Debug.logError(e, module);

                return null;
            }

            try {
                uiDropdown = (UIDropDown) uiDropDownClass.newInstance();
            } catch (IllegalAccessException e) {
                Debug.logError(
                    "[UIUtility.getUIDropDown]  Drop Down class \"" +
                    className + "\" could not be instantiated because " +
                    "the class or initializer is not accessible.", module);
                Debug.logError(e, module);

                return null;
            } catch (InstantiationException e) {
                Debug.logError("[UIUtility.getUIDropDown] Drop Down class \"" +
                    className + "\" cannot be instantiated because it is an " +
                    "abstract class, an interface, an array class, a primitive type, or void.", module);
                Debug.logError(e, module);

                return null;
            }
        } else {
            // Class name was not specified in the display object. Use the default class.
            uiDropdown = new UIDropDown();
        }

        // Return the new instance of UIDropDown.
        return uiDropdown;
    }

    /**
   * Instantiates GenericEventProcessor or one of its descendant classes.
   *
   * @param className The class to be instantiated
   *
   * @return Object of class specified by className parameter
   *
   * @see com.sourcetap.sfa.ui.UIDropDown
   */
  public static GenericEventProcessor getEventProcessor(String className) {
    Class eventProcessorClass = null;
    GenericEventProcessor eventProcessor = null;

    if ((className != null ) && (className.length() > 0) && !className.equals("null")) {
      try {
        eventProcessorClass = Class.forName(className);
      } catch (ClassNotFoundException e) {
        Debug.logError("[UIUtility.getEventProcessor] Class \"" +
          className +
          "\" specified in section.eventProcessorClass could not be found.", module);
        Debug.logError(e, module);

        return null;
      }

      try {
        eventProcessor = (GenericEventProcessor) eventProcessorClass.newInstance();
      } catch (IllegalAccessException e) {
        Debug.logError(
          "[UIUtility.getEventProcessor]  EventProcessor class \"" +
          className + "\" could not be instantiated because " +
          "the class or initializer is not accessible.", module);
        Debug.logError(e, module);

        return null;
      } catch (InstantiationException e) {
        Debug.logError("[UIUtility.getEventProcessor] EventProcessor class \"" +
          className + "\" cannot be instantiated because it is an " +
          "abstract class, an interface, an array class, a primitive type, or void.", module);
        Debug.logError(e, module);

        return null;
      }
    } else {
      // Class name was not specified in the display object. Use the default class.
      eventProcessor = new GenericEventProcessor();
    }

    // Return the new instance of UIDropDown.
    return eventProcessor;
  }

    /**
     * Instantiates UISearchField or one of its descendant classes.
     *
     * @param className The class to be instantiated
     *
     * @return Object of class specified by className parameter
     *
     * @see com.sourcetap.sfa.ui.UISearchField
     */
    public static UISearchField getUISearchField(String className) {
        Class UISearchFieldClass = null;
        UISearchField uiSearchField = null;

        if ((className.length() > 0) && !className.equals("null")) {
            // Class name was specified in the display object.  Need to instantiate that class.
            try {
                UISearchFieldClass = Class.forName(className);
            } catch (ClassNotFoundException e) {
                Debug.logError("[UIUtility.getUISearchField] Class \"" +
                    className +
                    "\" specified in display object could not be found.", module);
                Debug.logError(e, module);

                return null;
            }

            try {
                uiSearchField = (UISearchField) UISearchFieldClass.newInstance();
            } catch (IllegalAccessException e) {
                Debug.logError(
                    "[UIUtility.getUISearchField] Search field class \"" +
                    className + "\" could not be instantiated because " +
                    "the class or initializer is not accessible.", module);
                Debug.logError(e, module);

                return null;
            } catch (InstantiationException e) {
                Debug.logError(
                    "[UIUtility.getUISearchField] Search field class \"" +
                    className + "\" cannot be instantiated because it is an " +
                    "abstract class, an interface, an array class, a primitive type, or void.", module);
                Debug.logError(e, module);

                return null;
            }
        } else {
            // Class name was not specified in the display object. Use the default class.
            uiSearchField = new UISearchField();
        }

        // Return the new instance of UISearchField.
        return uiSearchField;
    }

    /**
     * DOCUMENT ME!
     *
     * @param delegator
     * @param searchAttribName
     * @param searchEntityName
     *
     * @return
     *
     * @throws GenericEntityException
     */
    public static String getAttributeId(GenericDelegator delegator,
        String searchAttribName, String searchEntityName)
        throws GenericEntityException {
        // Figure out the attribute ID for the UiAttribute this parameter corresponds to so we can
        // save the query.
        // select * from UiAttribute a, UIEntity e where e.entity_id = a.entity_id and a.attribute_name = <searchAttrName> and e.entityName = <searchEntityName>
       
        DynamicViewEntity dve = EntityHelper.createDynamicViewEntity( delegator, "UiAttribute");
    dve.addMemberEntity("UiEntity", "UiEntity");
    dve.addViewLink("UiAttribute", "UiEntity", Boolean.FALSE, UtilMisc.toList(new ModelKeyMap("entityId", "entityId")));
    dve.addAlias("UiEntity", "entityName", null, null, null, null, null);
    
    EntityCondition condition = new EntityConditionList(UtilMisc.toList(
        new EntityExpr("attributeName", EntityOperator.EQUALS, searchAttribName),
        new EntityExpr("entityName", EntityOperator.EQUALS, searchEntityName)),
        EntityOperator.AND);
       
        List queryGVL = EntityHelper.findByCondition( delegator, dve, condition, null );

        if (queryGVL.size() == 0) {
            throw new GenericEntityException(
                "No UI Attribute found for entity name \"" + searchEntityName +
                "\" and attribute name \"" + searchAttribName + "\"");
        }

        GenericValue uiAttributeGV = (GenericValue) queryGVL.iterator().next();
        String attributeId = uiAttributeGV.getString("attributeId");

        return attributeId;
    }

    /**
     * DOCUMENT ME!
     *
     * @param entityDetailsVector
     * @param entityName
     *
     * @return
     */
    public static GenericValue getEntityValue(Vector entityDetailsVector,
        String entityName) {
        // Get the specified entity from the vector.
        Iterator entityDetailsIterator = entityDetailsVector.iterator();

        while (entityDetailsIterator.hasNext()) {
            GenericValue testEntity = (GenericValue) entityDetailsIterator.next();

            if (testEntity.getEntityName().equals(entityName)) {
                return testEntity;
            }
        }

        return null;
    }

    /**
     * DOCUMENT ME!
     *
     * @param entityDetailsVector
     * @param entityName
     * @param attributeName
     *
     * @return
     */
    public static String getAttributeValue(Vector entityDetailsVector,
        String entityName, String attributeName) {
        GenericValue entityGV = UIUtility.getEntityValue(entityDetailsVector,
                entityName);

        if (entityGV == null) {
            return null;
        }

        try {
            String attribValue = String.valueOf(entityGV.get(attributeName));

            return attribValue;
        } catch (IllegalArgumentException e) {
            Debug.logError(
                "[UIUtility.getAttributeValue]: Problem getting entity atribute definition " +
                entityName + "." + attributeName, module);
            Debug.logError(e.getMessage(), module);
        }

        return null;
    }

    /**
     * DOCUMENT ME!
     *
     * @param selectedEntityPKL
     * @param eligibleEntityL
     *
     * @return
     */
    public static List removeSelectedEligibleEntities(List selectedEntityPKL,
        List eligibleEntityL) {
        Debug.logVerbose("[activityContactSelectAvailable] Start", module);

        Debug.logVerbose(
                "[activityContactSelectAvailable] selectedEntityPKL: " +
                selectedEntityPKL, module);

        Iterator eligibleEntityI = eligibleEntityL.iterator();

        while (eligibleEntityI.hasNext()) {
            GenericValue eligibleGV = (GenericValue) eligibleEntityI.next();

            // Look through the assigned keys to see if this key is already selected.
            Iterator selectedEntityPKI = selectedEntityPKL.iterator();

            while (selectedEntityPKI.hasNext()) {
                GenericPK selectedEntityPK = (GenericPK) selectedEntityPKI.next();

                if (selectedEntityPK.equals(eligibleGV.getPrimaryKey())) {
                    Debug.logVerbose(
                            "[activityContactSelectAvailable] Removing a selected item for PK " +
                            selectedEntityPK.toString(), module);

                    // This entity has already been selected. Remove it from the eligible list.
                    eligibleEntityI.remove();

                    break;
                }
            }
        }

        Debug.logVerbose(
                "[activityContactSelectAvailable] eligibleEntityL after removing selected items: " +
                eligibleEntityL, module);
        Debug.logVerbose("[activityContactSelectAvailable] End", module);

        return eligibleEntityL;
    }

    /**
     * DOCUMENT ME!
     *
     * @param action
     * @param fieldInfo
     *
     * @return
     */
    public static boolean getIsCopiedPrimaryKey(String action,
        UIFieldInfo fieldInfo) {
        if (action.equals(UIScreenSection.ACTION_SHOW_COPY) &&
                fieldInfo.getUiAttribute().getIsPk()) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * DOCUMENT ME!
     *
     * @param attributeValueSource
     * @param entityDetailsVector
     * @param currentAttibuteName
     *
     * @return
     *
     * @throws GenericEntityException
     */
    public static String decodeAttributeValue(String attributeValueSource,
        Vector entityDetailsVector, String currentAttibuteName)
        throws GenericEntityException {
        String screenEntityName = "";
        String screenAttributeName = "";
        GenericValue screenEntityDetails = null;

        Debug.logVerbose(
                "-->[UIUtility.decodeFieldValue] attributeValueSource: " +
                attributeValueSource, module);

        if (attributeValueSource.indexOf("\"") == -1) {
            // There are no quote marks in the attribute name, so it is really an attribute name.  Get the value of this
            // attribute from the screen entity.
            Debug.logVerbose(
                    "-->[UIUtility.decodeFieldValue] No quotes found in '" +
                    attributeValueSource + "'", module);

            // If there is a "." in the attribute name, split off the entity name.
            StringTokenizer tokPeriod = new StringTokenizer(attributeValueSource,
                    ".");

            if (tokPeriod.countTokens() == 1) {
                // There is no "." in the attribute string.  Assume we need to use the primary screen entity.
                Debug.logVerbose(
                        "-->[UIUtility.decodeFieldValue] No period found in '" +
                        attributeValueSource + "'.  Using the primary entity", module);

                screenEntityName = ((GenericValue) (entityDetailsVector.get(0))).getEntityName();
                screenAttributeName = attributeValueSource;
            } else {
                // Need to get the entity specified before the "." in the attribute name string.
                Debug.logVerbose(
                        "-->[UIUtility.decodeFieldValue] Period found in '" +
                        attributeValueSource +
                        "'.  Parsing the primary entity out of the find def.", module);

                screenEntityName = tokPeriod.nextToken();
                screenAttributeName = tokPeriod.nextToken();
            }

            tokPeriod = null;

            if (screenAttributeName.equals("#currentField")) {
                screenAttributeName = (currentAttibuteName == null) ? ""
                                                                    : currentAttibuteName;
                Debug.logVerbose(
                        "-->[UIUtility.decodeFieldValue] Replacing '#currentField' with '" +
                        screenAttributeName + "'", module);
            }

            Debug.logVerbose(
                    "-->[UIUtility.decodeFieldValue] Find Def Entity = " +
                    screenEntityName, module);
            Debug.logVerbose(
                    "-->[UIUtility.decodeFieldValue] Find Def Attrib = " +
                    screenAttributeName, module);

            // Get the specified screen entity from the vector.
            Iterator entityDetailsIterator = entityDetailsVector.iterator();

            while (entityDetailsIterator.hasNext()) {
                GenericValue testEntity = (GenericValue) entityDetailsIterator.next();

                if (testEntity.getEntityName().equals(screenEntityName)) {
                    screenEntityDetails = testEntity;
                }
            }

            try {
                String dummy = String.valueOf(screenEntityDetails.get(
                            screenAttributeName));
            } catch (IllegalArgumentException e) {
                throw new GenericEntityException(
                    "[UIUtility.decodeFieldValue]: Problem with attribute value definition \"" +
                    attributeValueSource + "\": " + e.getLocalizedMessage());

                //        Debug.logWarning("[UIUtility.decodeFieldValue]: Problem with entity find definition \"" + entityFindDef + "\":");
                //        Debug.logWarning(e.getMessage());
                //        entityFindMap = null;
                //        return entityFindMap;
            }

            return screenEntityDetails.getString(screenAttributeName);
        } else {
            Debug.logVerbose(
                    "-->[UIUtility.decodeEntityFindDef] Quotes found in '" +
                    attributeValueSource + "'.  Using literal value.", module);

            // This is a literal value because it has quote marks around it.
            return attributeValueSource.substring(attributeValueSource.indexOf(
                    "\"") + 1, attributeValueSource.lastIndexOf("\""));
        }
    }

    /**
     * Looks up the read-only value for the field to be shown on the screen instead
     * of a drop down select because the mode is read-only.
     *
     * @author  <a href='mailto:jnutting@sourcetap.com'>John Nutting</a>
     *
     * @param fieldValue Value stored or to be stored in the data base. Used as the primary key to look up the value to be displayed.
     * @param attributeName Name of the attribute being displayed
     * @param uiDisplayObject Reference to a display object defined in the data base and attached to the field to be displayed by the UI builder
     * @param entityDetailsVector Vector that holds one or more generic values from which the display value can be decoded
     * @param delegator Reference to the OFBIZ delegator being used to connect to the data base
     *
     * @return Array containing the data value and display value.
     */
    public static GenericValue getReadOnlyValue(String fieldValue,
        String attributeName, UIDisplayObject uiDisplayObject,
        Vector entityDetailsVector, GenericDelegator delegator) {

        GenericValue gv = null;

        if (fieldValue.trim().equals("")) {
            Debug.logVerbose("[getReadOnlyValue] Field value is empty.", module);

            // Field value is empty. Just display an empty string, and create a hidden field.
            return gv;
        } else {
            Debug.logVerbose(
                    "[getReadOnlyValue] Field value has contents. About to create the findByAnd field map.", module);

            // Decode the primary key entity find definition into a hash map that can be used
            // to create the primary key necessary for the findByPrimaryKey function.
            HashMap entityFindMap = UIUtility.decodeEntityFindDef(uiDisplayObject.getAttribEntityPkFindDef(),
                    entityDetailsVector, attributeName);

            if (entityFindMap == null) {
                Debug.logWarning("[getReadOnlyValue] Skipping field \"" +
                    attributeName + "\" because of faulty find definition: " +
                    uiDisplayObject.getAttribEntityPkFindDef(), module);

                return gv;
            }

            Debug.logVerbose(
                    "[getReadOnlyValue] Finished calling decodeEntityFindDef to decode find def '" +
                    uiDisplayObject.getAttribEntityPkFindDef() + "'.", module);
            Debug.logVerbose("[getReadOnlyValue] entityFindMap           -> " +
                    entityFindMap.toString(), module);

            // Find the entity by its primary key.
            ModelEntity entityEntity = delegator.getModelEntity(uiDisplayObject.getAttribEntity());
            GenericPK entityPk = new GenericPK(entityEntity, entityFindMap);

            try {
                gv = delegator.findByPrimaryKeyCache(entityPk);
            } catch (GenericEntityException e) {
                Debug.logError(
                    "[getReadOnlyValue] Error searching for read-only value for drop down: " +
                    e.getLocalizedMessage(), module);
            }

            if (gv == null) {
             
              gv = new GenericValue(entityPk);
             
                Debug.logWarning("[getReadOnlyValue] Skipping field \"" +
                    attributeName +
                    "\" because no entity was found for value \"" + fieldValue +
                    "\" using find definition \"" +
                    uiDisplayObject.getAttribEntityPkFindDef() + "\"", module);
            }

            return gv;
        }
    }
   
  /**
   * Add criteria to
   *
   * @param entityFindDef
   * @param entityDetailsVector
   * @param currentAttibuteName
   *
   * @return
   */
  public static boolean addSelectSearch(QueryInfo queryInfo, String displayObjectId, String entityName, String attributeName, String aliasName, EntityComparisonOperator searchOperator, Object searchValue)
  {
    try
    {
      GenericDelegator delegator = queryInfo.getDelegator();
      UIDisplayObject displayObject = new UIDisplayObject( displayObjectId, delegator );
      displayObject.loadAttributes();
     
      // Split the entity find definition into pieces.  Example:
      // * attribEntityFindDef:
      //     * sectionId:sectionId;partyId:"-1"
      // * Resulting find map pairs:
      //     * sectionId:43
      //     * partyId:-1
      // * Resulting find logic:
      //     * sectionId = 43 AND partyId = -1
     
      String findAttributeValue = "";
      List joinList  = new ArrayList();
      String joinEntity = "";
      HashMap conditionMap = new HashMap();
     
      String entityFindDef = displayObject.getAttribEntityPkFindDef();
     
      StringTokenizer tokSemicolon = new StringTokenizer(entityFindDef, ";");
     
      while (tokSemicolon.hasMoreTokens()) {
     
        String pair = tokSemicolon.nextToken();
        StringTokenizer tokColon = new StringTokenizer(pair, ":");
     
        if (tokColon.countTokens() != 2) {
          Debug.logWarning(
              "-->[UIUtility.decodeEntityFindDef] No colon found in '" +
              pair + "'" + "for entityFindDef" + entityFindDef, module);
               
          return false;
        } else {
     
          String findAttributeName = tokColon.nextToken();
          if ( findAttributeName.equals("#currentField"))
            findAttributeName = attributeName;
     
          //        String screenAttributeString = tokColon.nextToken();
          String attributeValueSource = tokColon.nextToken();
          if ( attributeValueSource.equals("#currentField"))
            attributeValueSource = attributeName;
         
          if ( attributeValueSource.indexOf("\"") > -1 )
          {
            attributeValueSource = attributeValueSource.substring(attributeValueSource.indexOf(
                      "\"") + 1, attributeValueSource.lastIndexOf("\""));
            conditionMap.put(findAttributeName, attributeValueSource);
          }
          else
          {
            StringTokenizer tokPeriod = new StringTokenizer(attributeValueSource,
                ".");
     
            String relatedEntity = "";
            if (tokPeriod.countTokens() == 1) {
              // There is no "." in the attribute string.  Assume we need to use the primary screen entity.
              relatedEntity = entityName;
            } else {
              // Need to get the entity specified before the "." in the attribute name string.
              relatedEntity = tokPeriod.nextToken();
              attributeValueSource = tokPeriod.nextToken();
            }
            if ( (joinEntity.length() > 0) && ( !joinEntity.equals(relatedEntity) ) )
            {
              Debug.logError("Invalid Join Condition, attempting to join lookup table to two different entities", module);
              return false;
            }
            joinEntity = relatedEntity;
     
            joinList.add(new ModelKeyMap(attributeValueSource, findAttributeName));
          }
         
        }
      }
     
      if( joinList.size() < 1)
      {
        Debug.logWarning("EntityFindDef has no join with primary tables", module);
        return false;
      }
     
      queryInfo.addJoin( joinEntity, joinEntity, displayObject.getAttribEntity(), aliasName, Boolean.valueOf(false), joinList );
     
      Iterator conditionIter = conditionMap.entrySet().iterator();
      while ( conditionIter.hasNext())
      {
        Map.Entry set = (Map.Entry) conditionIter.next();
        String fieldName = (String) set.getKey();
        String fieldValue = (String) set.getValue();
       
        queryInfo.addCondition( aliasName, "c" + aliasName + fieldName, fieldName, EntityOperator.EQUALS, fieldValue );
      }
     
      String listDisplayField = displayObject.getAttribEntityDisplayDef();
      if ( listDisplayField.indexOf(";") > 0)
        listDisplayField = listDisplayField.substring(listDisplayField.lastIndexOf(";") + 1);
       
      queryInfo.addCondition( aliasName, "c" + aliasName + listDisplayField, listDisplayField, searchOperator, searchValue)
     
      return true;
    } catch (GenericEntityException e)
    {
      Debug.logError("Unable to generate search on lookup table" + e.getMessage(), module);
      e.printStackTrace();
      return false;
    }
  }

}
TOP

Related Classes of com.sourcetap.sfa.ui.UIUtility

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