private ComputerInfo buildComputerInfo(int refID) {
    TestStruct ts = new TestStruct();
    ts.setD((double) 2);
    ts.setF((float) 3);
    ts.setI64((long) 4);
    ts.setI321(1);
    ts.setI322(2);
    ts.setS(svcObjFact.createTestStructS(""));

    ComputerInfo info = new ComputerInfo();
    info.setRefID(refID);
    String machineName;
    try {
      machineName = InetAddress.getLocalHost().getHostName();
    } catch (UnknownHostException e) {
      machineName = "";
    }
    info.setName(svcObjFact.createComputerInfoName(machineName));
    info.setJobID(jobid);
    info.setTaskID(taskid);
    info.setScheduler(svcObjFact.createComputerInfoScheduler(scheduler));
    info.setProcessId(this.processId);
    try {
      info.setCallIn(Utility.getXMLCurrentTime());
    } catch (DatatypeConfigurationException e1) {
      e1.printStackTrace();
      System.exit(1);
    }
    info.setTs(ts);
    return info;
  }
 @Override
 public void OnExiting(Sender sender, SOAEventArg soaEventArg) {
   try {
     Thread.sleep(exitDelay);
     String onAzureEnv = System.getenv("CCP_OnAzure");
     if (!Utility.isNullOrEmpty(onAzureEnv)
         && !onAzureEnv.equals("1")
         && Utility.isNullOrEmpty(logPath)) {
       String taskInfo =
           String.format(
               "%s.%s.%s",
               System.getenv(EnvVarNames.CCP_JOBID),
               System.getenv(EnvVarNames.CCP_TASKID),
               System.getenv(EnvVarNames.CCP_TASKINSTANCEID));
       writeLog(
           logPath + "\\CCP_AITest_Trace_" + String.valueOf(jobid),
           refID,
           "[Request] %s%%%s%%Svchost called.",
           Utility.getCurrentTime(),
           taskInfo);
     }
     System.out.format("[Exit] %s: GracefulExitEvent called.%n", Utility.getCurrentTime());
     info.setOnExitCalled(true);
   } catch (Exception e) {
     e.printStackTrace();
   }
 }
  /*
   * (non-Javadoc)
   *
   * @see org.tempuri.ITestService#echoWithParam(java.lang.Integer refID
   * ,)java.lang.Double d ,)java.lang.Float f ,)java.lang.Long i64
   * ,)java.lang.Integer i321 ,)java.lang.Integer i322
   * ,)org.datacontract.schemas._2004._07.services.TestEnum e
   * ,)java.lang.String s )*
   */
  public org.datacontract.schemas._2004._07.services.ComputerInfo echoWithParam(
      java.lang.Integer refID,
      java.lang.Double d,
      java.lang.Float f,
      java.lang.Long i64,
      java.lang.Integer i321,
      java.lang.Integer i322,
      org.datacontract.schemas._2004._07.services.TestEnum e,
      java.lang.String s) {
    ServiceContext.Logger.traceEvent(Level.ALL, "Executing operation echoWithParam");
    try {
      TestStruct ts = new TestStruct();
      ts.setD(d);
      ts.setF(f);
      ts.setI64(i64);
      ts.setI321(i321);
      ts.setI322(i322);
      ts.setE(e);
      ts.setS(svcObjFact.createTestStructS(s));

      Sub sub = new Sub();
      sub.setSubE(e);
      sub.setSubF(f);
      sub.setSubI(i321);
      sub.setSubS(svcObjFact.createSubSubS(s));

      ComputerInfo info = new ComputerInfo();

      info.setRefID(refID);
      String computername = InetAddress.getLocalHost().getHostName();
      info.setName(svcObjFact.createComputerInfoName(computername));
      info.setJobID(jobid);
      info.setTaskID(taskid);
      info.setScheduler(svcObjFact.createComputerInfoScheduler(scheduler));
      info.setCallIn(Utility.getXMLCurrentTime());

      info.setTs(ts);
      org.datacontract.schemas._2004._07.services.ObjectFactory fact =
          new org.datacontract.schemas._2004._07.services.ObjectFactory();
      info.setSub(fact.createComputerInfoSub(sub));

      return info;
    } catch (java.lang.Exception ex) {
      ex.printStackTrace();
      throw new RuntimeException(ex);
    }
  }
  /*
   * (non-Javadoc)
   *
   * @see org.tempuri.ITestService#echoWithOnExit(java.lang.Integer refID
   * ,)javax.xml.datatype.Duration runTime ,)javax.xml.datatype.Duration
   * exitDelay ,)java.lang.String logPath )*
   */
  public org.datacontract.schemas._2004._07.services.ComputerInfo echoWithOnExit(
      java.lang.Integer refID,
      javax.xml.datatype.Duration runTime,
      javax.xml.datatype.Duration exitDelay,
      java.lang.String logPath) {
    ServiceContext.Logger.traceEvent(Level.ALL, "Executing operation echoWithOnExit");

    try {
      System.out.println("Start call " + refID.toString());
      ComputerInfo info = echo(refID);
      String taskInfo =
          String.format(
              "%s.%s.%s",
              System.getenv(EnvVarNames.CCP_JOBID),
              System.getenv(EnvVarNames.CCP_TASKID),
              System.getenv(EnvVarNames.CCP_TASKINSTANCEID));
      boolean isOnAzure =
          System.getenv(EnvVarNames.CCP_ONAZURE) != null
              && System.getenv(EnvVarNames.CCP_ONAZURE).equals("1");
      if (!isOnAzure && !Utility.isNullOrEmpty(logPath)) {
        writeLog(
            logPath + "\\CCP_AITest_Trace_" + String.valueOf(jobid),
            refID,
            "[Request] %s%%%s%%Svchost called.",
            Utility.getCurrentTime(),
            taskInfo);
      }
      System.out.format("[Request] %s%%%s%%Svchost called.%n", Utility.getCurrentTime(), taskInfo);
      EchoWithOnExitHandler onExit =
          new EchoWithOnExitHandler(exitDelay.getTimeInMillis(new Date()), logPath, refID, info);
      ServiceContext.exitingEvents.addMyEventListener(onExit);
      Thread.sleep(runTime.getTimeInMillis(new Date()));
      if (!info.isOnExitCalled()) {
        ServiceContext.exitingEvents.removedMyEventListener(onExit);
      }
      return info;
    } catch (java.lang.Exception ex) {
      ex.printStackTrace();
      throw new RuntimeException(ex);
    }
  }
  /*
   * (non-Javadoc)
   *
   * @see org.tempuri.ITestService#echoStruct(java.lang.Integer refID
   * ,)org.datacontract.schemas._2004._07.services.TestStruct s )*
   */
  public org.datacontract.schemas._2004._07.services.ComputerInfo echoStruct(
      java.lang.Integer refID, org.datacontract.schemas._2004._07.services.TestStruct s) {
    ServiceContext.Logger.traceEvent(Level.ALL, "Executing operation echoStruct");
    try {
      ComputerInfo info = new ComputerInfo();

      info.setRefID(refID);
      String computername = InetAddress.getLocalHost().getHostName();
      info.setName(svcObjFact.createComputerInfoName(computername));
      info.setJobID(jobid);
      info.setTaskID(taskid);
      info.setScheduler(svcObjFact.createComputerInfoScheduler(scheduler));
      info.setCallIn(Utility.getXMLCurrentTime());

      info.setTs(s);
      return info;
    } catch (java.lang.Exception ex) {
      ex.printStackTrace();
      throw new RuntimeException(ex);
    }
  }
  /* (non-Javadoc)
   * @see org.tempuri.ITestService#trace(java.lang.Integer  refID ,)com.microsoft.schemas._2003._10.serialization.arrays.ArrayOfstring  traceMsgs ,)javax.xml.datatype.Duration  sleepBeforeTrace ,)javax.xml.datatype.Duration  sleepAfterTrace ,)java.lang.Integer  testActionId )*
   */
  public org.datacontract.schemas._2004._07.services.ComputerInfo trace(
      java.lang.Integer refID,
      com.microsoft.schemas._2003._10.serialization.arrays.ArrayOfstring traceMsgs,
      javax.xml.datatype.Duration sleepBeforeTrace,
      javax.xml.datatype.Duration sleepAfterTrace,
      java.lang.Integer testActionId)
      throws ITestServiceTraceRetryOperationErrorFaultFaultMessage,
          ITestServiceTraceOutOfMemoryExceptionFaultFaultMessage {
    LOG.info("Executing operation trace");
    ETWTraceEvent etw = new ETWTraceEvent(wsContext);
    etw.TraceEvent(
        JavaTraceLevelConverterEnum.Verbose, refID, "[HpcServiceHost]: Request is received.");
    Date callIn = new Date();

    etw.TraceEvent(JavaTraceLevelConverterEnum.Verbose, refID, "CallIn:" + callIn.toString());
    ComputerInfo info = buildComputerInfo(refID);

    try {
      info.setCallIn(Utility.convertXMLGregorianCalendar(callIn));
    } catch (DatatypeConfigurationException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }

    if (TracingTestActionId.fromInteger(testActionId) == TracingTestActionId.TraceFaultException) {
      etw.TraceEvent(JavaTraceLevelConverterEnum.Error, refID, "ThrowFaultException");
      etw.TraceEvent(
          JavaTraceLevelConverterEnum.Verbose,
          refID,
          "[HpcServiceHost]: Response is sent back. IsFault = True");
      OutOfMemoryException err = new OutOfMemoryException();
      throw new ITestServiceTraceOutOfMemoryExceptionFaultFaultMessage("Testing fault.", err);

    } else if (TracingTestActionId.fromInteger(testActionId)
        == TracingTestActionId.RetryOperationError) {
      etw.TraceEvent(JavaTraceLevelConverterEnum.Error, refID, "ThrowRetryOperationError");
      etw.TraceEvent(
          JavaTraceLevelConverterEnum.Verbose,
          refID,
          "[HpcServiceHost]: Response is sent back. IsFault = True");
      RetryOperationError err = new RetryOperationError();
      throw new ITestServiceTraceRetryOperationErrorFaultFaultMessage(
          "Testting RetryOperationError.", err);
    } else if (TracingTestActionId.fromInteger(testActionId)
        == TracingTestActionId.TraceProcessExit) {
      etw.TraceEvent(JavaTraceLevelConverterEnum.Error, refID, "ProcessExit");
      etw.Flush();
      Utility.sleep(20 * 1000);
      Runtime.getRuntime().exit(refID);
      //            System.exit(refID);
    } else if (TracingTestActionId.fromInteger(testActionId) == TracingTestActionId.NoUserTrace) {
      try {
        info.setCallOut(Utility.convertXMLGregorianCalendar(new Date()));
        etw.TraceEvent(
            JavaTraceLevelConverterEnum.Verbose, refID, "CallOut:" + info.getCallOut().toString());
        return info;
      } catch (DatatypeConfigurationException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
    }
    try {
      Thread.sleep(sleepBeforeTrace.getTimeInMillis(new Date()));
    } catch (InterruptedException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
    int count = 1;
    if (TracingTestActionId.fromInteger(testActionId) == TracingTestActionId.TraceLargeAmount) {
      count = 10000 / traceMsgs.getString().size();
    }
    for (int i = 0; i < count; i++) {
      for (String traceMsg : traceMsgs.getString()) {
        String[] splitters = traceMsg.split("\\|", 5);
        int iTracingType = Integer.parseInt(splitters[0]);
        int iEventType = Integer.parseInt(splitters[1]);
        int eventId = Integer.parseInt(splitters[2]);
        int sleepTime = Integer.parseInt(splitters[3]);
        String msg = splitters[4];
        TracingType tracingType = TracingType.fromInteger(iTracingType);
        JavaTraceLevelConverterEnum eventType =
            JavaTraceLevelConverterEnum.convertFromInteger(iEventType);
        if (tracingType == TracingType.TraceEvent) {
          etw.TraceEvent(eventType, eventId, msg);
          if (TracingTestActionId.fromInteger(testActionId)
              == TracingTestActionId.TraceRequestProcessing) {
            etw.Flush();
          }
        } else if (tracingType == TracingType.TraceInformation) {
          etw.TraceInformation(msg);
          if (TracingTestActionId.fromInteger(testActionId)
              == TracingTestActionId.TraceRequestProcessing) {
            etw.Flush();
          }
        } else if (tracingType == TracingType.TraceData) {
          if (TracingTestActionId.fromInteger(testActionId) == TracingTestActionId.TraceBigSize) {
            StringBuffer data = new StringBuffer();
            for (int j = 0; j < 63 * 512; j++) {
              data.append('0');
            }
            etw.TraceData(eventType, eventId, data);
            if (TracingTestActionId.fromInteger(testActionId)
                == TracingTestActionId.TraceRequestProcessing) {
              etw.Flush();
            }
            for (int j = 0; j < 2 * 512; j++) {
              data.append('1');
            }
            etw.TraceData(eventType, eventId, data);
            if (TracingTestActionId.fromInteger(testActionId)
                == TracingTestActionId.TraceRequestProcessing) {
              etw.Flush();
            }
          } else {
            TraceDataObj data = new TraceDataObj(msg);
            etw.TraceData(eventType, eventId, data);
            if (TracingTestActionId.fromInteger(testActionId)
                == TracingTestActionId.TraceRequestProcessing) {
              etw.Flush();
            }
          }
        } else if (tracingType == TracingType.TraceTransfer) {
          etw.TraceTransfer(eventId, msg, UUID.randomUUID());
        }
        Utility.sleep(sleepTime);
      }
    }
    Utility.sleep(sleepAfterTrace.getTimeInMillis(new Date()));
    try {
      info.setCallOut(Utility.convertXMLGregorianCalendar(new Date()));
    } catch (DatatypeConfigurationException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
    etw.TraceEvent(
        JavaTraceLevelConverterEnum.Verbose, refID, "CallOut:" + info.getCallOut().toString());
    etw.TraceEvent(
        JavaTraceLevelConverterEnum.Verbose,
        refID,
        "[HpcServiceHost]: Response is sent back. IsFault = False");
    return info;
  }
  /*
   * (non-Javadoc)
   *
   * @see org.tempuri.ITestService#echo(java.lang.Integer refID )*
   */
  public org.datacontract.schemas._2004._07.services.ComputerInfo echo(java.lang.Integer refID)
      throws ITestServiceEchoAuthenticationFailureFaultFaultMessage,
          ITestServiceEchoRetryOperationErrorFaultFaultMessage {
    ServiceContext.Logger.traceEvent(Level.ALL, "Executing operation echo");

    TestStruct ts = new TestStruct();
    ts.setD(2d);
    ts.setF(3f);
    ts.setI64(4l);
    ts.setI321(1);
    ts.setI322(2);
    ts.setS(svcObjFact.createTestStructS(""));

    ComputerInfo info = new ComputerInfo();
    info.setRefID(refID);
    String machineName;
    try {
      machineName = InetAddress.getLocalHost().getHostName();
    } catch (UnknownHostException e) {
      machineName = "";
    }
    info.setName(svcObjFact.createComputerInfoName(machineName));
    info.setJobID(jobid);
    info.setTaskID(taskid);
    info.setScheduler(svcObjFact.createComputerInfoScheduler(scheduler));

    try {
      info.setCallIn(Utility.getXMLCurrentTime());
    } catch (DatatypeConfigurationException e1) {
      e1.printStackTrace();
      System.exit(1);
    }

    info.setTs(ts);

    String username = System.getProperty("user.name");
    info.setRunAsUser(svcObjFact.createComputerInfoRunAsUser(username));

    info.setOnExitCalled(false);

    Map<String, String> envMap = System.getenv();
    List<KeyValueOfstringstring> envList = new ArrayList<KeyValueOfstringstring>();
    for (String envName : envMap.keySet()) {
      KeyValueOfstringstring entry = new KeyValueOfstringstring();
      entry.setKey(envName);
      entry.setValue(envMap.get(envName));
      envList.add(entry);
      if (envName.compareToIgnoreCase(EnvVarNames.NON_TERMINATING_ERROR_RETRY_COUNT) == 0) {
        if (NonTerminatingErrorRetryCount < Integer.parseInt(entry.getValue())) {
          NonTerminatingErrorRetryCount++;
          System.out.format(
              "Throw NonTerminatingErrorRetryCount times: %d%n", NonTerminatingErrorRetryCount);

          throw Utility.BuildRetryOperationError(
              "test", String.valueOf(NonTerminatingErrorRetryCount));
        }
      }
    }

    String WriteFileTest = System.getenv(EnvVarNames.WRITE_FAIL_TEST);
    if (!Utility.isNullOrEmpty(WriteFileTest)) {
      try {
        for (String file : WriteFileTest.split(";")) {
          System.out.format("Begin to write file %s%n", file);
          FileWriter writer = new FileWriter(new File(file), true);
          writer.close();
        }
        for (String file : WriteFileTest.split(";")) {
          System.out.format("Begin to delete file %s%n", file);
          File f = new File(file);
          f.delete();
        }
      } catch (Exception e) {
        e.printStackTrace();
        throw Utility.BuildRetryOperationError(e.toString());
      }
    }
    System.out.format("Called %d%n", refID);

    return info;
  }
  /**
   * Test method for {@link
   * com.microsoft.hpc.scheduler.session.SessionBase#close(java.lang.Boolean)} .
   */
  @Test
  public final void testCloseBoolean() {

    logger.Start("testCloseBoolean");

    SessionStartInfo info =
        new SessionStartInfo(
            config.Scheduler, config.ServiceName, config.UserName, config.Password);
    logger.Info("Creating a %s durable session.", config.ServiceName);

    DurableSession session = null;
    int sessionId = 0;
    int refId = Util.generateRandomInteger();
    try {
      session = DurableSession.createSession(info);
      sessionId = session.getId();
      logger.Info("Session %d is created.", sessionId);
      BrokerClient<AITestLibService> client =
          new BrokerClient<AITestLibService>(session, AITestLibService.class);
      logger.Info("Sending %d requests...", config.NbOfCalls);

      for (int i = 0; i < config.NbOfCalls; i++) {
        Echo request = Util.generateEchoRequest(refId);
        client.sendRequest(request, i);
      }
      logger.Info("Call endRequests()...");
      client.endRequests();
      client.close();
      // close the session without purge
      session.close(false);

    } catch (Throwable e) {
      logger.Error("Exception is thrown ", e);
    }

    SessionAttachInfo attInfo =
        new SessionAttachInfo(config.Scheduler, sessionId, config.UserName, config.Password);

    try {
      session = DurableSession.attachSession(attInfo);
      logger.Info("Session %d is attached.", sessionId);

      BrokerClient<AITestLibService> client =
          new BrokerClient<AITestLibService>(session, AITestLibService.class);
      logger.Info("Retrieving responses...");

      for (BrokerResponse<EchoResponse> response : client.getResponses(EchoResponse.class)) {
        try {
          ComputerInfo reply = response.getResult().getEchoResult().getValue();
          logger.Info("\tReceived response for request %s: %s", response.getUserData(), reply);
          logger.assertTrue("check response", reply.getRefID() == refId);
          // logger.assertEqual("check whole string", reply,
          // "SHPC-00421001:Java BVT");
        } catch (Throwable ex) {
          logger.Error("Error in process request ", ex);
        }
      }
      logger.Info("Done retrieving %d responses", config.NbOfCalls);
      client.close();
      // close the session without purge
      session.close(false);

    } catch (Throwable e1) {
      logger.Error("Exception is thrown ", e1);
    }

    try {
      session = DurableSession.attachSession(attInfo);
      logger.Info("Session %d is attached.", sessionId);

      BrokerClient<AITestLibService> client =
          new BrokerClient<AITestLibService>(session, AITestLibService.class);
      logger.Info("Retrieving responses...");

      for (BrokerResponse<EchoResponse> response : client.getResponses(EchoResponse.class)) {
        try {
          ComputerInfo reply = response.getResult().getEchoResult().getValue();
          logger.Info("\tReceived response for request %s: %s", response.getUserData(), reply);
          logger.assertTrue("check response", reply.getRefID() == refId);
          // logger.assertEqual("check whole string", reply,
          // "SHPC-00421001:Java BVT");
        } catch (Throwable ex) {
          logger.Error("Error in process request ", ex);
        }
      }
      logger.Info("Done retrieving %d responses", config.NbOfCalls);
      client.close();
      session.close();

    } catch (Throwable e1) {
      logger.Error("Exception is thrown ", e1);
    }

    if (session != null) {
      try {
        session.close();
      } catch (Throwable e1) {
        logger.Error("Exception is thrown ", e1);
      }
    }

    logger.End("testCloseBoolean");
  }