/** Log the results to the session's log (System.out). */
 public void dumpResults() {
   this.lastDumpTime = System.currentTimeMillis();
   StringWriter writer = new StringWriter();
   writer.write("\nPerformance Monitor:");
   writer.write(String.valueOf(this.lastDumpTime));
   writer.write("\nOperation\tValue (ns)\n");
   Set<String> operations = new TreeSet<String>(this.operationTimings.keySet());
   NumberFormat formater = NumberFormat.getInstance();
   for (String operation : operations) {
     Object value = this.operationTimings.get(operation);
     if (value == null) {
       value = Long.valueOf(0);
     }
     writer.write(operation);
     writer.write("\t");
     if (value instanceof Long) {
       writer.write(formater.format(value));
     } else {
       writer.write(value.toString());
     }
     writer.write("\n");
   }
   try {
     this.session.getLog().write(writer.toString());
     this.session.getLog().flush();
   } catch (IOException error) {
     // ignore
   }
 }
  public void setup() {
    ConcurrentTestRefreshWithOptimisticLocking.execute = true;
    try {
      getSession().getLog().write("WARNING, some tests may take 3 minutes or more");
      getSession().getLog().flush();
    } catch (java.io.IOException e) {
    }

    try {
      DatabaseLogin login = (DatabaseLogin) getSession().getLogin().clone();
      ConcurrentTestRefreshWithOptimisticLocking.server =
          new Server(login, numThreads, numThreads + 2);
      ConcurrentTestRefreshWithOptimisticLocking.server.serverSession.setSessionLog(
          getSession().getSessionLog());
      ConcurrentTestRefreshWithOptimisticLocking.server.login();
      ConcurrentTestRefreshWithOptimisticLocking.server.copyDescriptors(getSession());
      ClassDescriptor empDesc =
          this.server.serverSession.getClassDescriptor(DeadLockEmployee.class);
      this.oldVersionRefresh = empDesc.shouldOnlyRefreshCacheIfNewerVersion();
      empDesc.onlyRefreshCacheIfNewerVersion();

    } catch (ValidationException ex) {
      this.verify();
    }

    for (int count = 0; count < numThreads; ++count) {
      ConcurrentTestRefreshWithOptimisticLocking.threadList[count] =
          new Thread(new ConcurrentTestRefreshWithOptimisticLocking(false, count).runnable());
      ConcurrentTestRefreshWithOptimisticLocking.timeList[count] = System.currentTimeMillis();
    }
  }
 /**
  * PUBLIC: Create a new profiler. The profiler can be registered with a session to log performance
  * information on queries.
  */
 public PerformanceMonitor() {
   this.operationTimings = new Hashtable();
   this.operationStartTimesByThread = new Hashtable();
   this.lastDumpTime = System.currentTimeMillis();
   this.dumpTime = 60000; // 1 minute
   this.profileWeight = SessionProfiler.ALL;
 }
 public void watchOtherThreads() {
   long startTime = System.currentTimeMillis();
   while (((System.currentTimeMillis() - startTime) < (runTime + 30000))
       && ConcurrentTestRefreshWithOptimisticLocking.execute) {
     for (int localIdex = 0; localIdex < numThreads; ++localIdex) {
       if ((System.currentTimeMillis()
               - ConcurrentTestRefreshWithOptimisticLocking.timeList[localIdex])
           > 30000) {
         // System.out.println(" Number: " + localIdex + " time: " + (System.currentTimeMillis() -
         // this.timeList[localIdex]));
         execute = false;
         break;
       }
     }
     try {
       Thread.sleep(30000);
     } catch (InterruptedException ex) {
       throw new TestProblemException("Test thread was interrupted.  Test failed to run properly");
     }
   }
 }
  /** INTERNAL: End the operation timing. */
  public void endOperationProfile(String operationName) {
    if (this.profileWeight < SessionProfiler.HEAVY) {
      return;
    }
    long endTime = System.nanoTime();
    Long startTime = getOperationStartTimes().get(operationName);
    if (startTime == null) {
      return;
    }
    long time = endTime - startTime.longValue();

    synchronized (this.operationTimings) {
      Long totalTime = (Long) this.operationTimings.get(operationName);
      if (totalTime == null) {
        this.operationTimings.put(operationName, Long.valueOf(time));
      } else {
        this.operationTimings.put(operationName, Long.valueOf(totalTime.longValue() + time));
      }
    }
  }
 public void executeUntilStopped() {
   Session session =
       ConcurrentTestRefreshWithOptimisticLocking.server.serverSession.acquireClientSession();
   DeadLockAddress address =
       (DeadLockAddress)
           session.readObject(
               org.eclipse.persistence.testing.tests.clientserver.DeadLockAddress.class);
   DeadLockEmployee employee = (DeadLockEmployee) session.readObject(DeadLockEmployee.class);
   ReadObjectQuery query;
   if ((this.index % 2) != 0) {
     query = new ReadObjectQuery(address);
     query.refreshIdentityMapResult();
     query.setCascadePolicy(DatabaseQuery.CascadeAllParts);
   } else {
     query = new ReadObjectQuery(employee);
     query.refreshIdentityMapResult();
     query.setCascadePolicy(DatabaseQuery.CascadeAllParts);
   }
   while (ConcurrentTestRefreshWithOptimisticLocking.execute) {
     ConcurrentTestRefreshWithOptimisticLocking.timeList[this.index] = System.currentTimeMillis();
     session.executeQuery(query);
   }
   // System.out.println("BeingShutDown");
 }
  public void populate(DatabaseSession session) {
    PopulationManager manager = PopulationManager.getDefaultManager();

    Cat cat = Cat.example1();
    session.writeObject(cat);
    manager.registerObject(cat, "catExample1");

    Dog dog = Dog.example1();
    session.writeObject(dog);
    manager.registerObject(dog, "dogExample1");

    cat = Cat.example2();
    session.writeObject(cat);
    manager.registerObject(cat, "catExample2");

    dog = Dog.example2();
    session.writeObject(dog);
    manager.registerObject(dog, "dogExample2");

    cat = Cat.example3();
    session.writeObject(cat);
    manager.registerObject(cat, "catExample3");

    dog = Dog.example3();
    session.writeObject(dog);
    manager.registerObject(dog, "dogExample3");

    Company company = Company.example1();
    session.writeObject(company);
    manager.registerObject(company, "example1");

    manager.registerObject(((Vector) company.getVehicles().getValue()).firstElement(), "example1");

    company = Company.example2();
    session.writeObject(company);
    manager.registerObject(company, "example2");

    company = Company.example3();
    session.writeObject(company);
    manager.registerObject(company, "example3");

    Person person = Person.example1();
    session.writeObject(person);
    manager.registerObject(person, "example1");

    // populate the data for duplicate field testing
    session.writeObject(A_King2.exp1());
    session.writeObject(A_King2.exp2());
    session.writeObject(A_1_King2.exp3());
    session.writeObject(A_2_King2.exp4());
    session.writeObject(A_2_1_King2.exp5());

    UnitOfWork unitOfWork = session.acquireUnitOfWork();
    person = Person.example2();
    unitOfWork.registerObject(person);
    unitOfWork.commit();
    manager.registerObject(person, "example2");
    manager.registerObject(person.bestFriend, "example5");
    manager.registerObject(person.representitive, "example4");

    person = Person.example3();
    session.writeObject(person);
    manager.registerObject(person, "example3");

    Computer computer = Computer.example1();
    session.writeObject(computer);
    manager.registerObject(computer, "example1");

    computer = Computer.example2();
    session.writeObject(computer);
    manager.registerObject(computer, "example2");

    computer = Computer.example3();
    session.writeObject(computer);
    manager.registerObject(computer, "example3");

    computer = Computer.example4();
    session.writeObject(computer);
    manager.registerObject(computer, "example4");

    computer = Computer.example5();
    session.writeObject(computer);
    manager.registerObject(computer, "example5");

    JavaProgrammer JP = JavaProgrammer.example1();
    session.writeObject(JP);
    manager.registerObject(JP, "example1");

    JP = JavaProgrammer.example2();
    session.writeObject(JP);
    manager.registerObject(JP, "example2");

    // Added to test bug 3019934.
    unitOfWork = session.acquireUnitOfWork();
    Alligator alligator = new Alligator();
    alligator.setFavoriteSwamp("Florida");
    alligator.setLatestVictim(JavaProgrammer.steve());
    unitOfWork.registerObject(alligator);
    manager.registerObject(alligator, "example1");
    unitOfWork.commit();

    // Added to test bug 6111278

    unitOfWork = session.acquireUnitOfWork();
    Entomologist bugguy = new Entomologist();
    bugguy.setId((int) System.currentTimeMillis());
    bugguy.setName("Gary");
    bugguy = (Entomologist) unitOfWork.registerObject(bugguy);
    Insect insect = new GrassHopper();
    insect.setIn_numberOfLegs(4);
    insect.setEntomologist(bugguy);
    bugguy.getInsectCollection().add(insect);
    unitOfWork.commit();
  }
  /**
   * Load the last test result from the test result database. Find only the results run on the same
   * machine and database. Compare the current test run result with the previous results do
   * determine if the test passes or fails.
   */
  public static void verify(PerformanceRegressionTest test) {
    // Ensures all tests pass to reset baseline,
    // Required when tests or environment change to be slower to avoid failures.
    if (reset) {
      throw new TestWarningException("Reseting baseline.");
    }
    Session session = LoadBuildSystem.getSystem().getSession();

    // Query all previous successful test results for this test on the same machine and database.
    // Find only the baseline version, or last version run different than current version.
    // If you need to compare results against the current version you must change the TopLink
    // version string.
    ReadAllQuery query = new ReadAllQuery(TestResult.class);
    ExpressionBuilder result = new ExpressionBuilder();
    query.setSelectionCriteria(
        result
            .get("name")
            .equal(test.getName())
            .and(
                result
                    .get("loadBuildSummary")
                    .get("machine")
                    .equal(LoadBuildSystem.getSummary().getMachine()))
            .and(
                result
                    .get("loadBuildSummary")
                    .get("loginChoice")
                    .equal(LoadBuildSystem.getSummary().getLoginChoice())));
    // Allow comparing to a set version through a system property.
    String currentVersion = LoadBuildSystem.getSummary().getToplinkVersion();
    String baselineVersion = null;
    if (System.getProperties().containsKey("toplink.loadbuild.baseline-version")) {
      baselineVersion = System.getProperties().getProperty("toplink.loadbuild.baseline-version");
      // System properties cannot store spaces so need to replace them from \b.
      baselineVersion = baselineVersion.replace('_', ' ');
      ((PerformanceComparisonTestResult) ((TestCase) test).getTestResult()).baselineVersion =
          baselineVersion;
    } else {
      // Compare against the last successful version.
      ReportQuery reportQuery = new ReportQuery(TestResult.class, query.getExpressionBuilder());
      reportQuery.useDistinct();
      reportQuery.returnSingleValue();
      reportQuery.addAttribute("version", result.get("loadBuildSummary").get("toplinkVersion"));
      reportQuery.setSelectionCriteria(
          query
              .getSelectionCriteria()
              .and(
                  (result.get("outcome").equal(TestResult.PASSED))
                      .or(result.get("outcome").equal(TestResult.WARNING)))
              .and(result.get("loadBuildSummary").get("toplinkVersion").notEqual(currentVersion)));
      reportQuery.addOrdering(result.get("loadBuildSummary").get("timestamp").descending());
      baselineVersion = (String) session.executeQuery(reportQuery);
    }
    query.setSelectionCriteria(
        query
            .getSelectionCriteria()
            .and(result.get("loadBuildSummary").get("toplinkVersion").equal(baselineVersion)));
    query.addOrdering(result.get("loadBuildSummary").get("timestamp").descending());
    query.setMaxRows(10);
    query.useCursoredStream(1, 1);
    CursoredStream stream = (CursoredStream) session.executeQuery(query);
    if (!stream.hasMoreElements()) {
      throw new TestWarningException("No previous test result to compare performance with.");
    }
    TestResult lastResult = (TestResult) stream.nextElement();
    double lastCount = lastResult.getTestTime();
    PerformanceComparisonTestResult testResult =
        (PerformanceComparisonTestResult) ((TestCase) test).getTestResult();
    testResult.getBaselineVersionResults().add(new Double(lastCount));
    // Average last 5 runs.
    int numberOfRuns = 0;
    while (stream.hasMoreElements() && (numberOfRuns < 4)) {
      TestResult nextResult = (TestResult) stream.nextElement();
      testResult.getBaselineVersionResults().add(new Double(nextResult.getTestTime()));
      numberOfRuns++;
    }
    stream.close();
    double baselineAverage =
        PerformanceComparisonTestResult.averageResults(testResult.getBaselineVersionResults());
    double currentCount = ((TestCase) test).getTestResult().getTestTime();
    testResult.baselineVersion = lastResult.getLoadBuildSummary().getToplinkVersion();
    testResult.percentageDifferenceLastRun =
        PerformanceComparisonTestResult.percentageDifference(currentCount, lastCount);

    // Query the current version last 5 runs for averaging.
    query = new ReadAllQuery(TestResult.class);
    result = new ExpressionBuilder();
    query.setSelectionCriteria(
        result
            .get("name")
            .equal(((TestCase) test).getName())
            .and(
                result
                    .get("loadBuildSummary")
                    .get("machine")
                    .equal(LoadBuildSystem.getSummary().getMachine()))
            .and(
                result
                    .get("loadBuildSummary")
                    .get("loginChoice")
                    .equal(LoadBuildSystem.getSummary().getLoginChoice()))
            .and(result.get("loadBuildSummary").get("toplinkVersion").equal(currentVersion)));
    query.addOrdering(result.get("loadBuildSummary").get("timestamp").descending());
    query.useCursoredStream(1, 1);
    stream = (CursoredStream) session.executeQuery(query);
    // Average last 5 runs.
    testResult.getCurrentVersionResults().add(new Double(currentCount));
    numberOfRuns = 0;
    while (stream.hasMoreElements() && (numberOfRuns < 4)) {
      TestResult nextResult = (TestResult) stream.nextElement();
      testResult.getCurrentVersionResults().add(new Double(nextResult.getTestTime()));
      numberOfRuns++;
    }
    stream.close();
    double currentAverage =
        PerformanceComparisonTestResult.averageResults(testResult.getCurrentVersionResults());
    testResult.percentageDifferenceAverage =
        PerformanceComparisonTestResult.percentageDifference(currentAverage, baselineAverage);

    testResult.baselineStandardDeviation =
        PerformanceComparisonTestResult.standardDeviationResults(
            testResult.getBaselineVersionResults());
    testResult.currentStandardDeviation =
        PerformanceComparisonTestResult.standardDeviationResults(
            testResult.getCurrentVersionResults());

    if (testResult.percentageDifferenceAverage < test.getAllowableDecrease()) {
      throw new TestErrorException(
          "Test is "
              + ((long) testResult.percentageDifferenceAverage)
              + "% slower than last successful execution.");
    }
  }
 /** Log the results after a set amount of time has passed. */
 public void checkDumpTime() {
   if ((System.currentTimeMillis() - this.lastDumpTime) > this.dumpTime) {
     dumpResults();
   }
 }
 /** INTERNAL: Start the operation timing. */
 public void startOperationProfile(String operationName) {
   getOperationStartTimes().put(operationName, Long.valueOf(System.nanoTime()));
 }