/**
  * Runs the specified TestCase
  *
  * @param testCase the testcase to run
  * @param context
  */
 protected void runTestCase(WsdlTestCase testCase) {
   try {
     log.info("Running TestCase [" + testCase.getName() + "]");
     WsdlTestCaseRunner runner = testCase.run(new StringToObjectMap(), false);
     log.info(
         "TestCase ["
             + testCase.getName()
             + "] finished with status ["
             + runner.getStatus()
             + "] in "
             + (runner.getTimeTaken())
             + "ms");
   } catch (Exception e) {
     e.printStackTrace();
   }
 }
  @Override
  public boolean cancel() {
    if (testCaseRunner != null) {
      testCaseRunner.cancel("Canceled by calling TestCase");
    }

    return true;
  }
  @Override
  public String getLabel() {
    String name = getName();

    if (testCaseRunner != null) {
      name += " - [" + testCaseRunner.getStatus() + "]";
    }

    if (isDisabled()) return name + " (disabled)";
    else return name;
  }
 public void actionPerformed(ActionEvent e) {
   WsdlTestCaseRunner testCaseRunner = getModelItem().getTestCaseRunner();
   if (testCaseRunner != null) testCaseRunner.cancel("Canceled from RunTestCase UI");
 }
  public TestStepResult run(TestCaseRunner testRunner, TestCaseRunContext testRunContext) {
    WsdlMessageExchangeTestStepResult result = new WsdlMessageExchangeTestStepResult(this);

    testCaseRunner = null;

    if (targetTestCase != null) {
      Enum runMode = getRunMode();

      if (runMode == RunTestCaseRunModeTypeConfig.PARALLELL) {
        runningTestCase = createTestCase(targetTestCase);
      } else {
        runningTestCase = targetTestCase;

        TestCaseRunner targetTestRunner = SoapUI.getTestMonitor().getTestRunner(targetTestCase);
        if (targetTestRunner != null && targetTestRunner.getStatus() == TestRunner.Status.RUNNING) {
          if (runMode == RunTestCaseRunModeTypeConfig.SINGLETON_AND_FAIL) {
            result.setStatus(TestStepStatus.FAILED);
            result.addMessage("Target TestCase is already running");
            result.stopTimer();
            runningTestCase = null;
          } else {
            targetTestRunner.waitUntilFinished();
          }
        }
      }

      if (runningTestCase != null) {
        synchronized (runningTestCase) {
          for (TestRunListener listener : testRunListeners)
            runningTestCase.addTestRunListener(listener);

          StringList returnProperties = getReturnProperties();
          Map<String, TestProperty> props = getProperties();
          for (String key : props.keySet()) {
            if (runningTestCase.hasProperty(key) && !returnProperties.contains(key)) {
              String value = props.get(key).getValue();
              runningTestCase.setPropertyValue(
                  key, PropertyExpander.expandProperties(testRunContext, value));
            }
          }

          currentLabel = getLabel();
          runningTestCase.addTestRunListener(testRunListener);

          // StringToObjectMap properties = new StringToObjectMap();
          // for( String name : testRunContext.getPropertyNames() )
          // properties.put( name, testRunContext.getProperty( name ));

          result.startTimer();
          testCaseRunner = runningTestCase.run(new StringToObjectMap(), true);
          testCaseRunner.waitUntilFinished();
          result.stopTimer();

          for (String key : returnProperties) {
            if (runningTestCase.hasProperty(key))
              setPropertyValue(key, runningTestCase.getPropertyValue(key));
          }

          // aggregate results
          for (TestStepResult testStepResult : testCaseRunner.getResults()) {
            result.addMessage(
                testStepResult.getTestStep().getName()
                    + " - "
                    + testStepResult.getStatus()
                    + " - "
                    + testStepResult.getTimeTaken());
            for (String msg : testStepResult.getMessages()) {
              result.addMessage("- " + msg);
            }

            if (testStepResult instanceof MessageExchangeTestStepResult) {
              result.addMessages(
                  ((MessageExchangeTestStepResult) testStepResult).getMessageExchanges());
            }
          }

          switch (testCaseRunner.getStatus()) {
            case CANCELED:
              result.setStatus(TestStepStatus.CANCELED);
              break;
            case FAILED:
              result.setStatus(TestStepStatus.FAILED);
              break;
            case FINISHED:
              result.setStatus(TestStepStatus.OK);
              break;
            default:
              result.setStatus(TestStepStatus.UNKNOWN);
              break;
          }

          for (TestRunListener listener : testRunListeners)
            runningTestCase.removeTestRunListener(listener);

          if (runMode == RunTestCaseRunModeTypeConfig.PARALLELL) runningTestCase.release();

          runningTestCase = null;
          testCaseRunner = null;
        }
      }
    } else {
      result.setStatus(TestStepStatus.FAILED);
      result.addMessage("Missing testCase in project");
      result.stopTimer();
    }

    return result;
  }
  @Override
  public void afterStep(
      TestCaseRunner testRunner, TestCaseRunContext runContext, TestStepResult result) {
    super.afterStep(testRunner, runContext, result);
    TestStep currentStep = runContext.getCurrentStep();

    if (currentStep instanceof Assertable) {
      Assertable requestStep = (Assertable) currentStep;
      for (int c = 0; c < requestStep.getAssertionCount(); c++) {
        TestAssertion assertion = requestStep.getAssertionAt(c);
        log.info("Assertion [" + assertion.getName() + "] has status " + assertion.getStatus());
        if (assertion.getStatus() == AssertionStatus.FAILED) {
          for (AssertionError error : assertion.getErrors()) {
            log.error("ASSERTION FAILED -> " + error.getMessage());
          }

          assertions.add(assertion);
          assertionResults.put(assertion, (WsdlTestStepResult) result);
        }

        testAssertionCount++;
      }
    }

    String countPropertyName = currentStep.getName() + " run count";
    Long count = (Long) runContext.getProperty(countPropertyName);
    if (count == null) {
      count = new Long(0);
    }

    runContext.setProperty(countPropertyName, new Long(count.longValue() + 1));

    if (result.getStatus() == TestStepStatus.FAILED || exportAll) {
      try {
        String exportSeparator = System.getProperty(SOAPUI_EXPORT_SEPARATOR, "-");

        TestCase tc = currentStep.getTestCase();
        String nameBase =
            StringUtils.createFileName(tc.getTestSuite().getName(), '_')
                + exportSeparator
                + StringUtils.createFileName(tc.getName(), '_')
                + exportSeparator
                + StringUtils.createFileName(currentStep.getName(), '_')
                + "-"
                + count.longValue()
                + "-"
                + result.getStatus();

        WsdlTestCaseRunner callingTestCaseRunner =
            (WsdlTestCaseRunner) runContext.getProperty("#CallingTestCaseRunner#");

        if (callingTestCaseRunner != null) {
          WsdlTestCase ctc = callingTestCaseRunner.getTestCase();
          WsdlRunTestCaseTestStep runTestCaseTestStep =
              (WsdlRunTestCaseTestStep) runContext.getProperty("#CallingRunTestCaseStep#");

          nameBase =
              StringUtils.createFileName(ctc.getTestSuite().getName(), '_')
                  + exportSeparator
                  + StringUtils.createFileName(ctc.getName(), '_')
                  + exportSeparator
                  + StringUtils.createFileName(runTestCaseTestStep.getName(), '_')
                  + exportSeparator
                  + StringUtils.createFileName(tc.getTestSuite().getName(), '_')
                  + exportSeparator
                  + StringUtils.createFileName(tc.getName(), '_')
                  + exportSeparator
                  + StringUtils.createFileName(currentStep.getName(), '_')
                  + "-"
                  + count.longValue()
                  + "-"
                  + result.getStatus();
        }

        String absoluteOutputFolder = getAbsoluteOutputFolder(ModelSupport.getModelItemProject(tc));
        String fileName = absoluteOutputFolder + File.separator + nameBase + ".txt";

        if (result.getStatus() == TestStepStatus.FAILED) {
          log.error(currentStep.getName() + " failed, exporting to [" + fileName + "]");
        }

        new File(fileName).getParentFile().mkdirs();

        PrintWriter writer = new PrintWriter(fileName);
        result.writeTo(writer);
        writer.close();

        // write attachments
        if (result instanceof MessageExchange) {
          Attachment[] attachments = ((MessageExchange) result).getResponseAttachments();
          if (attachments != null && attachments.length > 0) {
            for (int c = 0; c < attachments.length; c++) {
              fileName = nameBase + "-attachment-" + (c + 1) + ".";

              Attachment attachment = attachments[c];
              String contentType = attachment.getContentType();
              if (!"application/octet-stream".equals(contentType)
                  && contentType != null
                  && contentType.indexOf('/') != -1) {
                fileName += contentType.substring(contentType.lastIndexOf('/') + 1);
              } else {
                fileName += "dat";
              }

              fileName = absoluteOutputFolder + File.separator + fileName;

              FileOutputStream outFile = new FileOutputStream(fileName);
              Tools.writeAll(outFile, attachment.getInputStream());
              outFile.close();
            }
          }
        }

        exportCount++;
      } catch (Exception e) {
        log.error("Error saving failed result: " + e, e);
      }
    }

    testStepCount++;
  }