/** INTERNAL: */
 protected Vector<DatabaseField> getVectorOfFieldsToGenerate(int operation, DatabaseTable table) {
   if (this.main[operation][ALL] == null) {
     return null;
   }
   if (this.tableToFieldsForGenerationMap == null) {
     // the method is called for the first time
     tableToFieldsForGenerationMap = new HashMap[NUM_OPERATIONS];
   }
   if (this.tableToFieldsForGenerationMap[operation] == null) {
     // the method is called for the first time for this operation
     this.tableToFieldsForGenerationMap[operation] = new HashMap();
   }
   Vector<DatabaseField> fieldsForGeneration =
       this.tableToFieldsForGenerationMap[operation].get(table);
   if (fieldsForGeneration == null) {
     // the method is called for the first time for this operation and this table
     fieldsForGeneration = new NonSynchronizedVector();
     Iterator it = this.main[operation][ALL].iterator();
     while (it.hasNext()) {
       DatabaseField field = (DatabaseField) it.next();
       if (field.getTable().equals(table)) {
         fieldsForGeneration.add(field);
       }
     }
     this.tableToFieldsForGenerationMap[operation].put(table, fieldsForGeneration);
   }
   return fieldsForGeneration;
 }
 /**
  * INTERNAL: Convert all the class-name-based settings in this InheritancePolicy 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. It will also convert referenced classes to the versions
  * of the classes from the classLoader.
  */
 public void convertClassNamesToClasses(ClassLoader classLoader) {
   Vector newParentInterfaces = new Vector();
   for (Iterator iterator = getParentInterfaceNames().iterator(); iterator.hasNext(); ) {
     String interfaceName = (String) iterator.next();
     Class interfaceClass = null;
     try {
       if (PrivilegedAccessHelper.shouldUsePrivilegedAccess()) {
         try {
           interfaceClass =
               (Class)
                   AccessController.doPrivileged(
                       new PrivilegedClassForName(interfaceName, true, classLoader));
         } catch (PrivilegedActionException exception) {
           throw ValidationException.classNotFoundWhileConvertingClassNames(
               interfaceName, exception.getException());
         }
       } else {
         interfaceClass =
             org.eclipse.persistence.internal.security.PrivilegedAccessHelper.getClassForName(
                 interfaceName, true, classLoader);
       }
     } catch (ClassNotFoundException exc) {
       throw ValidationException.classNotFoundWhileConvertingClassNames(interfaceName, exc);
     }
     newParentInterfaces.add(interfaceClass);
   }
   this.parentInterfaces = newParentInterfaces;
 }
  /**
   * Return the first employee that has a long enough name for the test. If no match is found throw
   * a warning exception. See bug 223005
   *
   * @param vectorOfEmployees
   * @param minFirstNameLength
   * @param testName
   * @return
   */
  public Employee getEmployeeWithRequiredNameLength(
      Vector vectorOfEmployees, int minFirstNameLength, String testName) {
    Employee empMatch = null;
    Vector<Employee> employees = vectorOfEmployees;
    String firstName;
    StringBuffer partialFirstName;

    // Loop through the collection of employees to find one that matches our test requirements
    for (int i = 0; i < employees.size(); i++) {
      empMatch = employees.get(i);
      firstName = empMatch.getFirstName();
      // Verify length criteria
      if (firstName.length() >= minFirstNameLength) {
        // exit the for loop - return the last empMatch
        i = employees.size();
      }
    }

    // If we could not find a proper employee for testing - throw a warning
    if (null == empMatch) {
      throw new RuntimeException(
          testName
              + " Setup Failed: unable to find an Employee with firstName size of at least  "
              + minFirstNameLength);
    } else {
      return empMatch;
    }
  }
  public void setup() {
    Employee emp1;
    Employee emp2;
    Employee emp3;
    emp1 = (Employee) getSomeEmployees().firstElement();
    emp2 = (Employee) getSomeEmployees().elementAt(1);
    emp3 = (Employee) getSomeEmployees().elementAt(2);

    ExpressionBuilder builder = new ExpressionBuilder();

    Vector idVector = new Vector();
    idVector.add(emp1.getId());
    idVector.add(emp2.getId());
    idVector.add(emp3.getId());

    Expression whereClause = builder.get("id").notIn(idVector);

    ReadAllQuery raq = new ReadAllQuery();
    raq.setReferenceClass(Employee.class);
    raq.setSelectionCriteria(whereClause);

    setOriginalOject(getSession().executeQuery(raq));
    getSession().getIdentityMapAccessor().initializeAllIdentityMaps();

    String ejbqlString = "SELECT OBJECT(emp) FROM Employee emp WHERE emp.id NOT IN (";
    ejbqlString = ejbqlString + emp1.getId().toString() + ", ";
    ejbqlString = ejbqlString + emp2.getId().toString() + ", ";
    ejbqlString = ejbqlString + emp3.getId().toString();
    ejbqlString = ejbqlString + ")";

    setEjbqlString(ejbqlString);

    super.setup();
  }
  public void setup() {
    Vector employees = getSomeEmployees();
    // Bug 223005: Verify that we have at least 1 employee with the required field length otherwise
    // an EclipseLinkException will be thrown
    Employee emp = getEmployeeWithRequiredNameLength(employees, MIN_FIRSTNAME_LENGTH, getName());

    String partialFirstName = "%" + emp.getFirstName().substring(0, 3) + "%";

    ReadAllQuery raq = new ReadAllQuery();
    raq.setReferenceClass(Employee.class);

    Vector parameters = new Vector();
    parameters.add(partialFirstName);

    ExpressionBuilder eb = new ExpressionBuilder();
    Expression whereClause = eb.get("firstName").like(partialFirstName);
    raq.setSelectionCriteria(whereClause);
    employees = (Vector) getSession().executeQuery(raq);

    String ejbqlString = "SELECT OBJECT(emp) FROM Employee emp WHERE emp.firstName LIKE ?1";

    setEjbqlString(ejbqlString);
    setOriginalOject(employees);
    setArguments(parameters);

    Vector myArgumentNames = new Vector();
    myArgumentNames.add("1");
    setArgumentNames(myArgumentNames);

    super.setup();
  }
 /** A clean way to specify which tests run on which platforms. */
 public boolean isPlatformSupported(DatabasePlatform platform) {
   boolean supported = false;
   boolean notSupported = false;
   if ((unsupportedPlatforms == null) && (supportedPlatforms == null)) {
     return true;
   }
   if (supportedPlatforms != null) {
     for (Iterator iterator = supportedPlatforms.iterator(); iterator.hasNext(); ) {
       Class platformClass = (Class) iterator.next();
       if (platformClass.isInstance(platform)) {
         supported = true;
       }
     }
   } else {
     supported = true;
   }
   if (unsupportedPlatforms != null) {
     for (Iterator iterator = unsupportedPlatforms.iterator(); iterator.hasNext(); ) {
       Class platformClass = (Class) iterator.next();
       if (platformClass.isInstance(platform)) {
         notSupported = true;
       }
     }
   }
   return supported && (!notSupported);
 }
  protected void buildExpectedResults() {
    Vector employees = getSession().readAllObjects(Employee.class);

    Object[] result = new Object[1];
    result[0] = new java.math.BigDecimal(employees.size());
    addResult(result, 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: 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: Build and return the appropriate field value for the specified set of nested rows.
   * The database better be expecting an ARRAY. It looks like we can ignore inheritance here....
   */
  public Object buildFieldValueFromNestedRows(
      Vector nestedRows, String structureName, AbstractSession session) throws DatabaseException {
    Object[] fields = new Object[nestedRows.size()];
    java.sql.Connection connection = ((DatabaseAccessor) session.getAccessor()).getConnection();
    boolean reconnected = false;

    try {
      if (connection == null) {
        ((DatabaseAccessor) session.getAccessor()).incrementCallCount(session);
        reconnected = true;
        connection = ((DatabaseAccessor) session.getAccessor()).getConnection();
      }

      int i = 0;
      for (Enumeration stream = nestedRows.elements(); stream.hasMoreElements(); ) {
        AbstractRecord nestedRow = (AbstractRecord) stream.nextElement();
        fields[i++] = this.buildStructureFromRow(nestedRow, session, connection);
      }

      return session.getPlatform().createArray(structureName, fields, session, connection);
    } catch (java.sql.SQLException exception) {
      throw DatabaseException.sqlException(exception, session, false);
    } finally {
      if (reconnected) {
        ((DatabaseAccessor) session.getAccessor()).decrementCallCount();
      }
    }
  }
  public static BinaryOperatorWithParameterTest
      getNumericParameterDivideTestWithBracketsAfterComparison() {
    BinaryOperatorWithParameterTest theTest = new BinaryOperatorWithParameterTest();
    theTest.setName("Divide with parameter test with brackets after comparison");

    String parameterName = "amountToDivide";
    theTest.setExpressionParameters(new Vector());
    theTest.getExpressionParameters().add(parameterName);

    ExpressionBuilder builder = new ExpressionBuilder();
    Expression whereClause =
        ExpressionBuilder.fromConstant(new Integer(20000), builder)
            .greaterThan(
                ExpressionMath.divide(
                    builder.get("salary"), (builder.getParameter(parameterName))));
    theTest.setOriginalObjectExpression(whereClause);

    String ejbqlString = "SELECT OBJECT(emp) FROM Employee emp WHERE 20000 > (emp.salary / ?1)";

    theTest.setEjbqlString(ejbqlString);
    Vector myArgumentNames = new Vector();
    myArgumentNames.add("1");
    theTest.setArgumentNames(myArgumentNames);

    theTest.setArguments(new Vector());
    theTest.getArguments().addElement(new Integer(2));

    return theTest;
  }
  public static BinaryOperatorWithParameterTest getNumericParameterDivideTest() {
    BinaryOperatorWithParameterTest theTest = new BinaryOperatorWithParameterTest();
    theTest.setName("Divide with parameter test");

    String parameterName = "amountToDivide";
    theTest.setExpressionParameters(new Vector());
    theTest.getExpressionParameters().add(parameterName);

    ExpressionBuilder builder = new ExpressionBuilder();
    Expression whereClause =
        ExpressionMath.divide(builder.get("salary"), (builder.getParameter(parameterName)))
            .lessThanEqual(20000);
    theTest.setOriginalObjectExpression(whereClause);

    String ejbqlString = "SELECT OBJECT(emp) FROM Employee emp WHERE emp.salary / ?1 <= 20000";

    theTest.setEjbqlString(ejbqlString);
    Vector myArgumentNames = new Vector();
    myArgumentNames.add("1");
    theTest.setArgumentNames(myArgumentNames);

    theTest.setArguments(new Vector());
    theTest.getArguments().addElement(new Integer(2));

    return theTest;
  }
  public static BinaryOperatorWithParameterTest
      getNumericParameterMultiplyTestWithBracketsBeforeComparison() {
    BinaryOperatorWithParameterTest theTest = new BinaryOperatorWithParameterTest();
    theTest.setName("Multiply with parameter test with brackets before comparison");

    String parameterName = "amountToMultiply";
    theTest.setExpressionParameters(new Vector());
    theTest.getExpressionParameters().add(parameterName);

    ExpressionBuilder builder = new ExpressionBuilder();
    Expression whereClause =
        ExpressionMath.multiply(builder.get("salary"), (builder.getParameter(parameterName)))
            .lessThanEqual(100000);
    theTest.setOriginalObjectExpression(whereClause);

    String ejbqlString = "SELECT OBJECT(emp) FROM Employee emp WHERE (emp.salary * ?1) <= 100000";

    theTest.setEjbqlString(ejbqlString);
    Vector myArgumentNames = new Vector();
    myArgumentNames.add("1");
    theTest.setArgumentNames(myArgumentNames);

    theTest.setArguments(new Vector());
    theTest.getArguments().addElement(new Integer(2));

    return theTest;
  }
 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: 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: Set a collection of the source to target query key/field associations. */
 public void setSourceToTargetQueryKeyFieldAssociations(
     Vector sourceToTargetQueryKeyFieldAssociations) {
   setSourceToTargetQueryKeyFields(
       new HashMap(sourceToTargetQueryKeyFieldAssociations.size() + 1));
   for (Enumeration associationsEnum = sourceToTargetQueryKeyFieldAssociations.elements();
       associationsEnum.hasMoreElements(); ) {
     Association association = (Association) associationsEnum.nextElement();
     Object sourceField = new DatabaseField((String) association.getKey());
     String targetQueryKey = (String) association.getValue();
     getSourceToTargetQueryKeyNames().put(sourceField, targetQueryKey);
   }
 }
Esempio n. 18
0
  protected void buildExpectedResults() {
    Vector projects = getSession().readAllObjects(LargeProject.class);

    for (Enumeration e = projects.elements(); e.hasMoreElements(); ) {
      LargeProject project = (LargeProject) e.nextElement();
      if (project.getBudget() > 4000) {
        Object[] result = new Object[2];
        result[0] = project.getName();
        result[1] = new Double(project.getBudget());
        addResult(result, null);
      }
    }
  }
  /** 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();
    }
  }
  /**
   * 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 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);
  }
 /** PUBLIC: Set the class indicator associations. */
 public void setClassIndicatorAssociations(Vector classIndicatorAssociations) {
   setTypeIndicatorNameTranslation(new HashMap(classIndicatorAssociations.size() + 1));
   setTypeIndicatorTranslation(new HashMap((classIndicatorAssociations.size() * 2) + 1));
   for (Enumeration associationsEnum = classIndicatorAssociations.elements();
       associationsEnum.hasMoreElements(); ) {
     Association association = (Association) associationsEnum.nextElement();
     Object classValue = association.getKey();
     if (classValue instanceof Class) {
       // 904 projects will be a class type.
       addClassIndicator((Class) association.getKey(), association.getValue());
     } else {
       addClassNameIndicator((String) association.getKey(), association.getValue());
     }
   }
 }
Esempio n. 23
0
  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;
  }
  /**
   * 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;
  }
  /** 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;
  }
 /**
  * Verify that the query ran successfully, and that the number of objects returned matches the
  * number of managed employees.
  */
 protected void verify() throws Exception {
   Vector params = new Vector();
   params.add(someManager.getId()); // numberOfManagedEmployees
   try {
     Vector results = (Vector) getSession().executeQuery(query, params);
     if (!(numberOfManagedEmployees == results.size())) {
       throw new TestErrorException(
           results.size()
               + " objects were read from the database, but originially there were, "
               + numberOfManagedEmployees
               + ".");
     }
   } catch (org.eclipse.persistence.exceptions.DatabaseException e) {
     throw new TestErrorException(
         "Custom SQL subquery with parameters failed with a DatabaseException.");
   }
 }
  /**
   * 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());
  }
  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");
  }
  /*
   * This verify method presumes that the stored procedure in EmployeeCustomSQLSystem.buildSQLInsertProcedure
   * has not changed and still returns an output parameter VERSION with value 952
   */
  public void verify() {
    if (this.events.isEmpty()) {
      throw new TestErrorException("No session events were thrown and some were expected");
    } else {
      if (((Number)
                  ((DatabaseRecord) ((SessionEvent) events.firstElement()).getResult())
                      .get("EMPLOYEE.VERSION"))
              .intValue()
          != 952) {
        throw new TestErrorException("Wrong value returned");
      }

      if (((WriteObjectQuery) ((SessionEvent) events.firstElement()).getQuery()).getObject()
          == null) {
        throw new TestErrorException("Object not set");
      }
    }
  }
Esempio n. 30
0
  /** 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;
  }