/* (non-Javadoc)
   * @see com.microstrategy.mfloadtest.jdbcwriter.BaseTestListener#testEnded()
   */
  @Override
  public void testEnded() {

    // this can only come from 1 thread
    final Timestamp lTimeStamp = new Timestamp(new Date().getTime());

    // do unconditionally
    mTrendLineTimer.cancel();

    try {

      final TestJobAgentWorker lAgent = mAgentProvider.get();

      lAgent.setEndTimestamp(lTimeStamp);
      lAgent.setLastNumberOfActiveThreads(0l);

      mAgentUpdater.write(lAgent);
      mSWriter.flush();
      mSWriter.close();
      mAgentUpdateThread.interrupt();

    } catch (Exception e) {
      LOGGER.error("testEnded", e);
      throw new RuntimeException("testEnded", e);
    }
  }
  private void updateAgent() {

    // We need to write the agent to the db,
    // We'll potentially need to retry due to possible database locking
    // so we use the JPAAgentUpdater that already knows
    // how to do this
    try {
      // initial agent parameters
      final TestJobAgentWorker lAgent = mAgentProvider.get();

      LOGGER.info("Successfully retrieved agent " + lAgent);

      if (lAgent.getProcessID() != null) {
        LOGGER.info(
            "Process succsesfully retrieved "
                + lAgent.getProcessID()
                + ". Stopping agent update thread");

        mAgentUpdateThread.interrupt();
        return;
      }

      LOGGER.info("PID not yet set, retrieving and updating");
      configureAgentInitialParameters(lAgent);
      LOGGER.info("Updating agent");

      mAgentUpdater.write(lAgent);
    } catch (Exception e) {
      LOGGER.error("Couldn't write the agent", e);
    }
  }
  private void configureAgentInitialParameters(final TestJobAgentWorker lAgent)
      throws UnknownHostException {

    lAgent.setTimeBound(mTimeBound);
    lAgent.setThreadNumber(mAgentThreadCount);
    lAgent.setTargetWebServer(mTargetWebServer);
    HibernateUtils.setMachineData(lAgent);
    lAgent.setStartTimestamp(mStartTimeStamp);
    lAgent.setComputationalInterval(mTrendLinePeriod);
  }