protected void buildExpectedResults() {
    ReadAllQuery query = new ReadAllQuery();
    query.setReferenceClass(Employee.class);

    Vector employees = (Vector) getSession().executeQuery(query);
    Vector distinctEmployees = new Vector();

    // initialize distinctEmployees
    distinctEmployees.addElement(employees.elementAt(0));

    // check employees with duplicate province and add only distinct employees to distinctEmployees
    for (int i = 1; i < employees.size(); i++) {
      boolean duplicateFound = false;

      // iterate through distinctEmployees to check for duplicate provinces, if found, employee not
      // added
      for (int j = 0; j < distinctEmployees.size(); j++) {
        if ((((Employee) employees.elementAt(i)).getAddress().getProvince())
            .equals((((Employee) distinctEmployees.elementAt(j)).getAddress().getProvince()))) {
          duplicateFound = true;
        }
      }
      if (!duplicateFound) {
        distinctEmployees.addElement(employees.elementAt(i));
      }
    }

    for (Enumeration e = distinctEmployees.elements(); e.hasMoreElements(); ) {
      Employee emp = (Employee) e.nextElement();
      Object[] result = new Object[1];
      result[0] = emp.getAddress().getProvince();
      addResult(result, null);
    }
  }
  /**
   * INTERNAL: Return the value for in memory comparison. This is only valid for valueable
   * expressions.
   */
  public Object valueFromObject(
      Object object,
      AbstractSession session,
      AbstractRecord translationRow,
      int valueHolderPolicy,
      boolean isObjectUnregistered) {
    // The expression may be across a relationship, in which case it must be traversed.
    if ((!getBaseExpression().isExpressionBuilder())
        && getBaseExpression().isQueryKeyExpression()) {
      object =
          getBaseExpression()
              .valueFromObject(
                  object, session, translationRow, valueHolderPolicy, isObjectUnregistered);

      // toDo: Null means the join filters out the row, returning null is not correct if an inner
      // join,
      // outer/inner joins need to be fixed to filter correctly.
      if (object == null) {
        return null;
      }

      // If from an anyof the object will be a collection of values,
      // A new vector must union the object values and the values extracted from it.
      if (object instanceof Vector) {
        Vector comparisonVector = new Vector(((Vector) object).size() + 2);
        for (Enumeration valuesToIterate = ((Vector) object).elements();
            valuesToIterate.hasMoreElements(); ) {
          Object vectorObject = valuesToIterate.nextElement();
          if (vectorObject == null) {
            comparisonVector.addElement(vectorObject);
          } else {
            Object valueOrValues =
                valuesFromCollection(
                    vectorObject, session, valueHolderPolicy, isObjectUnregistered);

            // If a collection of values were extracted union them.
            if (valueOrValues instanceof Vector) {
              for (Enumeration nestedValuesToIterate = ((Vector) valueOrValues).elements();
                  nestedValuesToIterate.hasMoreElements(); ) {
                comparisonVector.addElement(nestedValuesToIterate.nextElement());
              }
            } else {
              comparisonVector.addElement(valueOrValues);
            }
          }
        }
        return comparisonVector;
      }
    }
    return valuesFromCollection(object, session, valueHolderPolicy, isObjectUnregistered);
  }
  /**
   * Reset the commit order from the session's descriptors. This uses the constraint dependencies in
   * the descriptor's mappings, to decide which descriptors are dependent on which other
   * descriptors. Multiple computations of the commit order should produce the same ordering. This
   * is done to improve performance on unit of work writes through decreasing the stack size, and
   * acts as a deadlock avoidance mechanism.
   */
  public void initializeCommitOrder() {
    Vector descriptors = Helper.buildVectorFromMapElements(getSession().getDescriptors());

    // Must ensure uniqueness, some descriptor my be register twice for interfaces.
    descriptors = Helper.addAllUniqueToVector(new Vector(descriptors.size()), descriptors);
    Object[] descriptorsArray = new Object[descriptors.size()];
    for (int index = 0; index < descriptors.size(); index++) {
      descriptorsArray[index] = descriptors.elementAt(index);
    }
    Arrays.sort(descriptorsArray, new DescriptorCompare());
    descriptors = new Vector(descriptors.size());
    for (int index = 0; index < descriptorsArray.length; index++) {
      descriptors.addElement(descriptorsArray[index]);
    }

    CommitOrderCalculator calculator = new CommitOrderCalculator(getSession());
    calculator.addNodes(descriptors);
    calculator.calculateMappingDependencies();
    calculator.orderCommits();
    descriptors = calculator.getOrderedDescriptors();

    calculator = new CommitOrderCalculator(getSession());
    calculator.addNodes(descriptors);
    calculator.calculateSpecifiedDependencies();
    calculator.orderCommits();

    setCommitOrder(calculator.getOrderedClasses());
  }
  /**
   * 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;
  }
 public Vector getParentInterfaceNames() {
   if (parentInterfaceNames.isEmpty() && !parentInterfaces.isEmpty()) {
     for (int i = 0; i < parentInterfaces.size(); i++) {
       parentInterfaceNames.addElement(((Class) parentInterfaces.elementAt(i)).getName());
     }
   }
   return parentInterfaceNames;
 }
  public Vector getAttributeFromAll(String attributeName, Vector objects) {
    ClassDescriptor descriptor = getSession().getClassDescriptor(getReferenceClass());
    DirectToFieldMapping mapping =
        (DirectToFieldMapping) descriptor.getMappingForAttributeName(attributeName);

    Vector attributes = new Vector();
    Object currentObject;
    for (int i = 0; i < objects.size(); i++) {
      currentObject = objects.elementAt(i);
      if (currentObject.getClass() == ReportQueryResult.class) {
        attributes.addElement(((ReportQueryResult) currentObject).get(attributeName));
      } else {
        attributes.addElement(mapping.getAttributeValueFromObject(currentObject));
      }
    }
    return attributes;
  }
  public ReadAllBindAllParametersTest() {
    v = new Vector(2);
    v.addElement(new BigDecimal(1001));
    v.addElement(new BigDecimal(1002));

    setName("ReadAllBindAllParametersTest");
    setDescription(
        "Tests all combinations of shouldBindAllParameters attributes on Session and Query");
  }
  /**
   * PUBLIC: Return the foreign key field names associated with the mapping. These are only the
   * source fields that are writable.
   */
  public Vector getForeignKeyFieldNames() {
    Vector fieldNames = new Vector(getForeignKeyFields().size());
    for (Enumeration fieldsEnum = getForeignKeyFields().elements();
        fieldsEnum.hasMoreElements(); ) {
      fieldNames.addElement(((DatabaseField) fieldsEnum.nextElement()).getQualifiedName());
    }

    return fieldNames;
  }
  /** 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;
  }
  /**
   * PUBLIC: Return the foreign key field names associated with the mapping. These are only the
   * source fields that are writable.
   */
  public void setForeignKeyFieldNames(Vector fieldNames) {
    Vector fields =
        org.eclipse.persistence.internal.helper.NonSynchronizedVector.newInstance(
            fieldNames.size());
    for (Enumeration fieldNamesEnum = fieldNames.elements(); fieldNamesEnum.hasMoreElements(); ) {
      fields.addElement(new DatabaseField((String) fieldNamesEnum.nextElement()));
    }

    setForeignKeyFields(fields);
    if (!fields.isEmpty()) {
      setIsForeignKeyRelationship(true);
    }
  }
  /** INTERNAL: Return all the fields populated by this mapping. */
  @Override
  protected Vector collectFields() {
    DatabaseField type = getTypeField();

    // Get a shallow copy of the Vector
    if (type != null) {
      Vector sourceFields = (Vector) getForeignKeyFields().clone();
      sourceFields.addElement(type);
      return sourceFields;
    } else {
      return getForeignKeyFields();
    }
  }
  /** Append the string containing the SQL insert string for the given table. */
  protected SQLCall buildCallWithoutReturning(AbstractSession session) {
    SQLCall call = new SQLCall();
    call.returnNothing();

    Writer writer = new CharArrayWriter(200);
    try {
      writer.write("INSERT ");
      if (getHintString() != null) {
        writer.write(getHintString());
        writer.write(" ");
      }
      writer.write("INTO ");
      writer.write(getTable().getQualifiedNameDelimited(session.getPlatform()));
      writer.write(" (");

      Vector fieldsForTable = new Vector();
      for (Enumeration fieldsEnum = getModifyRow().keys(); fieldsEnum.hasMoreElements(); ) {
        DatabaseField field = (DatabaseField) fieldsEnum.nextElement();
        if (field.getTable().equals(getTable()) || (!field.hasTableName())) {
          fieldsForTable.addElement(field);
        }
      }

      if (fieldsForTable.isEmpty()) {
        throw QueryException.objectToInsertIsEmpty(getTable());
      }

      for (int i = 0; i < fieldsForTable.size(); i++) {
        writer.write(
            ((DatabaseField) fieldsForTable.elementAt(i)).getNameDelimited(session.getPlatform()));
        if ((i + 1) < fieldsForTable.size()) {
          writer.write(", ");
        }
      }
      writer.write(") VALUES (");

      for (int i = 0; i < fieldsForTable.size(); i++) {
        DatabaseField field = (DatabaseField) fieldsForTable.elementAt(i);
        call.appendModify(writer, field);
        if ((i + 1) < fieldsForTable.size()) {
          writer.write(", ");
        }
      }
      writer.write(")");

      call.setSQLString(writer.toString());
    } catch (IOException exception) {
      throw ValidationException.fileError(exception);
    }
    return call;
  }
  /**
   * 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;
  }
  /** Retrieve next page size of objects from the remote cursored stream */
  public Vector cursoredStreamNextPage(
      RemoteCursoredStream remoteCursoredStream,
      ReadQuery query,
      DistributedSession session,
      int pageSize) {
    Transporter transporter = null;
    try {
      transporter =
          getRemoteSessionController()
              .cursoredStreamNextPage(new Transporter(remoteCursoredStream.getID()), pageSize);
    } catch (RemoteException exception) {
      throw CommunicationException.errorInInvocation(exception);
    }

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

    if (!transporter.wasOperationSuccessful()) {
      throw transporter.getException();
    }

    Vector serverNextPageObjects = (Vector) transporter.getObject();
    if (serverNextPageObjects == null) {
      cursoredStreamClose(remoteCursoredStream.getID());
      return null;
    }
    Vector clientNextPageObjects = serverNextPageObjects;
    if (query.isReadAllQuery() && (!query.isReportQuery())) { // could be DataReadQuery
      clientNextPageObjects = new Vector(serverNextPageObjects.size());
      for (Enumeration objEnum = serverNextPageObjects.elements(); objEnum.hasMoreElements(); ) {
        // 2612538 - the default size of Map (32) is appropriate
        Object clientObject =
            session.getObjectCorrespondingTo(
                objEnum.nextElement(),
                transporter.getObjectDescriptors(),
                new IdentityHashMap(),
                (ObjectLevelReadQuery) query);
        clientNextPageObjects.addElement(clientObject);
      }
    }

    return clientNextPageObjects;
  }
  /**
   * INTERNAL: Build and return the nested rows from the specified field value. The field value
   * better be an ARRAY.
   */
  public Vector buildNestedRowsFromFieldValue(Object fieldValue, AbstractSession session)
      throws DatabaseException {

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

    Object[] structs = (Object[]) fieldValue;

    Vector nestedRows = new Vector(structs.length);
    for (int i = 0; i < structs.length; i++) {
      Object[] struct = (Object[]) structs[i];
      if (struct == null) {
        return null;
      }
      nestedRows.addElement(this.buildNestedRowFromFieldValue(struct));
    }
    return nestedRows;
  }
  /** INTERNAL: */
  public Vector getOwnedTables() {
    if ((getMapping() != null) && getMapping().isNestedTableMapping()) {
      Vector nestedTable = null;
      if (shouldQueryToManyRelationship()) {
        nestedTable = (Vector) super.getOwnedTables().clone();
      } else {
        nestedTable = new Vector(1);
      }

      nestedTable.addElement(new NestedTable(this));
      return nestedTable;
    }
    if ((getMapping() != null)
        && (getMapping().isReferenceMapping() || getMapping().isStructureMapping())) {
      return null;
    }

    return super.getOwnedTables();
  }
 /** INTERNAL: Return all the fields */
 public Vector getFields() {
   if (isAttribute()) {
     Vector result = new Vector(1);
     DatabaseField field = getField();
     if (field != null) {
       result.addElement(field);
     }
     return result;
   } else {
     Vector result = new Vector();
     result.addAll(super.getFields());
     if (mapping.isCollectionMapping()) {
       List<DatabaseField> fields =
           mapping.getContainerPolicy().getAllFieldsForMapKey((CollectionMapping) mapping);
       if (fields != null) {
         result.addAll(fields);
       }
     }
     return result;
   }
 }
 /** Returns all the aggregate fields. */
 protected Vector collectFields() {
   Vector fields = new Vector(1);
   fields.addElement(getField());
   return fields;
 }
  public void test() {

    ReadAllQuery query = new ReadAllQuery();
    ScrollableCursor cursor = null;

    try {
      query.setReferenceClass(Employee.class);
      if (TYPE_SCROLL_INSENSITIVE_isSupported && CONCUR_UPDATABLE_isSupported) {
        query.useScrollableCursor(2);
      } else {
        ScrollableCursorPolicy policy = new ScrollableCursorPolicy();
        if (!TYPE_SCROLL_INSENSITIVE_isSupported) {
          policy.setResultSetType(ScrollableCursorPolicy.TYPE_SCROLL_SENSITIVE);
        }
        if (!CONCUR_UPDATABLE_isSupported) {
          policy.setResultSetConcurrency(ScrollableCursorPolicy.CONCUR_READ_ONLY);
        }
        policy.setPageSize(2);
        query.useScrollableCursor(policy);
      }
      //
      if (configuration != null) {
        ExpressionBuilder builder = new ExpressionBuilder();
        Expression exp = builder.get("salary").greaterThan(50000);
        query.setSelectionCriteria(exp);
        query.conformResultsInUnitOfWork();
      }
      cursor = (ScrollableCursor) getSession().executeQuery(query);

      try {
        // test to see if we can iterate through a list and then iterate
        // in reverse through the same list.
        int totalItems = 0;
        while (cursor.hasNext()) {
          readWithNext.addElement(cursor.next());
          totalItems++;
        }
        while (cursor.hasPrevious()) {
          readWithPrevious.addElement(cursor.previous());
          totalItems--;
        }

        cursorSuccess = (totalItems == 0);

        int size = readWithPrevious.size();
        for (int i = 0; i < readWithNext.size(); i++) {
          cursorSuccess =
              (cursorSuccess
                  && (readWithNext.elementAt(i) == readWithPrevious.elementAt((size - 1) - i)));
        }

      } catch (org.eclipse.persistence.exceptions.QueryException ex) {
        caughtException = ex;
      }

    } finally {
      if (cursor != null) {
        cursor.close();
      }
    }
  }
 public void addSupportedPlatform(Class platform) {
   if (supportedPlatforms == null) {
     supportedPlatforms = new Vector();
   }
   supportedPlatforms.addElement(platform);
 }
 public void addUnsupportedPlatform(Class platform) {
   if (unsupportedPlatforms == null) {
     unsupportedPlatforms = new Vector();
   }
   unsupportedPlatforms.addElement(platform);
 }