private TransformationRecord getTransforMationRecord(
      final SqlAspect sqlAspect, final EObject eObject, final char recordType) {
    if (sqlAspect instanceof SqlTransformationAspect) {
      switch (recordType) {
        case IndexConstants.RECORD_TYPE.SELECT_TRANSFORM:
          return new TransformationRecordImpl(
              (SqlTransformationAspect) sqlAspect, eObject, SqlTransformationAspect.Types.SELECT);
        case IndexConstants.RECORD_TYPE.INSERT_TRANSFORM:
          return new TransformationRecordImpl(
              (SqlTransformationAspect) sqlAspect, eObject, SqlTransformationAspect.Types.INSERT);
        case IndexConstants.RECORD_TYPE.UPDATE_TRANSFORM:
          return new TransformationRecordImpl(
              (SqlTransformationAspect) sqlAspect, eObject, SqlTransformationAspect.Types.UPDATE);
        case IndexConstants.RECORD_TYPE.DELETE_TRANSFORM:
          return new TransformationRecordImpl(
              (SqlTransformationAspect) sqlAspect, eObject, SqlTransformationAspect.Types.DELETE);
        case IndexConstants.RECORD_TYPE.PROC_TRANSFORM:
          return new TransformationRecordImpl(
              (SqlTransformationAspect) sqlAspect,
              eObject,
              SqlTransformationAspect.Types.PROCEDURE);
        case IndexConstants.RECORD_TYPE.MAPPING_TRANSFORM:
          return new TransformationRecordImpl(
              (SqlTransformationAspect) sqlAspect, eObject, SqlTransformationAspect.Types.MAPPING);
        default:
          throw new ModelerCoreRuntimeException(
              TransformationPlugin.Util.getString(
                  "TransformationMetadata.No_known_index_file_type_associated_with_the_recordType_1",
                  new Character(recordType))); // $NON-NLS-1$			
      }
    }

    return null;
  }
  public static QueryMetadataContext buildQueryMetadataContext(
      final EObject eObject, final boolean restrictSearch) {
    Collection resources = null;
    Container container = null;
    try {
      // assume model container...modler metadata is for workspace
      container = ModelerCore.getModelContainer();
      ModelWorkspace workspace = ModelerCore.getModelWorkspace();
      if (workspace.isOpen()) {
        resources = Arrays.asList(workspace.getEmfResources());
      } else {
        resources = container.getResources();
      }
    } catch (CoreException e) {
      TransformationPlugin.Util.log(e);
    }

    // find the resoucre for the eObject in the container
    Resource resource = ModelerCore.getModelEditor().findResource(container, eObject);
    // create a indexSelector for this resource and instantiate transformation validator
    ModelResourceIndexSelector selector = new ModelResourceIndexSelector(resource);
    QueryMetadataContext context = new QueryMetadataContext(selector);
    // set the resource scope (all model resources in open model projects)
    context.setResources(resources);
    // set the restrict search flag
    context.setRestrictedSearch(restrictSearch);
    return context;
  }
  /**
   * Find the EObject having the specified UUID using the ObjectManager for the lookup. If an
   * EObject with this UUID cannot be found then null is returned.
   */
  protected EObject lookupEObject(final String uuid) {
    CoreArgCheck.isNotEmpty(uuid);

    // Before searching by UUID make sure all resources associated with this QMI are loaded
    if (this.getResources() != null) {
      for (Iterator iter = this.getResources().iterator(); iter.hasNext(); ) {
        Resource r = (Resource) iter.next();
        if (!r.isLoaded()) {
          try {
            r.load(Collections.EMPTY_MAP);
          } catch (IOException e) {
            TransformationPlugin.Util.log(IStatus.ERROR, e.getLocalizedMessage());
          }
        }
      }
    }

    // Go to the Container ...
    EObject eObject = null;

    if (this.getContainer() != null) {
      eObject = (EObject) this.getContainer().getEObjectFinder().find(uuid);

      if (eObject != null) {
        // get the resource on the object
        Resource resource = eObject.eResource();
        // check if this is among the resources is scope for this QMI
        if (this.getResources() != null) {
          Container cntr = ModelerCore.getContainer(resource);
          // If the resource exists in the same Container as the one associated with this QMI
          // but the resource is not in the scope of resources then return null
          if (cntr == this.getContainer() && !this.getResources().contains(resource)) {
            return null;
          }
        }
      }
      return eObject;
    }

    // We are in a non-container environment
    Iterator rsrs = this.getResources().iterator();
    while (rsrs.hasNext()) {
      Resource rsrc = (Resource) rsrs.next();
      if (rsrc instanceof MMXmiResource) {
        eObject = ((MMXmiResource) rsrc).getEObject(uuid);
        if (eObject != null) {
          return eObject;
        }
      } else if (rsrc instanceof XSDResourceImpl) {
        eObject = ((XSDResourceImpl) rsrc).getEObject(uuid);
        if (eObject != null) {
          return eObject;
        }
      }
    }

    return eObject;
  }
 /**
  * Return a reference to a {@link QueryMetadataInterface} implementation that for the given
  * eObject , its resourceand the resources that depend ont it. This assumes the Eobject is in a
  * modelContainer, should be used only for workspace validation.
  *
  * @param eObject The eObject for which metadata instance is returned
  * @param restrictSearch A boolean indicating if the search needs to be restricted to model
  *     imports or if the whole workspace needs to be searched
  * @return the QueryMetadataInterface implementation; never null
  */
 public QueryMetadataInterface getModelerMetadata(
     final EObject eObject, final boolean restrictSearch) {
   CoreArgCheck.isNotNull(eObject);
   QueryMetadataContext context = buildQueryMetadataContext(eObject, restrictSearch);
   Container container = null;
   try {
     container = ModelerCore.getModelContainer();
   } catch (CoreException e) {
     TransformationPlugin.Util.log(e);
   }
   return getModelerMetadata(context, container);
 }
  protected Collection findSystemMetadataRecords(
      final char recordType, final String entityName, final boolean isPartialName)
      throws Exception {
    Collection eObjects = new ArrayList();

    List tokens = CoreStringUtil.getTokens(entityName, DELIMITER_STRING);
    String firstSegment = (String) tokens.get(0);

    if (!isSystemModelName(firstSegment)) {
      return eObjects;
    }

    Object value = systemModelByNameMap.get(firstSegment.toUpperCase());

    // If the entity name is the name of one of our system models, we need to verify
    // that no model in the workspace
    // we match a System resource in the external container make sure there is
    // no workspace resource we should choose instead
    if (value != null && value instanceof EmfResource) {
      ObjectID eResourceUuid = ((EmfResource) value).getUuid();
      Resource wsEResource =
          this.getContainer().getResourceFinder().findByUUID(eResourceUuid, false);
      if (wsEResource != null) {
        value = wsEResource;
      }
    }

    Collection entities = findEntitiesByName(value, entityName, recordType, isPartialName);
    for (Iterator iter = entities.iterator(); iter.hasNext(); ) {
      EObject eObj = (EObject) iter.next();
      if (eObj != null && (eObj.eContainer() != null || eObj.eResource() != null)) {
        eObjects.add(eObj);
      }
    }
    Collection records = createMetadataRecords(recordType, eObjects);
    if (ModelerCore.DEBUG_QUERY_RESOLUTION) {
      final Object[] params = new Object[] {Integer.toString(records.size()), entityName};
      final String debugMsg =
          TransformationPlugin.Util.getString(
              "ModelerMetadata.Found_{0}_records_for_the_entity_{1}_1", params); // $NON-NLS-1$
      ModelerCore.Util.log(IStatus.INFO, debugMsg);
    }
    return records;
  }
  private Collection getTransforMationsForTable(
      final Object container,
      final String entityName,
      final char recordType,
      final boolean isPartialName) {
    AbstractNameFinder finder = null;
    switch (recordType) {
      case IndexConstants.RECORD_TYPE.SELECT_TRANSFORM:
      case IndexConstants.RECORD_TYPE.INSERT_TRANSFORM:
      case IndexConstants.RECORD_TYPE.UPDATE_TRANSFORM:
      case IndexConstants.RECORD_TYPE.DELETE_TRANSFORM:
      case IndexConstants.RECORD_TYPE.MAPPING_TRANSFORM:
        finder = new TableNameFinder(entityName, isPartialName);
        break;
      case IndexConstants.RECORD_TYPE.PROC_TRANSFORM:
        finder = new ProcedureNameFinder(entityName, isPartialName);
        break;
      default:
        throw new ModelerCoreRuntimeException(
            TransformationPlugin.Util.getString(
                "TransformationMetadata.No_known_index_file_type_associated_with_the_recordType_1",
                new Character(recordType))); // $NON-NLS-1$		
    }

    executeVisitor(container, finder, ModelVisitorProcessor.DEPTH_INFINITE);
    Collection matches = finder.getMatchingEObjects();
    Collection transforms = new ArrayList(matches.size());
    for (Iterator targetIter = matches.iterator(); targetIter.hasNext(); ) {
      EObject targetObj = (EObject) targetIter.next();
      if (org.teiid.designer.core.metamodel.aspect.sql.SqlAspectHelper.isValidTransformationTarget(
          targetObj)) {
        EObject mappinRoot = TransformationHelper.getMappingRoot(targetObj);
        transforms.add(mappinRoot);
      }
    }

    return transforms;
  }
  private Collection findEntitiesByName(
      final Object container,
      final String entityName,
      final char recordType,
      final boolean isPartialName) {
    CoreArgCheck.isNotEmpty(entityName);

    AbstractNameFinder finder = null;
    switch (recordType) {
      case IndexConstants.RECORD_TYPE.MODEL:
        finder = new ModelNameFinder(entityName, isPartialName);
        break;
      case IndexConstants.RECORD_TYPE.TABLE:
        finder = new TableNameFinder(entityName, isPartialName);
        break;
      case IndexConstants.RECORD_TYPE.CALLABLE:
        finder = new ProcedureNameFinder(entityName, isPartialName);
        break;
      case IndexConstants.RECORD_TYPE.CALLABLE_PARAMETER:
      case IndexConstants.RECORD_TYPE.COLUMN:
        finder = new ColumnNameFinder(entityName, isPartialName);
        break;
      case IndexConstants.RECORD_TYPE.RESULT_SET:
      case IndexConstants.RECORD_TYPE.INDEX:
      case IndexConstants.RECORD_TYPE.ACCESS_PATTERN:
      case IndexConstants.RECORD_TYPE.PRIMARY_KEY:
      case IndexConstants.RECORD_TYPE.UNIQUE_KEY:
      case IndexConstants.RECORD_TYPE.FOREIGN_KEY:
        finder = new ColumnNameFinder(entityName, isPartialName);
        break;
      case IndexConstants.RECORD_TYPE.SELECT_TRANSFORM:
      case IndexConstants.RECORD_TYPE.INSERT_TRANSFORM:
      case IndexConstants.RECORD_TYPE.UPDATE_TRANSFORM:
      case IndexConstants.RECORD_TYPE.DELETE_TRANSFORM:
      case IndexConstants.RECORD_TYPE.PROC_TRANSFORM:
      case IndexConstants.RECORD_TYPE.MAPPING_TRANSFORM:
        return getTransforMationsForTable(container, entityName, recordType, isPartialName);
      case IndexConstants.RECORD_TYPE.DATATYPE:
        // case IndexConstants.RECORD_TYPE.DATATYPE_ELEMENT:
        // case IndexConstants.RECORD_TYPE.DATATYPE_FACET:
        finder = new DatatypeNameFinder(entityName, isPartialName);
        break;
      case IndexConstants.RECORD_TYPE.VDB_ARCHIVE:
      case IndexConstants.RECORD_TYPE.ANNOTATION:
      case IndexConstants.RECORD_TYPE.PROPERTY:
      case IndexConstants.RECORD_TYPE.JOIN_DESCRIPTOR:
        break;
      default:
        throw new ModelerCoreRuntimeException(
            TransformationPlugin.Util.getString(
                "TransformationMetadata.No_known_index_file_type_associated_with_the_recordType_1",
                new Character(recordType))); // $NON-NLS-1$
    }

    if (finder != null) {
      executeVisitor(container, finder, ModelVisitorProcessor.DEPTH_INFINITE);
      return finder.getMatchingEObjects();
    }

    return Collections.EMPTY_LIST;
  }
  /**
   * Create the metadataRecord for the given EObject.
   *
   * @param recordType The record type for the expected MetadataRecord
   * @param eObject The EObject whose record is returned
   * @return The metadataRecord for the eObject
   * @throws Exception
   */
  protected MetadataRecord createMetadataRecord(final char recordType, final EObject eObject)
      throws Exception {
    MetadataRecord record = null;
    SqlAspect sqlAspect = AspectManager.getSqlAspect(eObject);
    if (!sqlAspect.isQueryable(eObject)) {
      return null;
    }
    switch (recordType) {
      case IndexConstants.RECORD_TYPE.MODEL:
        if (sqlAspect instanceof SqlModelAspect) {
          record = new ModelRecordImpl((SqlModelAspect) sqlAspect, eObject);
        }
        break;
      case IndexConstants.RECORD_TYPE.TABLE:
        if (sqlAspect instanceof SqlTableAspect) {
          record = new TableRecordImpl((SqlTableAspect) sqlAspect, eObject);
        }
        break;
      case IndexConstants.RECORD_TYPE.CALLABLE:
        if (sqlAspect instanceof SqlProcedureAspect) {
          record = new ProcedureRecordImpl((SqlProcedureAspect) sqlAspect, eObject);
        }
        break;
      case IndexConstants.RECORD_TYPE.CALLABLE_PARAMETER:
        if (sqlAspect instanceof SqlProcedureParameterAspect) {
          record =
              new ProcedureParameterRecordImpl((SqlProcedureParameterAspect) sqlAspect, eObject);
        }
        break;
      case IndexConstants.RECORD_TYPE.COLUMN:
        if (sqlAspect instanceof SqlColumnAspect) {
          record = new ColumnRecordImpl((SqlColumnAspect) sqlAspect, eObject);
        }
        break;
      case IndexConstants.RECORD_TYPE.RESULT_SET:
      case IndexConstants.RECORD_TYPE.INDEX:
      case IndexConstants.RECORD_TYPE.ACCESS_PATTERN:
      case IndexConstants.RECORD_TYPE.PRIMARY_KEY:
      case IndexConstants.RECORD_TYPE.UNIQUE_KEY:
        if (sqlAspect instanceof SqlColumnSetAspect) {
          record = new ColumnSetRecordImpl((SqlColumnSetAspect) sqlAspect, eObject, recordType);
        }
        break;
      case IndexConstants.RECORD_TYPE.FOREIGN_KEY:
        if (sqlAspect instanceof SqlForeignKeyAspect) {
          record = new ForeignKeyRecordImpl((SqlForeignKeyAspect) sqlAspect, eObject);
        }
        break;
      case IndexConstants.RECORD_TYPE.SELECT_TRANSFORM:
      case IndexConstants.RECORD_TYPE.INSERT_TRANSFORM:
      case IndexConstants.RECORD_TYPE.UPDATE_TRANSFORM:
      case IndexConstants.RECORD_TYPE.DELETE_TRANSFORM:
      case IndexConstants.RECORD_TYPE.PROC_TRANSFORM:
      case IndexConstants.RECORD_TYPE.MAPPING_TRANSFORM:
        record = getTransforMationRecord(sqlAspect, eObject, recordType);
        break;
      case IndexConstants.RECORD_TYPE.DATATYPE:
        if (sqlAspect instanceof SqlDatatypeAspect) {
          record = new DatatypeRecordImpl((SqlDatatypeAspect) sqlAspect, eObject);
        }
        break;
      case IndexConstants.RECORD_TYPE.VDB_ARCHIVE:
        if (sqlAspect instanceof SqlVdbAspect) {
          record = new VdbRecordImpl((SqlVdbAspect) sqlAspect, eObject);
        }
        break;
      case IndexConstants.RECORD_TYPE.ANNOTATION:
        if (sqlAspect instanceof SqlAnnotationAspect) {
          record = new AnnotationRecordImpl((SqlAnnotationAspect) sqlAspect, eObject);
        }
        break;
      case IndexConstants.RECORD_TYPE.PROPERTY:
      case IndexConstants.RECORD_TYPE.JOIN_DESCRIPTOR:
        return null;
      default:
        throw new TeiidDesignerException(
            TransformationPlugin.Util.getString(
                "TransformationMetadata.No_known_index_file_type_associated_with_the_recordType_1",
                new Character(recordType))); // $NON-NLS-1$
    }

    return record;
  }
  /**
   * Return all metadata records for the entity that matches the given entity name and is of the
   * type specified by the record type.
   *
   * @param recordType
   * @param entityName the name to match
   * @param isPartialName true if the entity name is a partially qualified
   * @throws Exception
   */
  @Override
  protected Collection findMetadataRecords(
      final char recordType, final String entityName, final boolean isPartialName)
      throws Exception {

    Collection eObjects = new ArrayList();

    String uuid = null;
    if (CoreStringUtil.startsWithIgnoreCase(entityName, UUID.PROTOCOL)) {
      uuid = entityName.toLowerCase();
    } else {
      String shortName = getShortElementName(entityName);
      if (CoreStringUtil.startsWithIgnoreCase(shortName, UUID.PROTOCOL)) {
        uuid = shortName.toLowerCase();
      }
    }
    // if it the element is a UUID
    if (uuid != null) {
      EObject eObj = lookupEObject(uuid);
      if (eObj != null) {
        // 12/31/03 (LLP) : fix for 10825. Prevent NPE when column has been deleted.
        if (eObj.eContainer() != null || eObj.eResource() != null) {
          eObjects.add(eObj);
        }
      }
    }

    // no eObjects found, could be cause the name is a "user string" or Eobject for UUID could
    // not be found in any of open resources
    if (eObjects.isEmpty()) {

      Collection sysObjects = findSystemMetadataRecords(recordType, entityName, isPartialName);

      if (!sysObjects.isEmpty()) {
        return sysObjects;
      }

      // model name is first token
      List tokens = CoreStringUtil.getTokens(entityName, DELIMITER_STRING);
      String firstSegment = (String) tokens.get(0);

      // check if a modelResource exists on the index selector,
      // if so there are indexes to be queried
      if (eObjects.isEmpty() && getIndexSelector() instanceof ModelResourceIndexSelector) {
        if (ModelerCore.DEBUG_QUERY_RESOLUTION) {
          final String debugMsg =
              TransformationPlugin.Util.getString(
                  "ModelerMetadata.Resolving_entity_{0}_using_index_files_1",
                  entityName); //$NON-NLS-1$
          TransformationPlugin.Util.log(IStatus.INFO, debugMsg);
        }
        ModelResourceIndexSelector resourceSelector =
            (ModelResourceIndexSelector) getIndexSelector();
        Object modelResource =
            ModelerCore.getModelWorkspace().findModelResource(resourceSelector.getResource());
        if (modelResource != null) {
          // look up the index files instead of navigating the resources.
          Collection records = super.findMetadataRecords(recordType, entityName, isPartialName);
          if (!super.getContext().isRestrictedSearch() && records.isEmpty()) {
            // if cant find query all files, there may have been no imports added
            // some one is trying to resolved a query containing groups for which there are no
            // imports
            IndexSelector workspaceSelector = new ModelWorkspaceIndexSelector();
            super.getContext().setIndexSelector(workspaceSelector);
            // look up the index files for the whole workspace instead of looking at imported
            // resources
            records = super.findMetadataRecords(recordType, entityName, isPartialName);
            // set back the resource selector for subsequent metadata lookup
            super.getContext().setIndexSelector(resourceSelector);
          }
          if (ModelerCore.DEBUG_QUERY_RESOLUTION) {
            final Object[] params = new Object[] {Integer.toString(records.size()), entityName};
            final String debugMsg =
                TransformationPlugin.Util.getString(
                    "ModelerMetadata.Found_{0}_records_for_the_entity_{1}_1",
                    params); //$NON-NLS-1$
            ModelerCore.Util.log(IStatus.INFO, debugMsg);
          }
          if (!records.isEmpty()) {
            return records;
          }
          if (uuid != null) {
            ResourceSet[] resourceSets = this.getContainer().getExternalResourceSets();
            for (int i = 0; i < resourceSets.length; i++) {
              ResourceSet currentResourceSet = resourceSets[i];
              if (currentResourceSet != null && currentResourceSet instanceof Container) {
                Container externalContainer = (Container) currentResourceSet;
                EObject externalEObj = (EObject) externalContainer.getEObjectFinder().find(uuid);
                if (externalEObj != null) {
                  // 12/31/03 (LLP) : fix for 10825. Prevent NPE when column has been deleted.
                  if (externalEObj.eContainer() != null || externalEObj.eResource() != null) {
                    eObjects.add(externalEObj);
                  }
                }
              }
            }
          }
        }
      }

      if (ModelerCore.DEBUG_QUERY_RESOLUTION) {
        final String debugMsg =
            TransformationPlugin.Util.getString(
                "ModelerMetadata.Resolving_entity_{0}_by_navigating_the_workspace_1",
                entityName); //$NON-NLS-1$
        TransformationPlugin.Util.log(IStatus.INFO, debugMsg);
      }

      // Look up the EObject by path assuming the first path segement
      // is the model name and the remaining segments are the path within
      // the model
      // find all resources for model name
      Iterator resourceIter = this.findResourcesByName(firstSegment).iterator();
      while (resourceIter.hasNext()) {
        Resource resource = (Resource) resourceIter.next();
        // find EObjects in each resource
        if (resource != null) {
          Collection entities = findEntitiesByName(resource, entityName, recordType, isPartialName);
          for (Iterator iter = entities.iterator(); iter.hasNext(); ) {
            EObject eObj = (EObject) iter.next();
            if (eObj != null && (eObj.eContainer() != null || eObj.eResource() != null)) {
              eObjects.add(eObj);
            }
          }
        }
      }
    }

    // find metadata records for the Eobjects collected
    if (!eObjects.isEmpty()) {
      Collection records = createMetadataRecords(recordType, eObjects);
      if (ModelerCore.DEBUG_QUERY_RESOLUTION) {
        final Object[] params = new Object[] {Integer.toString(records.size()), entityName};
        final String debugMsg =
            TransformationPlugin.Util.getString(
                "ModelerMetadata.Found_{0}_records_for_the_entity_{1}_1", params); // $NON-NLS-1$
        ModelerCore.Util.log(IStatus.INFO, debugMsg);
      }
      return records;
    }
    return Collections.EMPTY_LIST;
  }