/*
   * (non-Javadoc)
   *
   * @see
   * org.tempuri.ITestService#generateLoadWithResponseData(java.lang.Integer
   * refID ,)javax.xml.datatype.Duration sleepTime ,)byte[] inputData
   * ,)java.lang.Integer outputDataSize )*
   */
  public org.datacontract.schemas._2004._07.services.StatisticInfo generateLoadWithResponseData(
      java.lang.Integer refID,
      javax.xml.datatype.Duration sleepTime,
      byte[] inputData,
      java.lang.Integer outputDataSize) {
    ServiceContext.Logger.traceEvent(Level.ALL, "Executing operation generateLoadWithResponseData");

    try {
      StatisticInfo info = new StatisticInfo();
      info.setRefID(refID);
      info.setStartTime(Utility.getXMLCurrentTime());
      if (inputData != null) {
        for (byte b : inputData) {
          System.out.print(b);
        }
      }
      Thread.sleep(sleepTime.getTimeInMillis(new Date()));

      String instanceid = System.getenv(EnvVarNames.CCP_TASKINSTANCEID);
      String taskid = System.getenv(EnvVarNames.CCP_TASKID);
      if (Utility.isNullOrEmpty(instanceid)) instanceid = "0";
      if (Utility.isNullOrEmpty(taskid)) taskid = "0";

      if (instanceid.equals("0"))
        info.setInstanceId(svcObjFact.createStatisticInfoInstanceId(taskid));
      else info.setInstanceId(svcObjFact.createStatisticInfoInstanceId(taskid + "." + instanceid));
      info.setEndTime(Utility.getXMLCurrentTime());

      return info;
    } catch (java.lang.Exception ex) {
      ex.printStackTrace();
      throw new RuntimeException(ex);
    }
  }
 /*
  * (non-Javadoc)
  *
  * @see org.tempuri.ITestService#consumeCPU(javax.xml.datatype.Duration time
  * )*
  */
 public java.lang.String consumeCPU(javax.xml.datatype.Duration time) {
   ServiceContext.Logger.traceEvent(Level.ALL, "Executing operation consumeCPU");
   try {
     Pi PI = new Pi();
     PI.echo();
     return Pi.calculatePi(time.getTimeInMillis(new Date()));
   } 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#echoWithDelay(java.lang.Integer refID
   * ,)javax.xml.datatype.Duration delay )*
   */
  public org.datacontract.schemas._2004._07.services.ComputerInfo echoWithDelay(
      java.lang.Integer refID, javax.xml.datatype.Duration delay)
      throws ITestServiceEchoWithDelayAuthenticationFailureFaultFaultMessage,
          ITestServiceEchoWithDelayRetryOperationErrorFaultFaultMessage {
    ServiceContext.Logger.traceEvent(Level.ALL, "Executing operation echoWithDelay");

    try {
      System.out.println("Start call " + refID.toString());
      Thread.sleep((long) delay.getTimeInMillis(new Date()));
      return echo(refID);
    } 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#getCommonData(java.lang.Integer refID
   * ,)javax.xml.datatype.Duration sleepBeforeGet
   * ,)javax.xml.datatype.Duration sleepAfterGet ,)java.lang.String
   * dataClientId ,)java.lang.String expectedMd5Hash ,)java.lang.Integer
   * testActionId )*
   */
  public org.datacontract.schemas._2004._07.services.ComputerInfo getCommonData(
      java.lang.Integer refID,
      javax.xml.datatype.Duration sleepBeforeGet,
      javax.xml.datatype.Duration sleepAfterGet,
      java.lang.String dataClientId,
      java.lang.String expectedMd5Hash,
      java.lang.Integer testActionId)
      throws ITestServiceGetCommonDataCommonDataErrorFaultFaultMessage {
    ServiceContext.Logger.traceEvent(Level.ALL, "Executing operation getCommonData");
    try {
      switch (testActionId) {
        case Read_Raw_Bytes:
          long sleepTime = (long) sleepBeforeGet.getTimeInMillis(new Date());
          Thread.sleep(sleepTime);

          System.out.format(
              "%s: %d: Try to read raw common data for DataClient: %s\n",
              Utility.getCurrentTime(), refID, dataClientId);
          try {
            DataClient dataClient = ServiceContext.getDataClient(dataClientId);
            byte[] data = dataClient.readRawBytesAll();

            // Verify
            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] md5Bytes = md.digest(data);
            String commonDataMd5Hash = "";
            for (byte b : md5Bytes) {
              commonDataMd5Hash += String.format("%02X", b);
            }
            if (!commonDataMd5Hash.equalsIgnoreCase(expectedMd5Hash)) {
              String output =
                  String.format(
                      "Corrupted common data in content. Expected md5: %s, actual md5: %s",
                      expectedMd5Hash, commonDataMd5Hash);
              System.out.println(output);
              throw new Exception(output);
            }

            System.out.format(
                "%s: %d: Common data for DataClient: %s validated",
                Utility.getCurrentTime(), refID, dataClientId);
            dataClient.close();
          } catch (Exception e) {
            boolean fileAccessable = false;
            try {
              String path = System.getenv("HPC_RUNTIMESHARE");
              if (!Utility.isNullOrEmpty(path)) {
                path += "\\Data";
                path += "\\" + String.valueOf(hashString(dataClientId));
              }
              System.out.println(path);
              fileAccessable = (new File(path)).exists();
            } catch (Exception e_alt) {
              // swallow
            }
            String errmsg =
                String.format(
                    "%s: %d: Unexpected exception thrown when reading data: %s\n",
                    Utility.getCurrentTime(), refID, e.toString());
            throw new Exception(
                String.format(
                    "ErrMsg: %s\nOutput: %s\nFileAccessable: %s",
                    errmsg, e.getMessage(), String.valueOf(fileAccessable)));
          }
          return echoWithDelay(refID, sleepAfterGet);
        case READ_AccessDenied:
        case READ_AccessDenied_ReadBytes:
        case No_Read_PerReq:
        case No_Read_Raw_PerReq:
        case Default:
        default:
          // unimplemented due to API difference
          return null;
      }
    } catch (java.lang.Exception ex) {
      ex.printStackTrace();
      throw new RuntimeException(ex);
    }
    // throw new
    // ITestServiceGetCommonDataCommonDataErrorFaultFaultMessage("ITestService_GetCommonData_CommonDataErrorFault_FaultMessage...");
  }
 /*
  * getTimeInMillis(java.util.Calendar startInstant) returns milliseconds
  * between startInstant and startInstant plus this Duration throws NPE if
  * startInstant parameter is null.
  */
 @Test(expectedExceptions = NullPointerException.class)
 public void checkDurationGetTimeInMillisNeg() {
   Duration duration87 = datatypeFactory.newDuration("PT1M1S");
   Calendar calendar87 = null;
   duration87.getTimeInMillis(calendar87);
 }
 /*
  * getTimeInMillis(java.util.Calendar startInstant) returns milliseconds
  * between startInstant and startInstant plus this Duration.
  */
 @Test
 public void checkDurationGetTimeInMillis() {
   Duration duration86 = datatypeFactory.newDuration("PT1M1S");
   Calendar calendar86 = Calendar.getInstance();
   assertEquals(duration86.getTimeInMillis(calendar86), 61000);
 }