@Override
  public VdbSourceConnection ensureVdbSourceConnection(
      String sourceModelname, Properties properties) throws Exception {
    CoreArgCheck.isNotNull(properties, "properties"); // $NON-NLS-1$

    ModelConnectionMapper mapper = new ModelConnectionMapper(sourceModelname, properties);

    VdbSourceConnection vdbSourceConnection = null;

    ExecutionAdmin defaultAdmin = getDefaultServer().getAdmin();

    String uuid = ModelerCore.workspaceUuid().toString();

    try {
      vdbSourceConnection = mapper.getVdbSourceConnection(defaultAdmin, uuid);
    } catch (ModelWorkspaceException e) {
      UTIL.log(
          IStatus.ERROR,
          e,
          UTIL.getString(
              "VdbSourceConnectionHandler.Error_could_not_find_source_connection_info_for_{0}_model",
              sourceModelname)); //$NON-NLS-1$
    }

    // TODO: vdbSourceConnection may be NULL, so query the user for translator name & jndi name

    return vdbSourceConnection;
  }
 public EntityProcessor(
     Connection sqlConnection,
     MetamodelEntityBuilder entityBuilder,
     int modelType,
     String modelAndSchemaName,
     MultiStatus status) {
   super(sqlConnection, modelAndSchemaName);
   CoreArgCheck.isNotNull(status);
   CoreArgCheck.isNotNull(entityBuilder);
   this.status = status;
   this.entityBuilder = entityBuilder;
   if (modelType == RELATIONAL_MODEL) {
     this.processingOrder = RELATIONAL_PROCESSING_ORDER;
   } else if (modelType == EXTENSION_MODEL) {
     this.processingOrder = EXTENSIONS_PROCESSING_ORDER;
   } else {
     this.processingOrder = new String[] {};
   }
 }
  /** Displays the appropriate UI for the current model state. */
  void displayElementSymbol() {
    CoreArgCheck.isNotNull(viewer);

    StructuredSelection selection = StructuredSelection.EMPTY;

    if (model.getElementSymbol() != null) {
      strategy.setTreeViewer(viewer); // make sure this viewer is set before using strategy
      Object node = strategy.getNode(model.getElementSymbol());

      if (node != null) {
        selection = new StructuredSelection(node);
      }

      if (!selection.equals(viewer.getSelection())) {
        viewer.setSelection(selection);
      }
    }
  }
  public void modifyNotCriteriaStatus() {
    Object selectedObj = getSelectedObject();
    CoreArgCheck.isNotNull(selectedObj); // should not be calling if no row selected

    if (selectedObj instanceof NotCriteria) {
      modifySelectedItem(((NotCriteria) selectedObj).getCriteria(), true);
    } else if (selectedObj instanceof Criteria) {
      modifySelectedItem(new NotCriteria((Criteria) selectedObj), true);
    } else if (isUndefined(selectedObj)) {
      CoreArgCheck.isTrue(
          false,
          Util.getString(
              PREFIX + "unexpectedType", // $NON-NLS-1$
              new Object[] {"modifyNotCriteriaStatus", BuilderUtils.UNDEFINED})); // $NON-NLS-1$
    } else {
      CoreArgCheck.isTrue(
          false,
          Util.getString(
              PREFIX + "unexpectedType", // $NON-NLS-1$
              new Object[] {"modifyNotCriteriaStatus", selectedObj.getClass()})); // $NON-NLS-1$
    }
  }
  protected void handleSetSelected() {
    editor.save();

    // need the editor's language object in order to update tree.
    // the language object should never be null. if it was this handler should not have been called
    LanguageObject langObj = editor.getLanguageObject();

    CoreArgCheck.isNotNull(
        langObj,
        Util.getString(
            PREFIX + "nullLangObj", // $NON-NLS-1$
            new Object[] {"handleSetSelected"})); // $NON-NLS-1$

    // update tree
    treeViewer.modifySelectedItem(langObj, false);

    // update SQL text
    setCurrentSql(treeViewer.getLanguageObject());

    // put focus back on editor from the set button
    editor.acceptFocus();
  }
  /**
   * Returns the collective properties of a <code>ConnectionProfile</code> to include name,
   * description and provider id in addition to it's base properties. These properties are also
   * prefixed with a custom namespace for storage in a model resource "annotation"
   *
   * @param connectionProfile the connection profile
   * @return the name-spaced properties for the connection profile
   */
  public Properties getNamespacedProperties(IConnectionProfile connectionProfile) {
    CoreArgCheck.isNotNull(connectionProfile, "connectionProfile"); // $NON-NLS-1$

    Properties baseProps = connectionProfile.getBaseProperties();
    Properties connProps = new Properties();
    connProps.put(
        IConnectionInfoHelper.CONNECTION_PROFILE_NAMESPACE + IConnectionInfoHelper.PROFILE_NAME_KEY,
        connectionProfile.getName());
    connProps.put(
        IConnectionInfoHelper.CONNECTION_PROFILE_NAMESPACE
            + IConnectionInfoHelper.PROFILE_DESCRIPTION_KEY,
        connectionProfile.getDescription());
    connProps.put(
        IConnectionInfoHelper.CONNECTION_PROFILE_NAMESPACE
            + IConnectionInfoHelper.PROFILE_PROVIDER_ID_KEY,
        connectionProfile.getProviderId());
    Set<Object> keys = baseProps.keySet();
    for (Object nextKey : keys) {
      connProps.put(
          IConnectionInfoHelper.CONNECTION_PROFILE_NAMESPACE + nextKey, baseProps.get(nextKey));
    }
    return connProps;
  }
  public static void deploy(final IFile medToDeploy) {
    CoreArgCheck.isNotNull(medToDeploy, "medToDeploy is null"); // $NON-NLS-1$

    // Check whether there is currently an open editor for the selected Med
    IEditorPart editor = getOpenEditor(medToDeploy);

    // If editor is open and dirty, ask user whether to save
    if ((editor != null) && editor.isDirty()) {
      if (!MessageDialog.openQuestion(
          getShell(),
          Messages.updateMedInRegistryMedDirtyTitle,
          Messages.updateMedInRegistryMedDirtyMsg)) {
        return;
      }

      editor.doSave(new NullProgressMonitor());
    }

    // If the file has any error markers, user is informed to fix them first
    if (RegistryDeploymentValidator.checkProblemMarkers(medToDeploy)) {
      return;
    }

    ModelExtensionRegistry registry = ExtensionPlugin.getInstance().getRegistry();
    InputStream fileContents = null;

    try {
      fileContents = medToDeploy.getContents();
    } catch (CoreException e) {
      UTIL.log(
          IStatus.ERROR, e, NLS.bind(Messages.medFileGetContentsErrorMsg, medToDeploy.getName()));
    }

    if (fileContents != null) {
      // Parse file contents to get the MED. Show info dialog if parse errors.
      ModelExtensionDefinition med = null;

      try {
        ModelExtensionDefinitionParser parser =
            new ModelExtensionDefinitionParser(ExtensionPlugin.getInstance().getMedSchema());
        med =
            parser.parse(
                fileContents,
                ExtensionPlugin.getInstance().createDefaultModelObjectExtensionAssistant());

        if (!parser.getErrors().isEmpty()) {
          MessageDialog.openError(
              getShell(),
              Messages.registerMedActionFailedTitle,
              NLS.bind(Messages.medFileParseErrorMsg, medToDeploy.getName()));
          return;
        }
      } catch (Exception e) {
        UTIL.log(e);
        MessageDialog.openError(
            getShell(), Messages.registerMedActionFailedTitle, Messages.registerMedActionFailedMsg);
        return;
      }

      // Continue checks on parsable MED
      if (med != null) {
        ModelExtensionDefinition medNSPrefixMatch =
            RegistryDeploymentValidator.getRegisteredMedWithNSPrefix(
                registry, med.getNamespacePrefix());
        ModelExtensionDefinition medNSUriMatch =
            RegistryDeploymentValidator.getRegisteredMedWithNSUri(registry, med.getNamespaceUri());

        boolean nsPrefixConflict = false;
        boolean nsUriConflict = false;
        boolean nsPrefixAndUriConflictSameMed = false;
        boolean nsPrefixConflictMedBuiltIn = false;
        boolean nsUriConflictMedBuiltIn = false;

        if (medNSPrefixMatch != null) {
          nsPrefixConflict = true;
          nsPrefixConflictMedBuiltIn = medNSPrefixMatch.isBuiltIn();
        }
        if (medNSUriMatch != null) {
          nsUriConflict = true;
          nsUriConflictMedBuiltIn = medNSUriMatch.isBuiltIn();
        }
        if (nsPrefixConflict && nsUriConflict && medNSPrefixMatch.equals(medNSUriMatch))
          nsPrefixAndUriConflictSameMed = true;

        // No conflicts - add it to the registry
        if (!nsPrefixConflict && !nsUriConflict) {
          // Add the selected Med
          BusyIndicator.showWhile(
              Display.getDefault(),
              new Runnable() {
                @Override
                public void run() {
                  internalRun(medToDeploy, false);
                }
              });
          // If the NS Prefix conflicts with a Built-in, prompt user to fix
        } else if (nsPrefixConflictMedBuiltIn) {
          RegistryDeploymentValidator.showMedNSPrefixConflictsWBuiltInDialog();
          // If the NS URI conflicts with a Built-in, prompt user to fix
        } else if (nsUriConflictMedBuiltIn) {
          RegistryDeploymentValidator.showMedNSUriConflictsWBuiltInDialog();
          // If there is (1) just a NS Prefix Conflict or (2) NS Prefix AND URI, but they are same
          // MED, prompt user
          // whether to update
        } else if (nsPrefixConflict
            && (!nsUriConflict || (nsUriConflict && nsPrefixAndUriConflictSameMed))) {
          // Do not re-deploy the same MED
          if (med.equals(medNSPrefixMatch)) {
            RegistryDeploymentValidator.showMedNSPrefixAlreadyRegisteredDialog();
          } else {
            boolean doUpdate =
                RegistryDeploymentValidator.showMedNSPrefixAlreadyRegisteredDoUpdateDialog();
            if (doUpdate) {
              // Add the selected Med
              BusyIndicator.showWhile(
                  Display.getDefault(),
                  new Runnable() {
                    @Override
                    public void run() {
                      internalRun(medToDeploy, true);
                    }
                  });
            }
          }
          // If there is a NS URI Conflict, prompt user to fix it
        } else if (nsUriConflict) {
          RegistryDeploymentValidator.showMedNSUriAlreadyRegisteredDialog();
        }
      }
    }
  }
  private void addUndefinedCriteria(Criteria theCriteria, boolean theAndFlag) {
    CoreArgCheck.isNotNull(theCriteria); // should not be calling if null

    Object newSelection = StructuredSelection.EMPTY;

    if (theCriteria instanceof CompoundCriteria) {
      CompoundCriteria criteria = (CompoundCriteria) theCriteria;
      criteria.addCriteria((Criteria) null);
      refresh(true);
      newSelection = contentProvider.getChildAt((criteria.getCriteriaCount() - 1), criteria);
    } else if (theCriteria instanceof NotCriteria) {
      // the contained Criteria must be a CompoundCriteria
      addUndefinedCriteria(((NotCriteria) theCriteria).getCriteria(), theAndFlag);
    } else if (theCriteria instanceof PredicateCriteria) {
      CompoundCriteria compoundCriteria = new CompoundCriteria();
      compoundCriteria.setOperator((theAndFlag) ? CompoundCriteria.AND : CompoundCriteria.OR);
      compoundCriteria.addCriteria(theCriteria);
      compoundCriteria.addCriteria((Criteria) null);

      // modify parent here
      LanguageObject parent = (LanguageObject) contentProvider.getParent(theCriteria);
      int index = contentProvider.getChildIndex(theCriteria);

      if (parent == null) {
        setLanguageObject(compoundCriteria);
        refresh(true);

        // select undefined criteria
        newSelection = contentProvider.getChildAt(1, contentProvider.getRoot());
        expandToLevel(newSelection, ALL_LEVELS);
      } else if ((parent instanceof NotCriteria) || (parent instanceof CompoundCriteria)) {
        CompoundCriteria criteria = null;

        if (parent instanceof NotCriteria) {
          // then NotCriteria's contained criteria must be a CompoundCriteria
          criteria = (CompoundCriteria) ((NotCriteria) theCriteria).getCriteria();
        } else {
          criteria = (CompoundCriteria) parent;
        }

        List crits = criteria.getCriteria();
        crits.set(index, compoundCriteria);
        refresh(true);

        // select undefined criteria
        newSelection = contentProvider.getChildAt(1, compoundCriteria);
      } else {
        CoreArgCheck.isTrue(
            false,
            Util.getString(
                PREFIX + "unexpectedType", // $NON-NLS-1$
                new Object[] {"addUndefinedCriteria", parent.getClass()})); // $NON-NLS-1$
      }
    }

    // select appropriate tree item
    final Object selection = newSelection;

    Display.getDefault()
        .asyncExec(
            new Runnable() {
              public void run() {
                setSelection(new StructuredSelection(selection));
              }
            });
  }
  private void modifyLanguageObject(
      Object theObject, LanguageObject theNewValue, boolean retainSelection) {
    CoreArgCheck.isNotNull(theNewValue); // should not be null when modifying

    //
    // set the parent object to reflect the change in it's child. parent's can't be undefined
    //

    Object newSelection = StructuredSelection.EMPTY;
    LanguageObject parent = (LanguageObject) contentProvider.getParent(theObject);

    Object newValue = theNewValue;

    if (parent == null) {
      // root language object
      setLanguageObject((LanguageObject) newValue);
      refresh(true);
      newSelection = contentProvider.getRoot();
      expandToLevel(newSelection, ALL_LEVELS);

      if (newSelection instanceof Function) {
        Function function = (Function) newSelection;

        if (function.getArgs().length > 0) {
          newSelection = contentProvider.getChildAt(0, function);
        }
      }
    } else if (parent instanceof Function) {
      // set the arg to new value in parent
      int index = contentProvider.getChildIndex(theObject);

      Expression[] args = ((Function) parent).getArgs();
      args[index] = (Expression) newValue;

      refresh(true);
      expandToLevel(parent, ALL_LEVELS);

      newSelection = contentProvider.getChildAt(index, parent);

      if (!retainSelection) {
        if (newSelection instanceof Function) {
          // if function arg change to be a function, select first function arg
          if (contentProvider.getChildCount(newSelection) > 0) {
            newSelection = contentProvider.getChildAt(0, newSelection);
          }
        } else {
          // select next sibling function arg if exists
          if ((args.length - 1) > index) {
            newSelection = contentProvider.getChildAt(index + 1, parent);
          } else if (index > 0) {
            newSelection = contentProvider.getChildAt(0, parent);
          } else {
            newSelection = contentProvider.getChildAt(index, parent);
          }
        }
      }
    } else if (parent instanceof Criteria) {
      // theLangObj must also be a Criteria
      // since NotCriteria aren't really edited in the editor (their contained criteria is). Need to
      // save the state in order to restore it when modifying
      Criteria newCriteria = (Criteria) newValue;
      int index = contentProvider.getChildIndex(theObject);

      if ((parent instanceof CompoundCriteria) || (parent instanceof NotCriteria)) {
        CompoundCriteria compoundCriteria = null;

        if (parent instanceof CompoundCriteria) {
          compoundCriteria = (CompoundCriteria) parent;
        } else {
          compoundCriteria = (CompoundCriteria) ((NotCriteria) parent).getCriteria();
        }

        List criteriaCollection = compoundCriteria.getCriteria();
        criteriaCollection.set(index, newCriteria);
        refresh(true);

        if (retainSelection) {
          newSelection = criteriaCollection.get(index);
        } else {
          // set selection to next sibling criteria or to the first sibling
          if ((criteriaCollection.size() - 1) > index) {
            newSelection = criteriaCollection.get(index + 1);
          } else if (index > 0) {
            newSelection = criteriaCollection.get(0);
          } else {
            newSelection = contentProvider.getChildAt(index + 1, parent);
          }
        }
      } else {
        CoreArgCheck.isTrue(
            false,
            Util.getString(
                PREFIX + "unexpectedType", // $NON-NLS-1$
                new Object[] {
                  "modifyLanguageObject", //$NON-NLS-1$
                  parent.getClass().getName()
                }));
      }

      expandToLevel(parent, ALL_LEVELS);
    }

    // select next node
    setSelection(
        (newSelection == null) ? StructuredSelection.EMPTY : new StructuredSelection(newSelection));
  }