/**
  * Used to find a resource using a relative URI referenced to a known resource
  *
  * @see
  *     org.teiid.designer.core.container.ResourceFinder#findByWorkspaceUri(org.eclipse.emf.common.util.URI,
  *     org.eclipse.emf.ecore.resource.Resource)
  * @since 5.0.2
  */
 @Override
 public Resource findByWorkspaceUri(final URI theRelativeUri, final Resource knownResource) {
   try {
     // Defect 23396 - an NPE was thrown here because a relativeUri was provide (i.e.
     // BooksDatatypes.xsd) which resulted
     // in a NULL model Resource or null corresponding resource.
     ModelResource mr = ModelerCore.getModelEditor().findModelResource(knownResource);
     if (mr != null && mr.getCorrespondingResource() != null) {
       IPath thePath =
           mr.getCorrespondingResource()
               .getFullPath()
               .removeLastSegments(1)
               .append(theRelativeUri.toString());
       IResource iResrc = ModelerCore.getWorkspace().getRoot().findMember(thePath);
       if (iResrc instanceof IFile) {
         ModelResource modelResource =
             ModelerCore.getModelEditor().findModelResource((IFile) iResrc);
         if (modelResource != null) {
           return modelResource.getEmfResource();
         }
       }
     }
   } catch (ModelWorkspaceException theException) {
     ModelerCore.Util.log(theException);
   }
   return null;
 }
  /**
   * @see
   *     org.teiid.designer.core.container.ResourceFinder#findMissingImportLocations(org.eclipse.emf.ecore.resource.Resource)
   * @since 5.0.2
   */
  @Override
  public String[] findMissingImportLocations(final Resource theResource) {
    final Collection result = new HashSet();
    if (theResource != null && theResource instanceof MMXmiResource) {

      // just get the Resolved external resources (i.e. desired imports)
      Collection unresolvedResources = getResolvedExternalResources(theResource);

      // For each unresolved resource, create a location and check existing imports for this
      // location.
      for (Iterator iter = unresolvedResources.iterator(); iter.hasNext(); ) {
        Resource nextRes = (Resource) iter.next();

        String location =
            ModelerCore.getModelEditor().createModelLocation((MMXmiResource) theResource, nextRes);

        if (location != null) {
          ModelImport existingImport =
              ModelerCore.getModelEditor()
                  .getExistingModelImportForLocation((MMXmiResource) theResource, location);
          // If no existing import, add location to result
          if (existingImport == null) {
            result.add(location);
          }
        }
      }
    }
    return (String[]) result.toArray(new String[result.size()]);
  }
  public List getToolTipStrings() {
    List returnList = new ArrayList();
    if (isOnCoarseMappingDiagram()) {
      if (getExtent().getMappingReference() instanceof StagingTable) {
        String stName = ModelerCore.getModelEditor().getName(getExtent().getMappingReference());
        returnList.add(sStagingTablePrefix + stName);
      } else if (getExtent().getMappingReference() != null) {
        String stName = ModelerCore.getModelEditor().getName(getExtent().getMappingReference());
        returnList.add(sMappingClassPrefix + stName);
      } else {
        // handle Unmapped extents
        returnList.add("(unmapped)"); // $NON-NLS-1$
      }
      if (getExtent().getDocumentNodeReference() != null) {
        addToolTipStringsForLocation(returnList, getExtent());
      }
    } else {
      if (getExtent() != null) {
        if (getExtent().getMappingReference() instanceof StagingTable) {
          String stName = ModelerCore.getModelEditor().getName(getExtent().getMappingReference());
          returnList.add(sStagingTablePrefix + stName);
        } else {
          String stName = ModelerCore.getModelEditor().getName(super.getModelObject());
          returnList.add(sNamePrefix + stName);
          String sType =
              ModelerCore.getMetamodelRegistry().getMetaClassLabel(super.getModelObject().eClass());
          returnList.add(sTypePrefix + sType);

          returnList.add(sPathInDocumentPrefix + getExtent().getPathToDocumentRoot());

          String sComp = getExtent().getXsdQualifiedName();
          if (sComp == null || sComp.trim().length() == 0) {
            sComp = sNone;
            returnList.add(sXsdComponentPrefix + sComp);
          } else {
            returnList.add(sXsdComponentPrefix);
            String sNamespace = getExtent().getXsdTargetNamespace();
            if (sNamespace == null || sNamespace.trim().length() == 0) sNamespace = sNone;
            returnList.add(threeSpaces + sTargetNamespace + sNamespace);
            returnList.add(threeSpaces + sQualifiedName + sComp);
          }

          stName = "" + getExtent().isMappingRequired(); // $NON-NLS-1$
          returnList.add(sMappingRequiredPrefix + stName);
        }
      }
    }
    return returnList;
  }
  /**
   * Creates a {@link MappingRoot} having the specified <code>MappingClass</code> as it's input.
   *
   * @param theMappingClass the <code>MappingClass</code> used to create the mapping root
   * @return the index in the <code>mappingRoots</code> list of the new root
   * @throws IllegalArgumentException if input parameter is <code>null</code>
   */
  public EObject createTreeMappingRoot(MappingClass theMappingClass) {
    // startTracking("createTreeMappingRoot(GENERATING)"); //$NON-NLS-1$

    CoreArgCheck.isNotNull(theMappingClass);
    if (mappingLocator.hasTreeRoot(theMappingClass)) {
      return mappingLocator.getMappingRoot(theMappingClass);
    }

    TreeMappingRoot newRoot = null;
    try {
      // Defect 18433 - BML 8/31/05 - Changed call to create tree mapping root using a new
      // utility method that correctly adds it to the model (via addValue()) and also performs
      // additional work (i.e.adding nested Sql Helpers.
      newRoot =
          ModelResourceContainerFactory.createNewTreeMappingRoot(this.root, this.root.eResource());

      // Now add the mapping class to the Inputs list of the tree mapping root
      ModelerCore.getModelEditor().addValue(newRoot, theMappingClass, newRoot.getInputs());

    } catch (Exception theException) {
      Util.log(
          IStatus.ERROR,
          theException,
          Util.getString(
              PREFIX + "createMappingRootProblem", // $NON-NLS-1$
              new Object[] {root, theMappingClass}));
    }

    // stopTracking("createTreeMappingRoot(GENERATING)"); //$NON-NLS-1$
    return newRoot;
  }
  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;
  }
 public static void removeFacet(XSDSimpleTypeDefinition type, XSDConstrainingFacet facet) {
   try {
     ModelerCore.getModelEditor().removeValue(type, facet, type.getFacetContents());
   } catch (ModelerCoreException err) {
     ModelerXsdUiConstants.Util.log(err);
   } // endtry
 }
 public static void setEnterpriseFacetValue(XSDSimpleTypeDefinition type, FacetValue newValue) {
   if (newValue.value != null) {
     // set new enterprise info:
     EnterpriseDatatypeInfo edi =
         ModelerCore.getWorkspaceDatatypeManager().getEnterpriseDatatypeInfo(type);
     if (edi == null) {
       edi = new EnterpriseDatatypeInfo();
     } // endif
     edi.setRuntimeTypeFixed(new Boolean(newValue.isFixedLocal));
     edi.setRuntimeType((String) newValue.value);
     ModelEditorImpl.fillWithDefaultValues(edi, type);
     ModelerCore.getModelEditor().setEnterpriseDatatypePropertyValue(type, edi);
   } else {
     // need to unset:
     ModelerCore.getModelEditor().unsetEnterpriseDatatypePropertyValue(type);
   } // endif
 }
  private String getUndoText(EObject[] selectedObjects) {

    String description = null;
    if (selectedObjects.length == 1) {
      EObject obj = selectedObjects[0];
      String path = ModelerCore.getModelEditor().getModelRelativePath(obj).toString();
      description = UiConstants.Util.getString(UNDO_TEXT, path);
    } else {
      description = UiConstants.Util.getString(PLURAL_UNDO_TEXT, selectedObjects.length);
    }
    return description;
  }
  /**
   * @see
   *     org.teiid.designer.core.validation.ObjectValidationRule#validate(org.eclipse.emf.ecore.EObject,
   *     org.teiid.designer.core.validation.ValidationContext)
   * @since 4.2
   */
  @Override
  public void validate(final EObject eObject, final ValidationContext context) {
    CoreArgCheck.isNotNull(context);
    CoreArgCheck.isNotNull(eObject);

    // get uniqueness preference status
    final int status =
        context.getPreferenceStatus(ValidationPreferences.EOBJECT_UUID_UNIQUENESS, IStatus.ERROR);
    if (status == IStatus.OK) {
      return;
    }

    // if the eObject is a model annotation then
    // is already being validation by ModelAnnoattionUuidRule
    if (eObject instanceof ModelAnnotation) {
      return;
    }

    final ModelEditor editor = ModelerCore.getModelEditor();
    final String uuidString = ModelerCore.getObjectIdString(eObject);
    if (uuidString == null) {
      final String pathInModel = editor.getModelRelativePathIncludingModel(eObject).toString();
      final ValidationResult result = new ValidationResultImpl(eObject);
      // create validation problem and add it to the result
      final ValidationProblem problem =
          new ValidationProblemImpl(
              0,
              IStatus.ERROR,
              ModelerCore.Util.getString("EObjectUuidRule.0", pathInModel)); // $NON-NLS-1$
      problem.setHasPreference(context.hasPreferences());
      result.addProblem(problem);
      context.addResult(result);
    } else {
      boolean isDuplicate = context.containsUuid(uuidString);
      if (isDuplicate) {
        final String pathInModel = editor.getModelRelativePathIncludingModel(eObject).toString();
        final ValidationResult result = new ValidationResultImpl(eObject);
        String modelName = editor.getModelName(eObject);
        // create validation problem and addit to the result
        final ValidationProblem problem =
            new ValidationProblemImpl(
                0,
                status,
                ModelerCore.Util.getString(
                    "EObjectUuidRule.1", pathInModel, uuidString, modelName)); // $NON-NLS-1$
        problem.setHasPreference(context.hasPreferences());
        result.addProblem(problem);
        context.addResult(result);
      } else {
        context.addUuidToContext(uuidString);
      }
    }
  }
  public static XSDConstrainingFacet addOrSetFacetValue(
      XSDSimpleTypeDefinition type, String facetName, FacetValue fv) {
    XSDConstrainingFacet workFacet = fv.facet;
    // do we need to add?
    if (fv.facet == null || fv.facet.getContainer() != type) {
      // need to add to this type:
      boolean inclusiveness = false;
      if (fv.value instanceof InclusiveInteger) {
        inclusiveness = ((InclusiveInteger) fv.value).isInclusive;
      } // endif

      // remove any facets with opposite inclusiveness:
      if (facetName == FAKE_FACET_MAXIMUM || facetName == FAKE_FACET_MINIMUM) {
        // go ahead and remove:
        removeFacet(type, facetName);
      } // endif -- using fake facets?

      workFacet = createFacet(facetName, inclusiveness);

      try {
        ModelerCore.getModelEditor().addValue(type, workFacet, type.getFacetContents());
      } catch (ModelerCoreException err) {
        ModelerXsdUiConstants.Util.log(err);
      } // endtry
    } // endif

    // set main value:
    if (!FormUtil.safeEquals(fv.value, getMainFacetValue(workFacet))) {
      // only set if changed:
      workFacet = setMainFacetValue(type, workFacet, fv.value);
      // in case this is a bounds facet and we swapped them out:
      fv.facet = workFacet;
    } // endif

    // set description:
    String existingDesc = ModelObjectUtilities.getDescription(workFacet);
    if (fv.description != null) {
      // new not null:
      if (!fv.description.equals(existingDesc)) {
        // description changed to a nonnull value:
        ModelObjectUtilities.setDescription(workFacet, fv.description, type);
      } // endif -- different
    } else if (existingDesc != null && existingDesc.length() > 0) {
      // new null, old not null:
      ModelObjectUtilities.setDescription(workFacet, " ", type); // $NON-NLS-1$
    } // endif

    // Lastly, set fixed if applicable:
    setFixed(workFacet, fv.isFixedLocal);

    return workFacet;
  }
  @Override
  protected IProgressMonitor executeCommand(final RefactorCommand command) {
    IProgressMonitor monitor = super.executeCommand(command);

    try {
      // Save refactored resource
      final ModelEditor editor = ModelerCore.getModelEditor();

      // defect 16527 - check that a resource is a file before casting
      IResource res = this.dest.findMember(MoveRefactorAction.this.resSelectedResource.getName());
      if (res instanceof IFile) {
        final IFile file = (IFile) res;
        ModelResource model = editor.findModelResource(file);
        if (model != null) {
          if (model.getEmfResource().isModified()) {
            // If an editor is open, call doSave on it, else tell the model to save
            org.teiid.designer.ui.editors.ModelEditor openEditor =
                ModelEditorManager.getModelEditorForFile(file, false);
            if (openEditor != null) {
              openEditor.doSave(monitor);
            } else {
              model.save(monitor, true);
            }
          }
        }
      } // endif -- move was on a file

      // Save modified dependent resources
      for (final Iterator iter = ((ResourceMoveCommand) command).getDependentResources().iterator();
          iter.hasNext(); ) {
        IFile file = (IFile) iter.next();
        ModelResource model = editor.findModelResource(file);
        if (model != null) {
          if (model.getEmfResource().isModified() && !model.isReadOnly()) {
            // If an editor is open, call doSave on it, else tell the model to save
            org.teiid.designer.ui.editors.ModelEditor openEditor =
                ModelEditorManager.getModelEditorForFile(file, false);
            if (openEditor != null) {
              openEditor.doSave(monitor);
            } else {
              model.save(monitor, true);
            }
          }
        }
      }
    } catch (final ModelWorkspaceException err) {
      ModelerCore.Util.log(err);
    }

    return monitor;
  }
 /* (non-Javadoc)
  * @See org.teiid.designer.core.workspace.ModelWorkspace#findModelResource(org.eclipse.emf.ecore.EObject)
  */
 @Override
 public ModelResource findModelResource(final EObject eObject) {
   CoreArgCheck.isNotNull(eObject);
   try {
     final Container container = ModelerCore.getModelContainer();
     Resource resource = ModelerCore.getModelEditor().findResource(container, eObject, false);
     if (resource != null) {
       return findModelResource(resource);
     }
   } catch (CoreException err) {
     ModelerCore.Util.log(err);
   }
   return null;
 }
 /**
  * Determine if the source Groups have valid resources. If a model is removed the resource will
  * not be found, thus invalid resource.
  *
  * @return 'true' if the source groups are valid, 'false' if not.
  */
 public boolean areSrcGroupMdlResourcesValid() {
   boolean isValid = true;
   if (this.sourceGroups == null || this.sourceGroups.isEmpty()) {
     isValid = false;
   } else {
     Iterator iter = this.sourceGroups.iterator();
     while (iter.hasNext()) {
       EObject sourceGrp = (EObject) iter.next();
       ModelResource mdlRsrc = ModelerCore.getModelEditor().findModelResource(sourceGrp);
       if (mdlRsrc == null || !mdlRsrc.exists()) {
         isValid = false;
         break;
       }
     }
   }
   return isValid;
 }
  /**
   * @see
   *     org.teiid.designer.core.validation.ObjectValidationRule#validate(org.eclipse.emf.ecore.EObject,
   *     org.teiid.designer.core.validation.ValidationContext)
   * @since 4.2
   */
  @Override
  public void validate(final EObject eObject, final ValidationContext context) {
    CoreArgCheck.isNotNull(context);
    CoreArgCheck.isInstanceOf(ModelAnnotation.class, eObject);

    final ModelEditor editor = ModelerCore.getModelEditor();
    String uuidString = ModelerCore.getObjectIdString(eObject);
    if (uuidString == null) {
      final String pathInModel = editor.getModelRelativePathIncludingModel(eObject).toString();
      final ValidationResult result = new ValidationResultImpl(eObject);
      // create validation problem and add it to the result
      final ValidationProblem problem =
          new ValidationProblemImpl(
              0,
              IStatus.ERROR,
              ModelerCore.Util.getString("ModelAnnotationUuidRule.0", pathInModel)); // $NON-NLS-1$
      result.addProblem(problem);
      context.addResult(result);
    } else {
      boolean isDuplicate = context.containsUuid(uuidString);
      if (isDuplicate) {
        final String pathInModel = editor.getModelRelativePathIncludingModel(eObject).toString();
        final ValidationResult result = new ValidationResultImpl(eObject);
        String modelName = editor.getModelName(eObject);
        // create validation problem and addit to the result
        final ValidationProblem problem =
            new ValidationProblemImpl(
                0,
                IStatus.ERROR,
                ModelerCore.Util.getString(
                    "ModelAnnotationUuidRule.1",
                    pathInModel,
                    uuidString,
                    modelName)); //$NON-NLS-1$
        result.addProblem(problem);
        context.addResult(result);
      } else {
        context.addUuidToContext(uuidString);
      }
    }
  }
  /**
   * @param location the XSDSchema object to add this type to.
   * @param typeName the name to give the newly created type.
   * @param baseType (optional) if not null, use this type as the base type of the new type.
   * @return
   */
  public static XSDSimpleTypeDefinition createAtomicSimpleTypeDefinintion(
      XSDSchema location, String typeName, XSDSimpleTypeDefinition baseType) {
    XSDSimpleTypeDefinition std =
        (XSDSimpleTypeDefinition)
            XSDFactory.eINSTANCE.create(XSDPackage.eINSTANCE.getXSDSimpleTypeDefinition());
    std.setName(typeName);
    // defect 18444 - make sure things are wrapped in transactions
    try {
      ModelerCore.getModelEditor().addValue(location, std, location.getContents());

      if (baseType != null) {
        ModelerCore.getDatatypeManager(std).setBasetypeDefinition(std, baseType);
      } else {
        XSDSimpleTypeDefinition defaultBaseType = getDefaultBaseType();
        ModelerCore.getDatatypeManager(std).setBasetypeDefinition(std, defaultBaseType);
      } // endif
    } catch (ModelerCoreException ex) {
      ModelerXsdUiConstants.Util.log(ex);
    } // endtry

    return std;
  }
  /**
   * @param eObjectList
   * @return list of rest procedures
   */
  private static List<RestProcedure> findRestProcedures(ModelResource modelResource)
      throws Exception {
    List<RestProcedure> restfulProcedureArray = new ArrayList<RestProcedure>();
    Collection<EObject> eObjectList = modelResource.getEObjects();
    for (EObject eObject : eObjectList) {
      if (SqlAspectHelper.isProcedure(eObject)) {
        IPath path = ModelerCore.getModelEditor().getModelRelativePathIncludingModel(eObject);
        final StringBuffer sb = new StringBuffer();
        final String[] segments = path.segments();
        for (int i = 0; i < segments.length; i++) {
          if (i != 0) {
            sb.append('.');
          }
          final String segment = segments[i];
          sb.append(segment);
        }
        String fullName = sb.toString();
        String name = ((ProcedureImpl) eObject).getName();
        createRestProcedureCollection((Procedure) eObject, name, fullName, restfulProcedureArray);
      }
    }

    return restfulProcedureArray;
  }
  @Override
  protected void doRun() {
    if (descriptor != null) {

      Shell shell = super.getPlugin().getWorkbench().getActiveWorkbenchWindow().getShell();
      ModelResource modelResource = null;
      boolean continuing = true;
      try {
        modelResource = ModelerCore.getModelEditor().findModelResource(sibling);
      } catch (Exception ex) {
        String msg = getPluginUtils().getString(PROBLEM, new Object[] {descriptor});
        getPluginUtils().log(IStatus.ERROR, ex, msg);
        continuing = false;
      }

      // BML 9/16/04  ----------------------------
      // ModelObjectAction caches a selection, however, this instance does not.
      // Need to create a temporary selection to pass into the wizards, either an EObject
      // or a model resource.
      ISelection tempSelection = null;
      if (sibling.eContainer() != null) {
        tempSelection = new StructuredSelection(sibling.eContainer());
      } else {
        ModelResource mr = ModelUtilities.getModelResourceForModelObject(sibling);
        if (mr != null) tempSelection = new StructuredSelection(mr);
      }
      // --------------------------------------------

      if (continuing) {
        // We need to insure that all containers (especially Transformation & MappingClassSet
        // containers) are loaded/created
        // prior to new child transaction.  This insures undo works.
        ModelUtilities.initializeModelContainers(
            modelResource, "New Sibling Added", this); // $NON-NLS-1$

        if (NewModelObjectWizardManager.isObjectDescriptorValid(
            shell, descriptor, modelResource, tempSelection)) {

          //                   System.out.println("[NewSiblingAction.doRun] will run the
          // wizard");//$NON-NLS-1$

          // Defect 18433 - The XMLDocumentWizard was changed to insure that all work was done one a
          // single thread
          // and that wizard managed a single transaction to insure UNDO capability
          // (i.e. started, committed, canceled/rolledBack)
          // if there is a wizard, use it:
          NewModelObjectWizardManager.processObjectDescriptor(
              shell, descriptor, modelResource, tempSelection);

        } else {

          // if no wizard, create the new objects here
          //                   System.out.println("[NewSiblingAction.doRun] will do create txn");
          // //$NON-NLS-1$
          boolean started =
              ModelerCore.startTxn(
                  true,
                  UiConstants.Util.getString("NewSiblingAction.undoLabel", descriptor.getLabel()),
                  this); //$NON-NLS-1$
          boolean succeeded = false;
          EObject newObj = null;
          try {
            boolean undoable = true;

            newObj = ModelerCore.getModelEditor().createNewSiblingFromCommand(sibling, descriptor);

            // Defect 18433 - BML 8/31/05 - Added this manager and INewModelObjectHelper interface
            // to give arbitary
            // plugins the change to contribute more work following the creation of a new object
            // In the case of a Virtual Group, we needed to create the transformation for that table
            // so it didn't
            // get lazily created as another "Undo" event. (i.e. TransformationNotificationListener,
            // EditAction,, etc.)
            // If Helper exists, ask for helpCreate(newObj)
            // The helper also has the opportunity to change/override the "Undo" state of the
            // transaction

            undoable = NewModelObjectHelperManager.helpCreate(newObj, null);
            if (!undoable) ModelerCore.getCurrentUoW().setUndoable(false);

            succeeded = true;
          } catch (ModelerCoreException theException) {
            String msg = getPluginUtils().getString(PROBLEM, new Object[] {descriptor});
            getPluginUtils().log(IStatus.ERROR, theException, msg);
            setEnabled(false);
          } finally {
            if (started) {
              if (succeeded) {
                String newObjName = ModelerCore.getModelEditor().getName(newObj);
                if (newObjName != null) {
                  ModelerCore.getCurrentUoW()
                      .setDescription(
                          UiConstants.Util.getString(
                              "NewSiblingAction.undoLabel", newObjName)); // $NON-NLS-1$
                }
                ModelerCore.commitTxn();
              } else {
                ModelerCore.rollbackTxn();
              }
            }
          }
        }
      }
    }
  }
  /**
   * Return a collection EMF resource matching the specified model name.
   *
   * @param modelName The name of the model whose resource/s are returned
   * @return The collection of EMD resources
   */
  private Collection findResourcesByName(final String modelName) {
    CoreArgCheck.isNotEmpty(modelName);

    // get the collection of resources to check
    Collection rsrcs =
        new ArrayList(
            (this.getResources() != null ? this.getResources() : getContainer().getResources()));

    // Add the system models to the collection if not already there
    Resource[] systemModels = ModelerCore.getSystemVdbResources();
    for (int i = 0; i != systemModels.length; ++i) {
      Resource systemModel = systemModels[i];
      if (!rsrcs.contains(systemModel)) {
        rsrcs.add(systemModel);
      }
    }

    // get the editor to get the name of the resources
    ModelEditor modelEditor = ModelerCore.getModelEditor();
    // find all the resource the match the model name
    Collection resources = new ArrayList(1);
    // get the index selector to limit the resource search
    IndexSelector selector = this.getIndexSelector();
    if (selector != null && selector instanceof ModelResourceIndexSelector) {
      // the selector has reference to the resource and references to its imports
      ModelResourceIndexSelector resourceSelector = (ModelResourceIndexSelector) selector;
      // try finding the entity in the selectors resource
      Resource modelResource = resourceSelector.getResource();
      String resourceName = modelEditor.getModelName(modelResource);
      if (resourceName.equalsIgnoreCase(modelName)) {
        resources.add(modelResource);
      } else {
        // check if any if any of the imported resources have the same name
        Iterator importIter = resourceSelector.getModelImports().iterator();
        while (importIter.hasNext()) {
          ModelImport modelImport = (ModelImport) importIter.next();
          String importName = modelImport.getName();
          if (importName.equalsIgnoreCase(modelName)) {
            // compare the import path of the model to the path in the resource
            String importPath = modelImport.getPath();
            for (Iterator resourceIter = rsrcs.iterator(); resourceIter.hasNext(); ) {
              Resource resource = (Resource) resourceIter.next();
              String resourceUri = URI.decode(resource.getURI().toString());
              if (CoreStringUtil.endsWithIgnoreCase(resourceUri, importPath)) {
                resources.add(resource);
                break;
              }
            }
          }
        }
      }
    } else {
      // find the resource that matches the model name
      for (Iterator resourceIter = rsrcs.iterator(); resourceIter.hasNext(); ) {
        Resource resource = (Resource) resourceIter.next();
        String resourceName = modelEditor.getModelName(resource);
        if (resourceName.equalsIgnoreCase(modelName)) {
          resources.add(resource);
          break;
        }
      }
    }
    if (!resources.isEmpty()) {
      return resources;
    }
    // all open resources as model could not be found
    return rsrcs;
  }
  public String getSqlOutputString(ModelResource modelResource) throws ModelWorkspaceException {
    List transformations = modelResource.getModelTransformations().getTransformations();
    int nTransforms = transformations.size();
    int initBufferSize = nTransforms * 200;
    StringBuffer sb = new StringBuffer(initBufferSize);
    String relativeTablePath = null;
    boolean hasMissingSelects = false;
    boolean hasMissingInserts = false;
    boolean hasMissingUpdates = false;
    boolean hasMissingDeletes = false;

    for (Iterator iter = transformations.iterator(); iter.hasNext(); ) {
      Object obj = iter.next();
      String rowString = null;
      if (obj instanceof SqlTransformationMappingRoot) {
        EObject table = ((SqlTransformationMappingRoot) obj).getTarget();
        relativeTablePath = ModelerCore.getModelEditor().getModelRelativePath(table).toString();

        String userString = TransformationHelper.getSelectSqlString(obj);

        if (userString != null && relativeTablePath != null) {
          rowString = createRowForFile(QueryValidator.SELECT_TRNS, relativeTablePath, userString);
          if (rowString != null && rowString.length() > 0) {
            sb.append(rowString);
          }
        } else {
          hasMissingSelects = true;
        }

        // Now check if updates allowed
        boolean tableSupportsUpdates = TransformationHelper.tableSupportsUpdate(table);
        if (tableSupportsUpdates) {
          if (TransformationHelper.supportsInsert((EObject) obj, null)) {
            userString = TransformationHelper.getInsertSqlString(obj);

            if (userString != null && relativeTablePath != null) {
              rowString =
                  createRowForFile(QueryValidator.INSERT_TRNS, relativeTablePath, userString);
              if (rowString != null && rowString.length() > 0) {
                sb.append(rowString);
              }
            } else {
              hasMissingInserts = true;
            }
          }
          if (TransformationHelper.supportsUpdate((EObject) obj, null)) {
            userString = TransformationHelper.getUpdateSqlString(obj);

            if (userString != null && relativeTablePath != null) {
              rowString =
                  createRowForFile(QueryValidator.UPDATE_TRNS, relativeTablePath, userString);
              if (rowString != null && rowString.length() > 0) {
                sb.append(rowString);
              }
            } else {
              hasMissingUpdates = true;
            }
          }
          if (TransformationHelper.supportsDelete((EObject) obj, null)) {
            userString = TransformationHelper.getDeleteSqlString(obj);

            if (userString != null && relativeTablePath != null) {
              rowString =
                  createRowForFile(QueryValidator.DELETE_TRNS, relativeTablePath, userString);
              if (rowString != null && rowString.length() > 0) {
                sb.append(rowString);
              }
            } else {
              hasMissingDeletes = true;
            }
          }
        }
      }
    }

    // If operations are missing, specify in the error message
    if (hasMissingSelects || hasMissingInserts || hasMissingUpdates || hasMissingDeletes) {
      int count = 0;
      StringBuffer msgBuff =
          new StringBuffer(
              UiConstants.Util.getString(
                  "ExportTransformationSqlToTextAction.exportQueryProblem",
                  modelResource.getItemName())); // $NON-NLS-1$
      msgBuff.append(SPACE + LEFT_BRACKET);
      if (hasMissingSelects) {
        msgBuff.append(ISQLConstants.SQL_TYPE_SELECT_STRING);
        count++;
      }
      if (hasMissingInserts) {
        if (count > 0) msgBuff.append(SPACE + DELIMETER + SPACE);
        msgBuff.append(ISQLConstants.SQL_TYPE_INSERT_STRING);
        count++;
      }
      if (hasMissingUpdates) {
        if (count > 0) msgBuff.append(SPACE + DELIMETER + SPACE);
        msgBuff.append(ISQLConstants.SQL_TYPE_UPDATE_STRING);
        count++;
      }
      if (hasMissingDeletes) {
        if (count > 0) msgBuff.append(SPACE + DELIMETER + SPACE);
        msgBuff.append(ISQLConstants.SQL_TYPE_DELETE_STRING);
        count++;
      }
      msgBuff.append(RIGHT_BRACKET);
      UiConstants.Util.log(IStatus.ERROR, msgBuff.toString());
    }

    return sb.toString();
  }
 private Collection copyEObject(final List eObjects, final Map originalsToCopies)
     throws Exception {
   return ModelerCore.getModelEditor().copyAll(eObjects, originalsToCopies);
 }
  /**
   * Sets the core value of the specified facet. If facet cannot be properly modified to match fv,
   * facets will be added or removed as necessary to make it work. This occurs when a min or max
   * value is changed from inclusive to exclusive, and when dealing with patterns and enumerations.
   *
   * @param facet
   * @param fv
   */
  private static XSDConstrainingFacet setMainFacetValue(
      XSDSimpleTypeDefinition type, XSDConstrainingFacet facet, Object value) {
    int facetClassifierID = facet.eClass().getClassifierID();
    switch (facetClassifierID) {
      case XSDPackage.XSD_LENGTH_FACET:
        {
          XSDLengthFacet lf = (XSDLengthFacet) facet;
          if (value instanceof Integer) {
            Integer i = (Integer) value;
            lf.setLexicalValue(i.toString());
          } else if (value instanceof InclusiveInteger) {
            InclusiveInteger ii = (InclusiveInteger) value;
            lf.setLexicalValue(Integer.toString(ii.value));
          } // endif
        }
        break;
      case XSDPackage.XSD_MAX_LENGTH_FACET:
        {
          XSDMaxLengthFacet mf = (XSDMaxLengthFacet) facet;
          if (value instanceof Integer) {
            Integer i = (Integer) value;
            mf.setLexicalValue(i.toString());
          } else if (value instanceof InclusiveInteger) {
            InclusiveInteger ii = (InclusiveInteger) value;
            mf.setLexicalValue(Integer.toString(ii.value));
          } // endif
        }
        break;
      case XSDPackage.XSD_MIN_LENGTH_FACET:
        {
          XSDMinLengthFacet mf = (XSDMinLengthFacet) facet;
          if (value instanceof Integer) {
            Integer i = (Integer) value;
            mf.setLexicalValue(i.toString());
          } else if (value instanceof InclusiveInteger) {
            InclusiveInteger ii = (InclusiveInteger) value;
            mf.setLexicalValue(Integer.toString(ii.value));
          } // endif
        }
        break;
      case XSDPackage.XSD_PATTERN_FACET:
        {
          XSDPatternFacet pf = (XSDPatternFacet) facet;
          pf.setLexicalValue((String) value);
        }
        break;
      case XSDPackage.XSD_ENUMERATION_FACET:
        {
          XSDEnumerationFacet ef = (XSDEnumerationFacet) facet;
          ef.setLexicalValue((String) value);
        }
        break;
      case XSDPackage.XSD_WHITE_SPACE_FACET:
        {
          XSDWhiteSpaceFacet wf = (XSDWhiteSpaceFacet) facet;
          if (value instanceof String) {
            String white = (String) value;
            wf.setLexicalValue(white);
          } // endif
        }
        break;
      case XSDPackage.XSD_MIN_EXCLUSIVE_FACET:
      case XSDPackage.XSD_MIN_INCLUSIVE_FACET:
        {
          XSDMinFacet mf = (XSDMinFacet) facet;
          if (value instanceof Integer) {
            Integer i = (Integer) value;
            mf.setLexicalValue(i.toString());
          } else if (value instanceof InclusiveInteger) {
            InclusiveInteger ii = (InclusiveInteger) value;
            if (ii.isInclusive == mf.isInclusive()) {
              // same inclusive types, don't need to do anything crazy
              mf.setLexicalValue(Integer.toString(ii.value));
            } else {
              XSDMinFacet mf2;
              if (ii.isInclusive) {
                mf2 = XSDFactory.eINSTANCE.createXSDMinInclusiveFacet();
              } else {
                mf2 = XSDFactory.eINSTANCE.createXSDMinExclusiveFacet();
              } // endif
              mf2.setLexicalValue(Integer.toString(ii.value));
              try {
                // remove old:
                ModelerCore.getModelEditor().removeValue(type, mf, type.getFacetContents());
                // add the copy:
                ModelerCore.getModelEditor().addValue(type, mf2, type.getFacetContents());
                // update the return value:
                facet = mf2;
              } catch (ModelerCoreException err) {
                ModelerXsdUiConstants.Util.log(err);
              } // endtry

              return mf2;
            } // endif -- same inclusive
          } // endif -- integer or iinteger
        }
        break;
      case XSDPackage.XSD_MAX_EXCLUSIVE_FACET:
      case XSDPackage.XSD_MAX_INCLUSIVE_FACET:
        {
          XSDMaxFacet mf = (XSDMaxFacet) facet;
          if (value instanceof Integer) {
            Integer i = (Integer) value;
            mf.setLexicalValue(i.toString());
          } else if (value instanceof InclusiveInteger) {
            InclusiveInteger ii = (InclusiveInteger) value;
            if (ii.isInclusive == mf.isInclusive()) {
              // same inclusive types, don't need to do anything crazy
              mf.setLexicalValue(Integer.toString(ii.value));
            } else {
              XSDMaxFacet mf2;
              if (ii.isInclusive) {
                mf2 = XSDFactory.eINSTANCE.createXSDMaxInclusiveFacet();
              } else {
                mf2 = XSDFactory.eINSTANCE.createXSDMaxExclusiveFacet();
              } // endif
              mf2.setLexicalValue(Integer.toString(ii.value));
              try {
                // remove old:
                ModelerCore.getModelEditor().removeValue(type, mf, type.getFacetContents());
                // add the copy:
                ModelerCore.getModelEditor().addValue(type, mf2, type.getFacetContents());
                // update the return value:
                facet = mf2;
              } catch (ModelerCoreException err) {
                ModelerXsdUiConstants.Util.log(err);
              } // endtry

              return mf2;
            } // endif -- same inclusive
          } // endif -- integer or iinteger
        }
        break;
      case XSDPackage.XSD_FRACTION_DIGITS_FACET:
        {
          XSDFractionDigitsFacet ff = (XSDFractionDigitsFacet) facet;
          if (value instanceof Integer) {
            Integer i = (Integer) value;
            ff.setLexicalValue(i.toString());
          } else if (value instanceof InclusiveInteger) {
            InclusiveInteger ii = (InclusiveInteger) value;
            ff.setLexicalValue(Integer.toString(ii.value));
          } // endif
        }
        break;
      case XSDPackage.XSD_TOTAL_DIGITS_FACET:
        {
          XSDTotalDigitsFacet tf = (XSDTotalDigitsFacet) facet;
          if (value instanceof Integer) {
            Integer i = (Integer) value;
            tf.setLexicalValue(i.toString());
          } else if (value instanceof InclusiveInteger) {
            InclusiveInteger ii = (InclusiveInteger) value;
            tf.setLexicalValue(Integer.toString(ii.value));
          } // endif
        }
        break;

      default:
        ModelerXsdUiConstants.Util.log(
            ModelerXsdUiConstants.Util.getString(ERROR_KEY_UNUSABLE_FACET, facet));
        break;
    } // endswitch

    return facet;
  }
 /**
  * @param eObj the EObject whose contents will be checked for references to the original model
  *     and updated to new model
  * @see org.teiid.designer.core.util.ModelVisitor#visit(org.eclipse.emf.ecore.EObject)
  * @since 4.2
  */
 @Override
 public boolean visit(final EObject eObj) {
   // Get all EReference features for this EClass
   final List refs = eObj.eClass().getEAllReferences();
   for (final Iterator iter1 = refs.iterator(); iter1.hasNext(); ) {
     final EReference eReference = (EReference) iter1.next();
     // since we are going to visit all children
     // need not visit container references
     if (eReference.isContainment() && eReference.isContainer() && eReference.isVolatile()) {
       continue;
     }
     final Object value = eObj.eGet(eReference);
     if (eReference.isMany()) {
       // multi-valued feature ...
       final List values = (List) value;
       if (!values.isEmpty()) {
         final Collection newValues = new ArrayList(values.size());
         boolean resetList = false;
         // Check each value in the List for references to
         // EObjects in the original model. If the value
         // is found in the map then the EObject was copied
         // so the reference needs to be reset
         for (final Iterator iter2 = values.iterator(); iter2.hasNext(); ) {
           final Object valueInList = iter2.next();
           if (valueInList != null && valueInList instanceof EObject) {
             final EObject orig = (EObject) valueInList;
             final EObject copy = (EObject) originalsToCopies.get(orig);
             if (copy != null) {
               newValues.add(copy);
               resetList = true;
             } else {
               // copy does not exist,
               // values on the object may need to be updated
               updateReference(orig);
               newValues.add(orig);
             }
           }
         }
         if (resetList) {
           // always fails (see SetCommand.java:340):
           // eObj.eSet(eReference,newValues);
           ModelerCore.getModelEditor().setPropertyValue(eObj, newValues, eReference);
         }
       }
     } else {
       // There may be 0..1 value ...
       if (value != null && value instanceof EObject) {
         final EObject orig = (EObject) value;
         final EObject copy = (EObject) originalsToCopies.get(orig);
         if (copy != null) {
           eObj.eSet(eReference, copy);
         } else {
           // copy does not exist,
           // values on the object may need to be updated
           updateReference(orig);
         }
       }
     }
   }
   return true;
 }
  private EObject createViewProcedureInTxn(
      ModelResource modelResource, RelationalViewProcedure viewProcedure) {
    EObject newTable = null;

    boolean requiredStart =
        ModelerCore.startTxn(true, true, Messages.createRelationalViewProcedureTitle, this);
    boolean succeeded = false;
    try {
      ModelEditor editor =
          ModelEditorManager.getModelEditorForFile(
              (IFile) modelResource.getCorrespondingResource(), true);
      if (editor != null) {
        boolean isDirty = editor.isDirty();

        RelationalViewModelFactory factory = new RelationalViewModelFactory();

        RelationalModel relModel = new RelationalModel("dummy"); // $NON-NLS-1$
        relModel.addChild(viewProcedure);

        factory.build(modelResource, relModel, new NullProgressMonitor());

        if (!isDirty && editor.isDirty()) {
          editor.doSave(new NullProgressMonitor());
        }
        succeeded = true;

        for (Object child : modelResource.getEObjects()) {
          EObject eObj = (EObject) child;
          if (ModelerCore.getModelEditor()
              .getName(eObj)
              .equalsIgnoreCase(this.relationalViewProcedure.getName())) {
            newTable = eObj;
            break;
          }
        }
      }
    } catch (Exception e) {
      MessageDialog.openError(
          Display.getCurrent().getActiveShell(),
          Messages.createRelationalViewProcedureExceptionMessage,
          e.getMessage());
      IStatus status =
          new Status(
              IStatus.ERROR,
              UiConstants.PLUGIN_ID,
              Messages.createRelationalViewProcedureExceptionMessage,
              e);
      UiConstants.Util.log(status);

      return null;
    } finally {
      // if we started the txn, commit it.
      if (requiredStart) {
        if (succeeded) {
          ModelerCore.commitTxn();
        } else {
          ModelerCore.rollbackTxn();
        }
      }
    }

    return newTable;
  }