/** PUBLIC: Return a collection of the field to query key associations. */
  public Vector getSourceToTargetQueryKeyFieldAssociations() {
    Vector associations = new Vector(getSourceToTargetQueryKeyNames().size());
    Iterator sourceFieldEnum = getSourceToTargetQueryKeyNames().keySet().iterator();
    Iterator targetQueryKeyEnum = getSourceToTargetQueryKeyNames().values().iterator();
    while (sourceFieldEnum.hasNext()) {
      Object fieldValue = ((DatabaseField) sourceFieldEnum.next()).getQualifiedName();
      Object attributeValue = targetQueryKeyEnum.next();
      associations.addElement(new Association(fieldValue, attributeValue));
    }

    return associations;
  }
  /** INTERNAL: Transform the object-level value into a database-level value */
  public Object getFieldValue(Object objectValue, AbstractSession session) {
    DatabaseMapping mapping = getMapping();
    Object fieldValue = objectValue;
    if ((mapping != null)
        && (mapping.isDirectToFieldMapping() || mapping.isDirectCollectionMapping())) {
      // CR#3623207, check for IN Collection here not in mapping.
      if (objectValue instanceof Collection) {
        // This can actually be a collection for IN within expressions... however it would be better
        // for expressions to handle this.
        Collection values = (Collection) objectValue;
        Vector fieldValues = new Vector(values.size());
        for (Iterator iterator = values.iterator(); iterator.hasNext(); ) {
          Object value = iterator.next();
          if (!(value instanceof Expression)) {
            value = getFieldValue(value, session);
          }
          fieldValues.add(value);
        }
        fieldValue = fieldValues;
      } else {
        if (mapping.isDirectToFieldMapping()) {
          fieldValue = ((AbstractDirectMapping) mapping).getFieldValue(objectValue, session);
        } else if (mapping.isDirectCollectionMapping()) {
          fieldValue = ((DirectCollectionMapping) mapping).getFieldValue(objectValue, session);
        }
      }
    }

    return fieldValue;
  }
 /**
  * INTERNAL: Convert all the class-name-based settings in this mapping to actual class-based
  * settings. This method is used when converting a project that has been built with class names to
  * a project with classes.
  */
 @Override
 public void convertClassNamesToClasses(ClassLoader classLoader) {
   super.convertClassNamesToClasses(classLoader);
   Iterator iterator = getTypeIndicatorNameTranslation().entrySet().iterator();
   this.typeIndicatorTranslation = new HashMap();
   while (iterator.hasNext()) {
     Map.Entry entry = (Map.Entry) iterator.next();
     String referenceClassName = (String) entry.getKey();
     Object indicator = entry.getValue();
     Class referenceClass = null;
     try {
       if (PrivilegedAccessHelper.shouldUsePrivilegedAccess()) {
         try {
           referenceClass =
               (Class)
                   AccessController.doPrivileged(
                       new PrivilegedClassForName(referenceClassName, true, classLoader));
         } catch (PrivilegedActionException exception) {
           throw ValidationException.classNotFoundWhileConvertingClassNames(
               referenceClassName, exception.getException());
         }
       } else {
         referenceClass =
             PrivilegedAccessHelper.getClassForName(referenceClassName, true, classLoader);
       }
     } catch (ClassNotFoundException exception) {
       throw ValidationException.classNotFoundWhileConvertingClassNames(
           referenceClassName, exception);
     }
     addClassIndicator(referenceClass, indicator);
   }
 }
  /**
   * INTERNAL: Return the typeIndicatorName translation Used by the Mapping Workbench to avoid
   * classpath dependencies
   */
  public Map getTypeIndicatorNameTranslation() {
    if (typeIndicatorNameTranslation.isEmpty() && !typeIndicatorTranslation.isEmpty()) {
      Iterator keysEnum = typeIndicatorTranslation.keySet().iterator();
      Iterator valuesEnum = typeIndicatorTranslation.values().iterator();
      while (keysEnum.hasNext()) {
        Object key = keysEnum.next();
        Object value = valuesEnum.next();
        if (key instanceof Class) {
          String className = ((Class) key).getName();
          typeIndicatorNameTranslation.put(className, value);
        }
      }
    }

    return typeIndicatorNameTranslation;
  }
  /**
   * INTERNAL: Return the classification for the field contained in the mapping. This is used to
   * convert the row value to a consistent java value.
   */
  @Override
  public Class getFieldClassification(DatabaseField fieldToClassify) {
    if ((getTypeField() != null) && (fieldToClassify.equals(getTypeField()))) {
      return getTypeField().getType();
    }

    String queryKey = (String) getSourceToTargetQueryKeyNames().get(fieldToClassify);
    if (queryKey == null) {
      return null;
    }
    // Search any of the implementor descriptors for a mapping for the query-key.
    Iterator iterator =
        getReferenceDescriptor().getInterfacePolicy().getChildDescriptors().iterator();
    if (iterator.hasNext()) {
      ClassDescriptor firstChild = (ClassDescriptor) iterator.next();
      DatabaseMapping mapping = firstChild.getObjectBuilder().getMappingForAttributeName(queryKey);
      if ((mapping != null) && (mapping.isDirectToFieldMapping())) {
        return ((AbstractDirectMapping) mapping).getAttributeClassification();
      }
      QueryKey targetQueryKey = firstChild.getQueryKeyNamed(queryKey);
      if ((targetQueryKey != null) && (targetQueryKey.isDirectQueryKey())) {
        return firstChild
            .getObjectBuilder()
            .getFieldClassification(((DirectQueryKey) targetQueryKey).getField());
      }
    }
    return null;
  }
  /**
   * INTERNAL: This methods clones all the fields and ensures that each collection refers to the
   * same clones.
   */
  @Override
  public Object clone() {
    VariableOneToOneMapping clone = (VariableOneToOneMapping) super.clone();
    Map setOfKeys = new HashMap(getSourceToTargetQueryKeyNames().size());
    Map sourceToTarget = new HashMap(getSourceToTargetQueryKeyNames().size());
    Vector foreignKeys =
        org.eclipse.persistence.internal.helper.NonSynchronizedVector.newInstance(
            getForeignKeyFields().size());

    if (getTypeField() != null) {
      clone.setTypeField((DatabaseField) this.getTypeField().clone());
    }

    for (Iterator enumtr = getSourceToTargetQueryKeyNames().keySet().iterator();
        enumtr.hasNext(); ) {
      // Clone the SourceKeyFields
      DatabaseField field = (DatabaseField) enumtr.next();
      DatabaseField clonedField = (DatabaseField) field.clone();
      setOfKeys.put(field, clonedField);
      // on the next line I'm cloning the query key names
      sourceToTarget.put(clonedField, getSourceToTargetQueryKeyNames().get(field));
    }

    for (Enumeration enumtr = getForeignKeyFields().elements(); enumtr.hasMoreElements(); ) {
      DatabaseField field = (DatabaseField) enumtr.nextElement();
      foreignKeys.addElement(setOfKeys.get(field));
    }
    clone.setSourceToTargetQueryKeyFields(sourceToTarget);
    clone.setForeignKeyFields(foreignKeys);
    clone.setTypeIndicatorTranslation(new HashMap(this.getTypeIndicatorTranslation()));
    return clone;
  }
  /**
   * INTERNAL: Return the class indicator associations for XML. List of class-name/value
   * associations.
   */
  public Vector getClassIndicatorAssociations() {
    Vector associations = new Vector();
    Iterator classesEnum = getTypeIndicatorNameTranslation().keySet().iterator();
    Iterator valuesEnum = getTypeIndicatorNameTranslation().values().iterator();
    while (classesEnum.hasNext()) {
      Object className = classesEnum.next();

      // If the project was built in runtime is a class, MW is a string.
      if (className instanceof Class) {
        className = ((Class) className).getName();
      }
      Object value = valuesEnum.next();
      associations.addElement(new TypedAssociation(className, value));
    }

    return associations;
  }
 /**
  * INTERNAL: The foreign key names and their primary keys are converted to DatabaseField and
  * stored.
  */
 protected void initializeForeignKeys(AbstractSession session) {
   HashMap newSourceToTargetQueryKeyNames = new HashMap(getSourceToTargetQueryKeyNames().size());
   Iterator iterator = getSourceToTargetQueryKeyNames().entrySet().iterator();
   while (iterator.hasNext()) {
     Map.Entry entry = (Map.Entry) iterator.next();
     DatabaseField field = getDescriptor().buildField((DatabaseField) entry.getKey());
     newSourceToTargetQueryKeyNames.put(field, entry.getValue());
   }
   this.sourceToTargetQueryKeyNames = newSourceToTargetQueryKeyNames;
 }
 /**
  * INTERNAL: writes the first field from each of the owned tables, used for fine-grained
  * pessimistic locking.
  */
 protected void writeForUpdateOfFields(
     ExpressionSQLPrinter printer, SQLSelectStatement statement) {
   for (Iterator iterator = getForUpdateOfFields().iterator(); iterator.hasNext(); ) {
     DatabaseField field = (DatabaseField) iterator.next();
     if (printer.getPlatform().shouldPrintAliasForUpdate()) {
       writeAlias(printer, field, statement);
     } else {
       writeField(printer, field, statement);
     }
   }
 }
  /** INTERNAL: Set the type field classification through searching the indicators hashtable. */
  @Override
  public void preInitialize(AbstractSession session) throws DescriptorException {
    super.preInitialize(session);
    if (getTypeIndicatorTranslation().isEmpty()) {
      return;
    }
    Class type = null;
    for (Iterator typeValuesEnum = getTypeIndicatorTranslation().values().iterator();
        typeValuesEnum.hasNext() && (type == null); ) {
      Object value = typeValuesEnum.next();
      if ((value != Helper.getNullWrapper()) && (!(value instanceof Class))) {
        type = value.getClass();
      }
    }

    getTypeField().setType(type);
  }
  /**
   * INTERNAL: Compare the references of the two objects are the same, not the objects themselves.
   * Used for independent relationships. This is used for testing and validation purposes.
   *
   * <p>Must get separate fields for the objects because we may be adding a different class to the
   * attribute because of the interface
   */
  @Override
  protected boolean compareObjectsWithoutPrivateOwned(
      Object firstObject, Object secondObject, AbstractSession session) {
    Object firstPrivateObject = getRealAttributeValueFromObject(firstObject, session);
    Object secondPrivateObject = getRealAttributeValueFromObject(secondObject, session);

    if ((firstPrivateObject == null) && (secondPrivateObject == null)) {
      return true;
    }

    if ((firstPrivateObject == null) || (secondPrivateObject == null)) {
      return false;
    }
    if (firstPrivateObject.getClass() != secondPrivateObject.getClass()) {
      return false;
    }
    Iterator targetKeys = getSourceToTargetQueryKeyNames().values().iterator();
    ClassDescriptor descriptor = session.getDescriptor(firstPrivateObject.getClass());
    ClassDescriptor descriptor2 = session.getDescriptor(secondPrivateObject.getClass());

    while (targetKeys.hasNext()) {
      String queryKey = (String) targetKeys.next();
      DatabaseField field = descriptor.getObjectBuilder().getFieldForQueryKeyName(queryKey);
      Object firstObjectField =
          descriptor
              .getObjectBuilder()
              .extractValueFromObjectForField(firstPrivateObject, field, session);
      DatabaseField field2 = descriptor2.getObjectBuilder().getFieldForQueryKeyName(queryKey);
      Object secondObjectField =
          descriptor2
              .getObjectBuilder()
              .extractValueFromObjectForField(secondPrivateObject, field2, session);

      if (!((firstObjectField == null) && (secondObjectField == null))) {
        if ((firstObjectField == null) || (secondObjectField == null)) {
          return false;
        }
        if (!firstObjectField.equals(secondObjectField)) {
          return false;
        }
      }
    }

    return true;
  }
  /**
   * INTERNAL: Selection criteria is created with source foreign keys and target keys. This criteria
   * is then used to read target records from the table.
   */
  public void initializeSelectionCriteria(AbstractSession session) {
    Expression selectionCriteria = null;
    Expression expression;

    ExpressionBuilder expBuilder = new ExpressionBuilder();

    Iterator sourceKeysEnum = getSourceToTargetQueryKeyNames().keySet().iterator();

    while (sourceKeysEnum.hasNext()) {
      DatabaseField sourceKey = (DatabaseField) sourceKeysEnum.next();
      String target = (String) this.getSourceToTargetQueryKeyNames().get(sourceKey);
      expression = expBuilder.getParameter(sourceKey).equal(expBuilder.get(target));

      if (selectionCriteria == null) {
        selectionCriteria = expression;
      } else {
        selectionCriteria = expression.and(selectionCriteria);
      }
    }

    setSelectionCriteria(selectionCriteria);
  }