private void updateText() {
    StringBuilder sb = new StringBuilder();

    if (myShowSettingsBeforeRunCheckBox.isSelected()) {
      sb.append(ExecutionBundle.message("configuration.edit.before.run")).append(", ");
    }

    List<BeforeRunTask> tasks = myModel.getItems();
    if (!tasks.isEmpty()) {
      LinkedHashMap<BeforeRunTaskProvider, Integer> counter =
          new LinkedHashMap<BeforeRunTaskProvider, Integer>();
      for (BeforeRunTask task : tasks) {
        BeforeRunTaskProvider<BeforeRunTask> provider =
            BeforeRunTaskProvider.getProvider(
                myRunConfiguration.getProject(), task.getProviderId());
        if (provider != null) {
          Integer count = counter.get(provider);
          if (count == null) {
            count = task.getItemsCount();
          } else {
            count += task.getItemsCount();
          }
          counter.put(provider, count);
        }
      }
      for (Iterator<Map.Entry<BeforeRunTaskProvider, Integer>> iterator =
              counter.entrySet().iterator();
          iterator.hasNext(); ) {
        Map.Entry<BeforeRunTaskProvider, Integer> entry = iterator.next();
        BeforeRunTaskProvider provider = entry.getKey();
        String name = provider.getName();
        if (name.startsWith("Run ")) {
          name = name.substring(4);
        }
        sb.append(name);
        if (entry.getValue() > 1) {
          sb.append(" (").append(entry.getValue().intValue()).append(")");
        }
        if (iterator.hasNext()) sb.append(", ");
      }
    }
    if (sb.length() > 0) {
      sb.insert(0, ": ");
    }
    sb.insert(0, ExecutionBundle.message("before.launch.panel.title"));
    myListener.titleChanged(sb.toString());
  }
    public String getGeneratedName(final JavaRunConfigurationModule configurationModule) {
      if (TEST_PACKAGE.equals(TEST_OBJECT) || TEST_DIRECTORY.equals(TEST_OBJECT)) {
        final String moduleName =
            TEST_SEARCH_SCOPE.getScope() == TestSearchScope.WHOLE_PROJECT
                ? ""
                : configurationModule.getModuleName();
        final String packageName = getPackageName();
        if (packageName.length() == 0) {
          if (moduleName.length() > 0) {
            return ExecutionBundle.message("default.junit.config.name.all.in.module", moduleName);
          }
          return DEFAULT_PACKAGE_NAME;
        }
        if (moduleName.length() > 0) {
          return ExecutionBundle.message(
              "default.junit.config.name.all.in.package.in.module", packageName, moduleName);
        }
        return packageName;
      }
      if (TEST_PATTERN.equals(TEST_OBJECT)) {
        final int size = myPattern.size();
        if (size == 0) return "Temp suite";
        return StringUtil.getShortName(myPattern.iterator().next())
            + (size > 1 ? " and " + (size - 1) + " more" : "");
      }
      final String className =
          JavaExecutionUtil.getPresentableClassName(getMainClassName(), configurationModule);
      if (TEST_METHOD.equals(TEST_OBJECT)) {
        return className + '.' + getMethodName();
      }

      return className;
    }
Example #3
0
 @Override
 public String getDescription(RunConfigurableBeforeRunTask task) {
   if (task.getSettings() == null) {
     return ExecutionBundle.message("before.launch.run.another.configuration");
   } else {
     return ExecutionBundle.message(
         "before.launch.run.certain.configuration", task.getSettings().getName());
   }
 }
 public SettingsEditor<? extends RunConfiguration> getConfigurationEditor() {
   SettingsEditorGroup<JUnitConfiguration> group = new SettingsEditorGroup<JUnitConfiguration>();
   group.addEditor(
       ExecutionBundle.message("run.configuration.configuration.tab.title"),
       new JUnitConfigurable(getProject()));
   JavaRunConfigurationExtensionManager.getInstance().appendEditors(this, group);
   group.addEditor(
       ExecutionBundle.message("logs.tab.title"), new LogConfigurationPanel<JUnitConfiguration>());
   return group;
 }
 public String suggestActionName() {
   final String configurationName = myConfiguration.getName();
   if (!myConfiguration.isGeneratedName()) {
     return "'" + configurationName + "'";
   }
   final JUnitConfiguration.Data data = myConfiguration.getPersistentData();
   if (data.getPackageName().trim().length() > 0) {
     return ExecutionBundle.message("test.in.scope.presentable.text", data.getPackageName());
   }
   return ExecutionBundle.message("all.tests.scope.presentable.text");
 }
Example #6
0
 private String generateName(final String actionText) {
   switch (myType) {
     case CREATE:
       return ExecutionBundle.message(
           "create.run.configuration.for.item.action.name", actionText);
     case SELECT:
       return ExecutionBundle.message(
           "select.run.configuration.for.item.action.name", actionText);
     default:
       return ExecutionBundle.message("save.run.configuration.for.item.action.name", actionText);
   }
 }
Example #7
0
  public static void addLabel(final TestFrameworkRunningModel model) {
    String label;
    int color;

    if (model.getRoot().isDefect()) {
      color = RED.getRGB();
      label = ExecutionBundle.message("junit.runing.info.tests.failed.label");
    } else {
      color = GREEN.getRGB();
      label = ExecutionBundle.message("junit.runing.info.tests.passed.label");
    }
    final TestConsoleProperties consoleProperties = model.getProperties();
    String name = label + " " + consoleProperties.getConfiguration().getName();
    LocalHistory.getInstance().putSystemLabel(consoleProperties.getProject(), name, color);
  }
 public void restart() {
   final Project project =
       PlatformDataKeys.PROJECT.getData(
           DataManager.getInstance().getDataContext(myDescriptor.getComponent()));
   if (ExecutorRegistry.getInstance()
       .isStarting(project, myExecutor.getId(), myRunner.getRunnerId())) {
     return;
   }
   try {
     final ExecutionEnvironment old = myEnvironment;
     myRunner.execute(
         myExecutor,
         new ExecutionEnvironment(
             old.getRunProfile(),
             old.getExecutionTarget(),
             project,
             old.getRunnerSettings(),
             old.getConfigurationSettings(),
             myDescriptor,
             old.getRunnerAndConfigurationSettings()));
   } catch (RunCanceledByUserException ignore) {
   } catch (ExecutionException e1) {
     Messages.showErrorDialog(
         project, e1.getMessage(), ExecutionBundle.message("restart.error.message.title"));
   }
 }
  void doAddAction(AnActionButton button) {
    if (isUnknown()) {
      return;
    }

    final JBPopupFactory popupFactory = JBPopupFactory.getInstance();
    final BeforeRunTaskProvider<BeforeRunTask>[] providers =
        Extensions.getExtensions(
            BeforeRunTaskProvider.EXTENSION_POINT_NAME, myRunConfiguration.getProject());
    Set<Key> activeProviderKeys = getActiveProviderKeys();

    DefaultActionGroup actionGroup = new DefaultActionGroup(null, false);
    for (final BeforeRunTaskProvider<BeforeRunTask> provider : providers) {
      if (provider.createTask(myRunConfiguration) == null) continue;
      if (activeProviderKeys.contains(provider.getId()) && provider.isSingleton()) continue;
      AnAction providerAction =
          new AnAction(provider.getName(), null, provider.getIcon()) {
            @Override
            public void actionPerformed(AnActionEvent e) {
              BeforeRunTask task = provider.createTask(myRunConfiguration);
              if (task != null) {
                provider.configureTask(myRunConfiguration, task);
                if (!provider.canExecuteTask(myRunConfiguration, task)) return;
              } else {
                return;
              }
              task.setEnabled(true);

              Set<RunConfiguration> configurationSet = new HashSet<RunConfiguration>();
              getAllRunBeforeRuns(task, configurationSet);
              if (configurationSet.contains(myRunConfiguration)) {
                JOptionPane.showMessageDialog(
                    BeforeRunStepsPanel.this,
                    ExecutionBundle.message(
                        "before.launch.panel.cyclic_dependency_warning",
                        myRunConfiguration.getName(),
                        provider.getDescription(task)),
                    ExecutionBundle.message("warning.common.title"),
                    JOptionPane.WARNING_MESSAGE);
                return;
              }
              addTask(task);
              myListener.fireStepsBeforeRunChanged();
            }
          };
      actionGroup.add(providerAction);
    }
    final ListPopup popup =
        popupFactory.createActionGroupPopup(
            ExecutionBundle.message("add.new.run.configuration.acrtion.name"),
            actionGroup,
            SimpleDataContext.getProjectContext(myRunConfiguration.getProject()),
            false,
            false,
            false,
            null,
            -1,
            Condition.TRUE);
    popup.show(button.getPreferredPopupPoint());
  }
  public static void handleExecutionError(
      @NotNull final Project project,
      @NotNull final String toolWindowId,
      @NotNull String taskName,
      @NotNull ExecutionException e) {
    if (e instanceof RunCanceledByUserException) return;

    LOG.debug(e);

    String description = e.getMessage();
    HyperlinkListener listener = null;

    if ((description.contains("87") || description.contains("111") || description.contains("206"))
        && e instanceof ProcessNotCreatedException
        && !PropertiesComponent.getInstance(project).isTrueValue("dynamic.classpath")) {
      final String commandLineString =
          ((ProcessNotCreatedException) e).getCommandLine().getCommandLineString();
      if (commandLineString.length() > 1024 * 32) {
        description =
            "Command line is too long. In order to reduce its length classpath file can be used.<br>"
                + "Would you like to enable classpath file mode for all run configurations of your project?<br>"
                + "<a href=\"\">Enable</a>";

        listener =
            new HyperlinkListener() {
              @Override
              public void hyperlinkUpdate(HyperlinkEvent event) {
                PropertiesComponent.getInstance(project).setValue("dynamic.classpath", "true");
              }
            };
      }
    }
    final String title = ExecutionBundle.message("error.running.configuration.message", taskName);
    final String fullMessage = title + ":<br>" + description;

    if (ApplicationManager.getApplication().isUnitTestMode()) {
      LOG.error(fullMessage);
    }

    if (listener == null && e instanceof HyperlinkListener) {
      listener = (HyperlinkListener) e;
    }

    final HyperlinkListener finalListener = listener;
    final String finalDescription = description;
    UIUtil.invokeLaterIfNeeded(
        new Runnable() {
          @Override
          public void run() {
            ToolWindowManager.getInstance(project)
                .notifyByBalloon(toolWindowId, MessageType.ERROR, fullMessage, null, finalListener);
            NotificationListener notificationListener =
                ObjectUtils.tryCast(finalListener, NotificationListener.class);
            ourNotificationGroup
                .createNotification(
                    title, finalDescription, NotificationType.ERROR, notificationListener)
                .notify(project);
          }
        });
  }
  private ValidationResult getValidationResult() {
    if (!myValidationResultValid) {
      myLastValidationResult = null;
      try {
        RunnerAndConfigurationSettings snapshot = getSnapshot();
        if (snapshot != null) {
          snapshot.setName(getNameText());
          snapshot.checkSettings();
          for (ProgramRunner runner : RunnerRegistry.getInstance().getRegisteredRunners()) {
            for (Executor executor : ExecutorRegistry.getInstance().getRegisteredExecutors()) {
              if (runner.canRun(executor.getId(), snapshot.getConfiguration())) {
                checkConfiguration(runner, snapshot);
                break;
              }
            }
          }
        }
      } catch (RuntimeConfigurationException exception) {
        myLastValidationResult =
            exception != null
                ? new ValidationResult(
                    exception.getLocalizedMessage(), exception.getTitle(), exception.getQuickFix())
                : null;
      } catch (ConfigurationException e) {
        myLastValidationResult =
            new ValidationResult(
                e.getLocalizedMessage(),
                ExecutionBundle.message("invalid.data.dialog.title"),
                null);
      }

      myValidationResultValid = true;
    }
    return myLastValidationResult;
  }
Example #12
0
 private SelectionDialog(
     RunnerAndConfigurationSettings selectedSettings,
     @NotNull List<RunnerAndConfigurationSettings> settings) {
   super(myProject);
   setTitle(ExecutionBundle.message("before.launch.run.another.configuration.choose"));
   mySelectedSettings = selectedSettings;
   mySettings = settings;
   init();
   myJBList.setSelectedValue(mySelectedSettings, true);
   myJBList.addMouseListener(
       new MouseAdapter() {
         @Override
         public void mouseClicked(MouseEvent e) {
           if (SwingUtilities.isLeftMouseButton(e) && e.getClickCount() == 2) {
             doOKAction();
           }
         }
       });
   FontMetrics fontMetrics = myJBList.getFontMetrics(myJBList.getFont());
   int maxWidth = fontMetrics.stringWidth("m") * 30;
   for (RunnerAndConfigurationSettings setting : settings) {
     maxWidth =
         Math.max(fontMetrics.stringWidth(setting.getConfiguration().getName()), maxWidth);
   }
   maxWidth += 24; // icon and gap
   myJBList.setMinimumSize(new Dimension(maxWidth, myJBList.getPreferredSize().height));
 }
  private void waitForProcess(final RunContentDescriptor descriptor) {
    ProgressManager.getInstance()
        .runProcessWithProgressSynchronously(
            new Runnable() {
              public void run() {
                final Semaphore semaphore = new Semaphore();
                semaphore.down();

                ApplicationManager.getApplication()
                    .executeOnPooledThread(
                        new Runnable() {
                          public void run() {
                            final ProcessHandler processHandler = descriptor.getProcessHandler();
                            try {
                              if (processHandler != null) {
                                processHandler.waitFor();
                              }
                            } finally {
                              semaphore.up();
                            }
                          }
                        });

                final ProgressIndicator progressIndicator =
                    ProgressManager.getInstance().getProgressIndicator();

                if (progressIndicator != null) {
                  progressIndicator.setText(
                      ExecutionBundle.message("waiting.for.vm.detach.progress.text"));
                  ApplicationManager.getApplication()
                      .executeOnPooledThread(
                          new Runnable() {
                            public void run() {
                              while (true) {
                                if (progressIndicator.isCanceled()
                                    || !progressIndicator.isRunning()) {
                                  semaphore.up();
                                  break;
                                }
                                try {
                                  synchronized (this) {
                                    wait(2000L);
                                  }
                                } catch (InterruptedException ignore) {
                                }
                              }
                            }
                          });
                }

                semaphore.waitFor();
              }
            },
            ExecutionBundle.message(
                "terminating.process.progress.title", descriptor.getDisplayName()),
            true,
            myProject);
  }
  private static boolean userApprovesStopForSameTypeConfigurations(
      Project project, String configName, int instancesCount) {
    RunManagerImpl runManager = RunManagerImpl.getInstanceImpl(project);
    final RunManagerConfig config = runManager.getConfig();
    if (!config.isRestartRequiresConfirmation()) return true;

    DialogWrapper.DoNotAskOption option =
        new DialogWrapper.DoNotAskOption() {
          @Override
          public boolean isToBeShown() {
            return config.isRestartRequiresConfirmation();
          }

          @Override
          public void setToBeShown(boolean value, int exitCode) {
            config.setRestartRequiresConfirmation(value);
          }

          @Override
          public boolean canBeHidden() {
            return true;
          }

          @Override
          public boolean shouldSaveOptionsOnCancel() {
            return false;
          }

          @NotNull
          @Override
          public String getDoNotShowMessage() {
            return CommonBundle.message("dialog.options.do.not.show");
          }
        };
    return Messages.showOkCancelDialog(
            project,
            ExecutionBundle.message(
                "rerun.singleton.confirmation.message", configName, instancesCount),
            ExecutionBundle.message("process.is.running.dialog.title", configName),
            ExecutionBundle.message("rerun.confirmation.button.text"),
            CommonBundle.message("button.cancel"),
            Messages.getQuestionIcon(),
            option)
        == Messages.OK;
  }
Example #15
0
 public void testJdk() {
   try {
     CommandLineBuilder.createFromJavaParameters(new JavaParameters());
     fail("CantRunException (main class is not specified) expected");
   } catch (CantRunException e) {
     Assert.assertEquals(
         ExecutionBundle.message("run.configuration.error.no.jdk.specified"), e.getMessage());
   }
 }
Example #16
0
 public void testMainClass() {
   try {
     JavaParameters javaParameters = new JavaParameters();
     javaParameters.setJdk(getProjectJDK());
     CommandLineBuilder.createFromJavaParameters(javaParameters);
     fail("CantRunException (main class is not specified) expected");
   } catch (CantRunException e) {
     assertEquals(
         ExecutionBundle.message("main.class.is.not.specified.error.message"), e.getMessage());
   }
 }
  @Override
  public void update(final AnActionEvent event) {
    final Presentation presentation = event.getPresentation();
    String name = myEnvironment.getRunProfile().getName();
    ProcessHandler processHandler = myDescriptor.getProcessHandler();
    final boolean isRunning = processHandler != null && !processHandler.isProcessTerminated();

    presentation.setText(ExecutionBundle.message("rerun.configuration.action.name", name));
    presentation.setIcon(isRunning ? AllIcons.Actions.Restart : myExecutor.getIcon());
    presentation.setEnabled(isEnabled());
  }
 public MySearchForTestsTask(
     TestClassFilter classFilter,
     boolean[] junit4,
     THashSet<PsiClass> classes,
     FindCallback callback) {
   super(
       classFilter.getProject(), ExecutionBundle.message("seaching.test.progress.title"), true);
   myClassFilter = classFilter;
   myJunit4 = junit4;
   myClasses = classes;
   myCallback = callback;
 }
 public void checkConfiguration() throws RuntimeConfigurationException {
   super.checkConfiguration();
   final String packageName = myConfiguration.getPersistentData().getPackageName();
   final PsiPackage aPackage =
       JavaPsiFacade.getInstance(myConfiguration.getProject()).findPackage(packageName);
   if (aPackage == null) {
     throw new RuntimeConfigurationWarning(
         ExecutionBundle.message("package.does.not.exist.error.message", packageName));
   }
   if (getSourceScope() == null) {
     myConfiguration.getConfigurationModule().checkForWarning();
   }
 }
Example #20
0
 public void perform(final ConfigurationContext context) {
   final RunnerAndConfigurationSettingsImpl configuration = context.getConfiguration();
   if (RunDialog.editConfiguration(
       context.getProject(),
       configuration,
       ExecutionBundle.message(
           "create.run.configuration.for.item.dialog.title", configuration.getName()))) {
     final RunManagerImpl runManager = (RunManagerImpl) context.getRunManager();
     runManager.addConfiguration(
         configuration,
         runManager.isConfigurationShared(configuration),
         runManager.getBeforeRunTasks(configuration.getConfiguration()));
     runManager.setActiveConfiguration(configuration);
   }
 }
Example #21
0
 @Override
 public void checkConfiguration() throws RuntimeConfigurationException {
   JavaParametersUtil.checkAlternativeJRE(this);
   final String className = MAIN_CLASS_NAME;
   if (className == null || className.length() == 0) {
     throw new RuntimeConfigurationError(
         ExecutionBundle.message("no.main.class.specified.error.text"));
   }
   if (SCRATCH_FILE_ID <= 0) {
     throw new RuntimeConfigurationError("No scratch file associated with configuration");
   }
   if (getScratchVirtualFile() == null) {
     throw new RuntimeConfigurationError("Associated scratch file not found");
   }
   ProgramParametersUtil.checkWorkingDirectoryExist(
       this, getProject(), getConfigurationModule().getModule());
   JavaRunConfigurationExtensionManager.checkConfigurationIsValid(this);
 }
  private void appendForkInfo(Executor executor) throws ExecutionException {
    final String forkMode = myConfiguration.getForkMode();
    if (Comparing.strEqual(forkMode, "none")) {
      return;
    }

    if (getRunnerSettings().getData() != null) {
      final String actionName = executor.getActionName();
      throw new CantRunException(
          actionName
              + " is disabled in fork mode.<br/>Please change fork mode to &lt;none&gt; to "
              + actionName.toLowerCase()
              + ".");
    }

    final JavaParameters javaParameters = getJavaParameters();
    final Sdk jdk = javaParameters.getJdk();
    if (jdk == null) {
      throw new ExecutionException(
          ExecutionBundle.message("run.configuration.error.no.jdk.specified"));
    }

    try {
      final File tempFile = FileUtil.createTempFile("command.line", "", true);
      final PrintWriter writer = new PrintWriter(tempFile, "UTF-8");
      try {
        writer.println(((JavaSdkType) jdk.getSdkType()).getVMExecutablePath(jdk));
        for (String vmParameter : javaParameters.getVMParametersList().getList()) {
          writer.println(vmParameter);
        }
        writer.println("-classpath");
        writer.println(javaParameters.getClassPath().getPathsString());
      } finally {
        writer.close();
      }

      myJavaParameters
          .getProgramParametersList()
          .add("@@@" + forkMode + ',' + tempFile.getAbsolutePath());
    } catch (Exception e) {
      LOG.error(e);
    }
  }
 @Override
 public void update(final AnActionEvent e) {
   final Presentation presentation = e.getPresentation();
   final Project project = e.getData(CommonDataKeys.PROJECT);
   if (project == null) {
     disable(presentation);
     return;
   }
   RunnerAndConfigurationSettings settings = chooseTempSettings(project);
   if (settings == null) {
     disable(presentation);
   } else {
     presentation.setText(
         ExecutionBundle.message(
             "save.temporary.run.configuration.action.name", settings.getName()));
     presentation.setDescription(presentation.getText());
     presentation.setVisible(true);
     presentation.setEnabled(true);
   }
 }
 @Override
 public void update(AnActionEvent e) {
   Presentation presentation = e.getPresentation();
   Project project = e.getData(CommonDataKeys.PROJECT);
   if (ActionPlaces.isMainMenuOrActionSearch(e.getPlace())) {
     presentation.setDescription(
         ExecutionBundle.message("choose.run.configuration.action.description"));
   }
   try {
     if (project == null || project.isDisposed() || !project.isInitialized()) {
       updatePresentation(null, null, null, presentation);
       presentation.setEnabled(false);
     } else {
       updatePresentation(
           ExecutionTargetManager.getActiveTarget(project),
           RunManagerEx.getInstanceEx(project).getSelectedConfiguration(),
           project,
           presentation);
       presentation.setEnabled(true);
     }
   } catch (IndexNotReadyException e1) {
     presentation.setEnabled(false);
   }
 }
public class TestNGConfiguration extends JavaTestConfigurationBase {
  @NonNls private static final String PATTERNS_EL_NAME = "patterns";
  @NonNls private static final String PATTERN_EL_NAME = "pattern";
  @NonNls private static final String TEST_CLASS_ATT_NAME = "testClass";

  // private TestNGResultsContainer resultsContainer;
  protected TestData data;
  protected transient Project project;
  public boolean ALTERNATIVE_JRE_PATH_ENABLED;
  public String ALTERNATIVE_JRE_PATH;

  public static final String DEFAULT_PACKAGE_NAME =
      ExecutionBundle.message("default.package.presentable.name");
  public static final String DEFAULT_PACKAGE_CONFIGURATION_NAME =
      ExecutionBundle.message("default.package.configuration.name");
  private final RefactoringListeners.Accessor<PsiPackage> myPackage =
      new RefactoringListeners.Accessor<PsiPackage>() {
        public void setName(final String qualifiedName) {
          final boolean generatedName = isGeneratedName();
          data.PACKAGE_NAME = qualifiedName;
          if (generatedName) setGeneratedName();
        }

        @Nullable
        public PsiPackage getPsiElement() {
          final String qualifiedName = data.getPackageName();
          return qualifiedName != null
              ? JavaPsiFacade.getInstance(getProject()).findPackage(qualifiedName)
              : null;
        }

        public void setPsiElement(final PsiPackage psiPackage) {
          setName(psiPackage.getQualifiedName());
        }
      };

  private final RefactoringListeners.Accessor<PsiClass> myClass =
      new RefactoringListeners.Accessor<PsiClass>() {
        public void setName(final String qualifiedName) {
          final boolean generatedName = isGeneratedName();
          data.MAIN_CLASS_NAME = qualifiedName;
          if (generatedName) setGeneratedName();
        }

        @Nullable
        public PsiClass getPsiElement() {
          final String qualifiedName = data.getMainClassName();
          return qualifiedName != null
              ? JavaPsiFacade.getInstance(getProject())
                  .findClass(qualifiedName, GlobalSearchScope.allScope(project))
              : null;
        }

        public void setPsiElement(final PsiClass psiClass) {
          setName(psiClass.getQualifiedName());
        }
      };

  public TestNGConfiguration(String s, Project project, ConfigurationFactory factory) {
    this(s, project, new TestData(), factory);
  }

  private TestNGConfiguration(
      String s, Project project, TestData data, ConfigurationFactory factory) {
    super(s, new JavaRunConfigurationModule(project, false), factory);
    this.data = data;
    this.project = project;
  }

  public RunProfileState getState(
      @NotNull final Executor executor, @NotNull final ExecutionEnvironment env)
      throws ExecutionException {
    return new TestNGRunnableState(env, this);
  }

  public TestData getPersistantData() {
    return data;
  }

  @Override
  protected ModuleBasedConfiguration createInstance() {
    try {
      return new TestNGConfiguration(
          getName(),
          getProject(),
          (TestData) data.clone(),
          TestNGConfigurationType.getInstance().getConfigurationFactories()[0]);
    } catch (CloneNotSupportedException e) {
      // can't happen right?
      e.printStackTrace();
    }
    return null;
  }

  @Override
  public Collection<Module> getValidModules() {
    // TODO add handling for package
    return JavaRunConfigurationModule.getModulesForClass(getProject(), data.getMainClassName());
  }

  @Override
  public String suggestedName() {
    final TestNGTestObject testObject = TestNGTestObject.fromConfig(this);
    return testObject != null ? testObject.getGeneratedName() : null;
  }

  @Override
  public String getActionName() {
    final TestNGTestObject testObject = TestNGTestObject.fromConfig(this);
    return testObject != null ? testObject.getActionName() : null;
  }

  public void setVMParameters(String value) {
    data.setVMParameters(value);
  }

  public String getVMParameters() {
    return data.getVMParameters();
  }

  public void setProgramParameters(String value) {
    data.setProgramParameters(value);
  }

  public String getProgramParameters() {
    return data.getProgramParameters();
  }

  public void setWorkingDirectory(String value) {
    data.setWorkingDirectory(value);
  }

  public String getWorkingDirectory() {
    return data.getWorkingDirectory(project);
  }

  public void setEnvs(@NotNull Map<String, String> envs) {
    data.setEnvs(envs);
  }

  @NotNull
  public Map<String, String> getEnvs() {
    return data.getEnvs();
  }

  public void setPassParentEnvs(boolean passParentEnvs) {
    data.PASS_PARENT_ENVS = passParentEnvs;
  }

  public boolean isPassParentEnvs() {
    return data.PASS_PARENT_ENVS;
  }

  public boolean isAlternativeJrePathEnabled() {
    return ALTERNATIVE_JRE_PATH_ENABLED;
  }

  public void setAlternativeJrePathEnabled(boolean enabled) {
    this.ALTERNATIVE_JRE_PATH_ENABLED = enabled;
  }

  @Nullable
  public String getAlternativeJrePath() {
    return ALTERNATIVE_JRE_PATH;
  }

  public void setAlternativeJrePath(String path) {
    this.ALTERNATIVE_JRE_PATH = path;
  }

  public String getRunClass() {
    return !data.TEST_OBJECT.equals(TestType.CLASS.getType())
            && !data.TEST_OBJECT.equals(TestType.METHOD.getType())
        ? null
        : data.getMainClassName();
  }

  public String getPackage() {
    return !data.TEST_OBJECT.equals(TestType.PACKAGE.getType()) ? null : data.getPackageName();
  }

  public void setClassConfiguration(PsiClass psiclass) {
    setModule(data.setMainClass(psiclass));
    data.TEST_OBJECT = TestType.CLASS.getType();
    setGeneratedName();
  }

  public void setPackageConfiguration(Module module, PsiPackage pkg) {
    data.setPackage(pkg);
    setModule(module);
    data.TEST_OBJECT = TestType.PACKAGE.getType();
    setGeneratedName();
  }

  public void setMethodConfiguration(Location<PsiMethod> location) {
    setModule(data.setTestMethod(location));
    setGeneratedName();
  }

  public void bePatternConfiguration(List<PsiClass> classes, PsiMethod method) {
    data.TEST_OBJECT = TestType.PATTERN.getType();
    final String suffix;
    if (method != null) {
      data.METHOD_NAME = method.getName();
      suffix = "," + data.METHOD_NAME;
    } else {
      suffix = "";
    }
    LinkedHashSet<String> patterns = new LinkedHashSet<String>();
    for (PsiClass pattern : classes) {
      patterns.add(JavaExecutionUtil.getRuntimeQualifiedName(pattern) + suffix);
    }
    data.setPatterns(patterns);
    final Module module =
        RunConfigurationProducer.getInstance(TestNGPatternConfigurationProducer.class)
            .findModule(this, getConfigurationModule().getModule(), patterns);
    if (module == null) {
      data.setScope(TestSearchScope.WHOLE_PROJECT);
      setModule(null);
    } else {
      setModule(module);
    }
    setGeneratedName();
  }

  @NotNull
  public SettingsEditor<? extends RunConfiguration> getConfigurationEditor() {
    SettingsEditorGroup<TestNGConfiguration> group = new SettingsEditorGroup<TestNGConfiguration>();
    group.addEditor(
        ExecutionBundle.message("run.configuration.configuration.tab.title"),
        new TestNGConfigurationEditor(getProject()));
    JavaRunConfigurationExtensionManager.getInstance().appendEditors(this, group);
    group.addEditor(
        ExecutionBundle.message("logs.tab.title"),
        new LogConfigurationPanel<TestNGConfiguration>());
    return group;
  }

  @Override
  public void checkConfiguration() throws RuntimeConfigurationException {
    final TestNGTestObject testObject = TestNGTestObject.fromConfig(this);
    if (testObject != null) {
      testObject.checkConfiguration();
    }
    JavaRunConfigurationExtensionManager.checkConfigurationIsValid(this);
    ProgramParametersUtil.checkWorkingDirectoryExist(
        this, getProject(), getConfigurationModule().getModule());
    JavaParametersUtil.checkAlternativeJRE(this);
    // TODO add various checks here
  }

  @Override
  public void readExternal(Element element) throws InvalidDataException {
    PathMacroManager.getInstance(getProject()).expandPaths(element);
    super.readExternal(element);
    JavaRunConfigurationExtensionManager.getInstance().readExternal(this, element);
    readModule(element);
    DefaultJDOMExternalizer.readExternal(this, element);
    DefaultJDOMExternalizer.readExternal(getPersistantData(), element);
    EnvironmentVariablesComponent.readExternal(element, getPersistantData().getEnvs());

    Map<String, String> properties = getPersistantData().TEST_PROPERTIES;
    properties.clear();
    Element propertiesElement = element.getChild("properties");
    if (propertiesElement != null) {
      List<Element> children = propertiesElement.getChildren("property");
      for (Element property : children) {
        properties.put(property.getAttributeValue("name"), property.getAttributeValue("value"));
      }
    }

    List<String> listeners = getPersistantData().TEST_LISTENERS;
    listeners.clear();
    Element listenersElement = element.getChild("listeners");
    if (listenersElement != null) {
      List<Element> children = listenersElement.getChildren("listener");
      for (Element listenerClassName : children) {
        listeners.add(listenerClassName.getAttributeValue("class"));
      }
    }
    final Element patternsElement = element.getChild(PATTERNS_EL_NAME);
    if (patternsElement != null) {
      final LinkedHashSet<String> tests = new LinkedHashSet<String>();
      for (Object o : patternsElement.getChildren(PATTERN_EL_NAME)) {
        Element patternElement = (Element) o;
        tests.add(patternElement.getAttributeValue(TEST_CLASS_ATT_NAME));
      }
      getPersistantData().setPatterns(tests);
    }
  }

  @Override
  public void writeExternal(Element element) throws WriteExternalException {
    super.writeExternal(element);
    JavaRunConfigurationExtensionManager.getInstance().writeExternal(this, element);
    writeModule(element);
    DefaultJDOMExternalizer.writeExternal(this, element);
    DefaultJDOMExternalizer.writeExternal(getPersistantData(), element);
    EnvironmentVariablesComponent.writeExternal(element, getPersistantData().getEnvs());

    Element propertiesElement = element.getChild("properties");

    if (propertiesElement == null) {
      propertiesElement = new Element("properties");
      element.addContent(propertiesElement);
    }

    Map<String, String> properties = getPersistantData().TEST_PROPERTIES;
    for (Map.Entry<String, String> entry : properties.entrySet()) {
      Element property = new Element("property");
      property.setAttribute("name", entry.getKey());
      property.setAttribute("value", entry.getValue());
      propertiesElement.addContent(property);
    }

    Element listenersElement = element.getChild("listeners");
    if (listenersElement == null) {
      listenersElement = new Element("listeners");
      element.addContent(listenersElement);
    }

    List<String> listeners = getPersistantData().TEST_LISTENERS;
    for (String listener : listeners) {
      Element listenerElement = new Element("listener");
      listenerElement.setAttribute("class", listener);
      listenersElement.addContent(listenerElement);
    }
    final Set<String> patterns = getPersistantData().getPatterns();
    if (!patterns.isEmpty()) {
      final Element patternsElement = new Element(PATTERNS_EL_NAME);
      for (String o : patterns) {
        final Element patternElement = new Element(PATTERN_EL_NAME);
        patternElement.setAttribute(TEST_CLASS_ATT_NAME, o);
        patternsElement.addContent(patternElement);
      }
      element.addContent(patternsElement);
    }
  }

  @Nullable
  public RefactoringElementListener getRefactoringElementListener(final PsiElement element) {
    if (data.TEST_OBJECT.equals(TestType.PACKAGE.getType())) {
      if (!(element instanceof PsiPackage)) return null;
      final RefactoringElementListener listener =
          RefactoringListeners.getListener((PsiPackage) element, myPackage);
      return RunConfigurationExtension.wrapRefactoringElementListener(element, this, listener);
    } else if (data.TEST_OBJECT.equals(TestType.CLASS.getType())) {
      if (!(element instanceof PsiClass) && !(element instanceof PsiPackage)) return null;
      final RefactoringElementListener listener =
          RefactoringListeners.getClassOrPackageListener(element, myClass);
      return RunConfigurationExtension.wrapRefactoringElementListener(element, this, listener);
    } else if (data.TEST_OBJECT.equals(TestType.METHOD.getType())) {
      if (!(element instanceof PsiMethod)) {
        final RefactoringElementListener listener =
            RefactoringListeners.getClassOrPackageListener(element, myClass);
        return RunConfigurationExtension.wrapRefactoringElementListener(element, this, listener);
      }
      final PsiMethod method = (PsiMethod) element;
      if (!method.getName().equals(data.getMethodName())) return null;
      if (!method.getContainingClass().equals(myClass.getPsiElement())) return null;
      class Listener extends RefactoringElementAdapter implements UndoRefactoringElementListener {
        public void elementRenamedOrMoved(@NotNull final PsiElement newElement) {
          data.setTestMethod(PsiLocation.fromPsiElement((PsiMethod) newElement));
        }

        @Override
        public void undoElementMovedOrRenamed(
            @NotNull PsiElement newElement, @NotNull String oldQualifiedName) {
          final int methodIdx = oldQualifiedName.indexOf("#") + 1;
          if (methodIdx <= 0 || methodIdx >= oldQualifiedName.length()) return;
          data.METHOD_NAME = oldQualifiedName.substring(methodIdx);
        }
      }
      return RunConfigurationExtension.wrapRefactoringElementListener(
          element, this, new Listener());
    }
    return null;
  }

  @Override
  public boolean collectOutputFromProcessHandler() {
    return false;
  }

  @Override
  public SMTRunnerConsoleProperties createTestConsoleProperties(Executor executor) {
    return new TestNGConsoleProperties(this, executor);
  }

  @NotNull
  @Override
  public String getFrameworkPrefix() {
    return "g";
  }
}
public class JUnitConfiguration extends ModuleBasedConfiguration<JavaRunConfigurationModule>
    implements CommonJavaRunConfigurationParameters, RefactoringListenerProvider {
  private static final Logger LOG =
      Logger.getInstance("#com.intellij.execution.junit.JUnitConfiguration");
  public static final String DEFAULT_PACKAGE_NAME =
      ExecutionBundle.message("default.package.presentable.name");

  @NonNls public static final String TEST_CLASS = "class";
  @NonNls public static final String TEST_PACKAGE = "package";
  @NonNls public static final String TEST_DIRECTORY = "directory";
  @NonNls public static final String TEST_METHOD = "method";
  @NonNls private static final String PATTERN_EL_NAME = "pattern";
  @NonNls public static final String TEST_PATTERN = PATTERN_EL_NAME;

  @NonNls private static final String TEST_CLASS_ATT_NAME = "testClass";
  @NonNls private static final String PATTERNS_EL_NAME = "patterns";

  private final Data myData;
  // See #26522
  @NonNls
  public static final String JUNIT_START_CLASS = "com.intellij.rt.execution.junit.JUnitStarter";

  public boolean ALTERNATIVE_JRE_PATH_ENABLED;
  public String ALTERNATIVE_JRE_PATH;

  public JUnitConfiguration(
      final String name, final Project project, ConfigurationFactory configurationFactory) {
    this(name, project, new Data(), configurationFactory);
  }

  private JUnitConfiguration(
      final String name,
      final Project project,
      final Data data,
      ConfigurationFactory configurationFactory) {
    super(name, new JavaRunConfigurationModule(project, false), configurationFactory);
    myData = data;
  }

  public RunProfileState getState(
      @NotNull final Executor executor, @NotNull final ExecutionEnvironment env)
      throws ExecutionException {
    return TestObject.fromString(
        myData.TEST_OBJECT,
        getProject(),
        this,
        env.getRunnerSettings(),
        env.getConfigurationSettings());
  }

  public SettingsEditor<? extends RunConfiguration> getConfigurationEditor() {
    SettingsEditorGroup<JUnitConfiguration> group = new SettingsEditorGroup<JUnitConfiguration>();
    group.addEditor(
        ExecutionBundle.message("run.configuration.configuration.tab.title"),
        new JUnitConfigurable(getProject()));
    JavaRunConfigurationExtensionManager.getInstance().appendEditors(this, group);
    group.addEditor(
        ExecutionBundle.message("logs.tab.title"), new LogConfigurationPanel<JUnitConfiguration>());
    return group;
  }

  public Data getPersistentData() {
    return myData;
  }

  public RefactoringElementListener getRefactoringElementListener(final PsiElement element) {
    final RefactoringElementListener listener =
        myData.getTestObject(getProject(), this).getListener(element, this);
    return RunConfigurationExtension.wrapRefactoringElementListener(element, this, listener);
  }

  public String getGeneratedName() {
    return myData.getGeneratedName(getConfigurationModule());
  }

  public void checkConfiguration() throws RuntimeConfigurationException {
    myData.getTestObject(getProject(), this).checkConfiguration();
    JavaRunConfigurationExtensionManager.checkConfigurationIsValid(this);
  }

  public Collection<Module> getValidModules() {
    if (TEST_PACKAGE.equals(myData.TEST_OBJECT) || TEST_PATTERN.equals(myData.TEST_OBJECT)) {
      return Arrays.asList(ModuleManager.getInstance(getProject()).getModules());
    }
    try {
      myData.getTestObject(getProject(), this).checkConfiguration();
    } catch (RuntimeConfigurationError e) {
      return Arrays.asList(ModuleManager.getInstance(getProject()).getModules());
    } catch (RuntimeConfigurationException e) {
      // ignore
    }

    return JavaRunConfigurationModule.getModulesForClass(getProject(), myData.getMainClassName());
  }

  protected ModuleBasedConfiguration createInstance() {
    return new JUnitConfiguration(
        getName(),
        getProject(),
        myData.clone(),
        JUnitConfigurationType.getInstance()
            .getConfigurationFactories()[0]); // throw new RuntimeException("Should not call");
  }

  public boolean isGeneratedName() {
    final String name = getName();
    return myData.isGeneratedName(name, getConfigurationModule());
  }

  public String suggestedName() {
    return getTestObject().suggestActionName();
  }

  public void setVMParameters(String value) {
    myData.setVMParameters(value);
  }

  public String getVMParameters() {
    return myData.getVMParameters();
  }

  public void setProgramParameters(String value) {
    myData.setProgramParameters(value);
  }

  public String getProgramParameters() {
    return myData.getProgramParameters();
  }

  public void setWorkingDirectory(String value) {
    myData.setWorkingDirectory(value);
  }

  public String getWorkingDirectory() {
    return myData.getWorkingDirectory();
  }

  public void setEnvs(@NotNull Map<String, String> envs) {
    myData.setEnvs(envs);
  }

  @NotNull
  public Map<String, String> getEnvs() {
    return myData.getEnvs();
  }

  public void setPassParentEnvs(boolean passParentEnvs) {
    myData.PASS_PARENT_ENVS = passParentEnvs;
  }

  public boolean isPassParentEnvs() {
    return myData.PASS_PARENT_ENVS;
  }

  public boolean isAlternativeJrePathEnabled() {
    return ALTERNATIVE_JRE_PATH_ENABLED;
  }

  public void setAlternativeJrePathEnabled(boolean enabled) {
    this.ALTERNATIVE_JRE_PATH_ENABLED = enabled;
  }

  public String getAlternativeJrePath() {
    return ALTERNATIVE_JRE_PATH;
  }

  public void setAlternativeJrePath(String path) {
    this.ALTERNATIVE_JRE_PATH = path;
  }

  public String getRunClass() {
    final Data data = getPersistentData();
    return data.TEST_OBJECT != TEST_CLASS && data.TEST_OBJECT != TEST_METHOD
        ? null
        : data.getMainClassName();
  }

  public String getPackage() {
    final Data data = getPersistentData();
    return !Comparing.strEqual(data.TEST_OBJECT, TEST_PACKAGE) ? null : data.getPackageName();
  }

  public void beClassConfiguration(final PsiClass testClass) {
    setMainClass(testClass);
    myData.TEST_OBJECT = TEST_CLASS;
    setGeneratedName();
  }

  public void setMainClass(final PsiClass testClass) {
    final boolean shouldUpdateName = isGeneratedName();
    setModule(myData.setMainClass(testClass));
    if (shouldUpdateName) setGeneratedName();
  }

  public void setGeneratedName() {
    setName(getGeneratedName());
  }

  public void beMethodConfiguration(final Location<PsiMethod> methodLocation) {
    setModule(myData.setTestMethod(methodLocation));
    setGeneratedName();
  }

  @NotNull
  public Module[] getModules() {
    if (TEST_PACKAGE.equals(myData.TEST_OBJECT)
        && getPersistentData().getScope() == TestSearchScope.WHOLE_PROJECT) {
      return Module.EMPTY_ARRAY;
    }
    return super.getModules();
  }

  final RefactoringListeners.Accessor<PsiPackage> myPackage =
      new RefactoringListeners.Accessor<PsiPackage>() {
        public void setName(final String qualifiedName) {
          final boolean generatedName = isGeneratedName();
          myData.PACKAGE_NAME = qualifiedName;
          if (generatedName) setGeneratedName();
        }

        public PsiPackage getPsiElement() {
          final String qualifiedName = myData.getPackageName();
          return qualifiedName != null
              ? JavaPsiFacade.getInstance(getProject()).findPackage(qualifiedName)
              : null;
        }

        public void setPsiElement(final PsiPackage psiPackage) {
          setName(psiPackage.getQualifiedName());
        }
      };

  final RefactoringListeners.Accessor<PsiClass> myClass =
      new RefactoringListeners.Accessor<PsiClass>() {
        public void setName(@NotNull final String qualifiedName) {
          final boolean generatedName = isGeneratedName();
          myData.MAIN_CLASS_NAME = qualifiedName;
          if (generatedName) setGeneratedName();
        }

        public PsiClass getPsiElement() {
          return getConfigurationModule().findClass(myData.getMainClassName());
        }

        public void setPsiElement(final PsiClass psiClass) {
          final Module originalModule = getConfigurationModule().getModule();
          setMainClass(psiClass);
          restoreOriginalModule(originalModule);
        }
      };

  public TestObject getTestObject() {
    return myData.getTestObject(getProject(), this);
  }

  public void readExternal(final Element element) throws InvalidDataException {
    PathMacroManager.getInstance(getProject()).expandPaths(element);
    super.readExternal(element);
    JavaRunConfigurationExtensionManager.getInstance().readExternal(this, element);
    readModule(element);
    DefaultJDOMExternalizer.readExternal(this, element);
    DefaultJDOMExternalizer.readExternal(getPersistentData(), element);
    EnvironmentVariablesComponent.readExternal(element, getPersistentData().getEnvs());
    final Element patternsElement = element.getChild(PATTERNS_EL_NAME);
    if (patternsElement != null) {
      final Set<String> tests = new LinkedHashSet<String>();
      for (Object o : patternsElement.getChildren(PATTERN_EL_NAME)) {
        Element patternElement = (Element) o;
        tests.add(patternElement.getAttributeValue(TEST_CLASS_ATT_NAME));
      }
      myData.setPatterns(tests);
    }
    final Element forkModeElement = element.getChild("fork_mode");
    if (forkModeElement != null) {
      final String mode = forkModeElement.getAttributeValue("value");
      if (mode != null) {
        setForkMode(mode);
      }
    }
    final Element dirNameElement = element.getChild("dir");
    if (dirNameElement != null) {
      final String dirName = dirNameElement.getAttributeValue("value");
      getPersistentData().setDirName(FileUtil.toSystemDependentName(dirName));
    }
  }

  public void writeExternal(final Element element) throws WriteExternalException {
    super.writeExternal(element);
    JavaRunConfigurationExtensionManager.getInstance().writeExternal(this, element);
    writeModule(element);
    DefaultJDOMExternalizer.writeExternal(this, element);
    final Data persistentData = getPersistentData();
    DefaultJDOMExternalizer.writeExternal(persistentData, element);
    EnvironmentVariablesComponent.writeExternal(element, persistentData.getEnvs());
    final String dirName = persistentData.getDirName();
    if (!dirName.isEmpty()) {
      final Element dirNameElement = new Element("dir");
      dirNameElement.setAttribute("value", FileUtil.toSystemIndependentName(dirName));
      element.addContent(dirNameElement);
    }
    final Element patternsElement = new Element(PATTERNS_EL_NAME);
    for (String o : persistentData.getPatterns()) {
      final Element patternElement = new Element(PATTERN_EL_NAME);
      patternElement.setAttribute(TEST_CLASS_ATT_NAME, o);
      patternsElement.addContent(patternElement);
    }
    final String forkMode = getForkMode();
    if (!forkMode.equals("none")) {
      final Element forkModeElement = new Element("fork_mode");
      forkModeElement.setAttribute("value", forkMode);
      element.addContent(forkModeElement);
    }
    element.addContent(patternsElement);
    PathMacroManager.getInstance(getProject()).collapsePathsRecursively(element);
  }

  public void configureClasspath(final JavaParameters javaParameters) throws CantRunException {
    RunConfigurationModule module = getConfigurationModule();
    final String jreHome = isAlternativeJrePathEnabled() ? getAlternativeJrePath() : null;
    final int pathType = JavaParameters.JDK_AND_CLASSES_AND_TESTS;
    if (myData.getScope() == TestSearchScope.WHOLE_PROJECT) {
      JavaParametersUtil.configureProject(module.getProject(), javaParameters, pathType, jreHome);
    } else {
      JavaParametersUtil.configureModule(module, javaParameters, pathType, jreHome);
    }
  }

  public void setForkMode(@NotNull String forkMode) {
    myData.FORK_MODE = forkMode;
  }

  public String getForkMode() {
    return myData.FORK_MODE;
  }

  public static class Data implements Cloneable {
    public String PACKAGE_NAME;
    private String DIR_NAME;
    public String MAIN_CLASS_NAME;
    public String METHOD_NAME;
    public String TEST_OBJECT = TEST_CLASS;
    public String VM_PARAMETERS;
    public String PARAMETERS;
    public String WORKING_DIRECTORY;
    private String FORK_MODE = "none";
    private Set<String> myPattern = new LinkedHashSet<String>();

    // iws/ipr compatibility
    public String ENV_VARIABLES;
    private Map<String, String> myEnvs = new LinkedHashMap<String, String>();
    public boolean PASS_PARENT_ENVS = true;

    public TestSearchScope.Wrapper TEST_SEARCH_SCOPE = new TestSearchScope.Wrapper();

    public boolean equals(final Object object) {
      if (!(object instanceof Data)) return false;
      final Data second = (Data) object;
      return Comparing.equal(TEST_OBJECT, second.TEST_OBJECT)
          && Comparing.equal(getMainClassName(), second.getMainClassName())
          && Comparing.equal(getPackageName(), second.getPackageName())
          && Comparing.equal(getMethodName(), second.getMethodName())
          && Comparing.equal(getWorkingDirectory(), second.getWorkingDirectory())
          && Comparing.equal(VM_PARAMETERS, second.VM_PARAMETERS)
          && Comparing.equal(PARAMETERS, second.PARAMETERS)
          && Comparing.equal(myPattern, second.myPattern)
          && Comparing.equal(FORK_MODE, second.FORK_MODE)
          && Comparing.equal(DIR_NAME, second.DIR_NAME);
    }

    public int hashCode() {
      return Comparing.hashcode(TEST_OBJECT)
          ^ Comparing.hashcode(getMainClassName())
          ^ Comparing.hashcode(getPackageName())
          ^ Comparing.hashcode(getMethodName())
          ^ Comparing.hashcode(getWorkingDirectory())
          ^ Comparing.hashcode(VM_PARAMETERS)
          ^ Comparing.hashcode(PARAMETERS)
          ^ Comparing.hashcode(myPattern)
          ^ Comparing.hashcode(FORK_MODE)
          ^ Comparing.hashcode(DIR_NAME);
    }

    public TestSearchScope getScope() {
      return TEST_SEARCH_SCOPE.getScope();
    }

    public Data clone() {
      try {
        Data data = (Data) super.clone();
        data.TEST_SEARCH_SCOPE = new TestSearchScope.Wrapper();
        data.setScope(getScope());
        data.myEnvs = new LinkedHashMap<String, String>(myEnvs);
        return data;
      } catch (CloneNotSupportedException e) {
        throw new RuntimeException(e);
      }
    }

    public void setVMParameters(String value) {
      VM_PARAMETERS = value;
    }

    public String getVMParameters() {
      return VM_PARAMETERS;
    }

    public void setProgramParameters(String value) {
      PARAMETERS = value;
    }

    public String getProgramParameters() {
      return PARAMETERS;
    }

    public void setWorkingDirectory(String value) {
      WORKING_DIRECTORY = ExternalizablePath.urlValue(value);
    }

    public String getWorkingDirectory() {
      return ExternalizablePath.localPathValue(WORKING_DIRECTORY);
    }

    public Module setTestMethod(final Location<PsiMethod> methodLocation) {
      final PsiMethod method = methodLocation.getPsiElement();
      METHOD_NAME = method.getName();
      TEST_OBJECT = TEST_METHOD;
      return setMainClass(
          methodLocation instanceof MethodLocation
              ? ((MethodLocation) methodLocation).getContainingClass()
              : method.getContainingClass());
    }

    public boolean isGeneratedName(
        final String name, final JavaRunConfigurationModule configurationModule) {
      if (TEST_OBJECT == null) return true;
      if ((TEST_CLASS.equals(TEST_OBJECT) || TEST_METHOD.equals(TEST_OBJECT))
          && getMainClassName().length() == 0) {
        return JavaExecutionUtil.isNewName(name);
      }
      if (TEST_METHOD.equals(TEST_OBJECT) && getMethodName().length() == 0) {
        return JavaExecutionUtil.isNewName(name);
      }
      return Comparing.equal(name, getGeneratedName(configurationModule));
    }

    public String getGeneratedName(final JavaRunConfigurationModule configurationModule) {
      if (TEST_PACKAGE.equals(TEST_OBJECT) || TEST_DIRECTORY.equals(TEST_OBJECT)) {
        final String moduleName =
            TEST_SEARCH_SCOPE.getScope() == TestSearchScope.WHOLE_PROJECT
                ? ""
                : configurationModule.getModuleName();
        final String packageName = getPackageName();
        if (packageName.length() == 0) {
          if (moduleName.length() > 0) {
            return ExecutionBundle.message("default.junit.config.name.all.in.module", moduleName);
          }
          return DEFAULT_PACKAGE_NAME;
        }
        if (moduleName.length() > 0) {
          return ExecutionBundle.message(
              "default.junit.config.name.all.in.package.in.module", packageName, moduleName);
        }
        return packageName;
      }
      if (TEST_PATTERN.equals(TEST_OBJECT)) {
        final int size = myPattern.size();
        if (size == 0) return "Temp suite";
        return StringUtil.getShortName(myPattern.iterator().next())
            + (size > 1 ? " and " + (size - 1) + " more" : "");
      }
      final String className =
          JavaExecutionUtil.getPresentableClassName(getMainClassName(), configurationModule);
      if (TEST_METHOD.equals(TEST_OBJECT)) {
        return className + '.' + getMethodName();
      }

      return className;
    }

    public String getMainClassName() {
      return MAIN_CLASS_NAME != null ? MAIN_CLASS_NAME : "";
    }

    public String getPackageName() {
      return PACKAGE_NAME != null ? PACKAGE_NAME : "";
    }

    public String getMethodName() {
      return METHOD_NAME != null ? METHOD_NAME : "";
    }

    public String getDirName() {
      return DIR_NAME != null ? DIR_NAME : "";
    }

    public Set<String> getPatterns() {
      return myPattern;
    }

    public String getPatternPresentation() {
      final List<String> enabledTests = new ArrayList<String>();
      for (String pattern : myPattern) {
        enabledTests.add(pattern);
      }
      return StringUtil.join(enabledTests, "||");
    }

    public void setPatterns(Set<String> pattern) {
      myPattern = pattern;
    }

    public TestObject getTestObject(final Project project, final JUnitConfiguration configuration) {
      // TODO[dyoma]!
      return TestObject.fromString(TEST_OBJECT, project, configuration, null, null);
    }

    public Module setMainClass(final PsiClass testClass) {
      MAIN_CLASS_NAME = JavaExecutionUtil.getRuntimeQualifiedName(testClass);
      PsiPackage containingPackage = JUnitUtil.getContainingPackage(testClass);
      PACKAGE_NAME = containingPackage != null ? containingPackage.getQualifiedName() : "";
      return JavaExecutionUtil.findModule(testClass);
    }

    public void setScope(final TestSearchScope scope) {
      TEST_SEARCH_SCOPE.setScope(scope);
    }

    public Map<String, String> getEnvs() {
      return myEnvs;
    }

    public void setEnvs(final Map<String, String> envs) {
      myEnvs = envs;
    }

    public void setDirName(String dirName) {
      DIR_NAME = dirName;
    }
  }
}
  BeforeRunStepsPanel(StepsBeforeRunListener listener) {
    myListener = listener;
    myModel = new CollectionListModel<BeforeRunTask>();
    myList = new JBList(myModel);
    myList.getEmptyText().setText(ExecutionBundle.message("before.launch.panel.empty"));
    myList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    myList.setCellRenderer(new MyListCellRenderer());

    myModel.addListDataListener(
        new ListDataListener() {
          @Override
          public void intervalAdded(ListDataEvent e) {
            adjustVisibleRowCount();
            updateText();
          }

          @Override
          public void intervalRemoved(ListDataEvent e) {
            adjustVisibleRowCount();
            updateText();
          }

          @Override
          public void contentsChanged(ListDataEvent e) {}

          private void adjustVisibleRowCount() {
            myList.setVisibleRowCount(Math.max(4, Math.min(8, myModel.getSize())));
          }
        });

    ToolbarDecorator myDecorator = ToolbarDecorator.createDecorator(myList);
    if (!SystemInfo.isMac) {
      myDecorator.setAsUsualTopToolbar();
    }
    myDecorator.setEditAction(
        new AnActionButtonRunnable() {
          @Override
          public void run(AnActionButton button) {
            int index = myList.getSelectedIndex();
            if (index == -1) return;
            Pair<BeforeRunTask, BeforeRunTaskProvider<BeforeRunTask>> selection = getSelection();
            if (selection == null) return;
            BeforeRunTask task = selection.getFirst();
            BeforeRunTaskProvider<BeforeRunTask> provider = selection.getSecond();
            if (provider.configureTask(myRunConfiguration, task)) {
              myModel.setElementAt(task, index);
            }
          }
        });
    myDecorator.setEditActionUpdater(
        new AnActionButtonUpdater() {
          @Override
          public boolean isEnabled(AnActionEvent e) {
            Pair<BeforeRunTask, BeforeRunTaskProvider<BeforeRunTask>> selection = getSelection();
            return selection != null && selection.getSecond().isConfigurable();
          }
        });
    myDecorator.setAddAction(
        new AnActionButtonRunnable() {
          @Override
          public void run(AnActionButton button) {
            doAddAction(button);
          }
        });
    myDecorator.setAddActionUpdater(
        new AnActionButtonUpdater() {
          @Override
          public boolean isEnabled(AnActionEvent e) {
            return checkBeforeRunTasksAbility(true);
          }
        });

    myShowSettingsBeforeRunCheckBox =
        new JCheckBox(ExecutionBundle.message("configuration.edit.before.run"));
    myShowSettingsBeforeRunCheckBox.addActionListener(
        new ActionListener() {
          @Override
          public void actionPerformed(ActionEvent e) {
            updateText();
          }
        });

    myPanel = myDecorator.createPanel();

    setLayout(new BorderLayout());
    add(myPanel, BorderLayout.CENTER);
    add(myShowSettingsBeforeRunCheckBox, BorderLayout.SOUTH);
  }
 public SearchForTestsTask(@Nullable final Project project, final ServerSocket socket) {
   super(project, ExecutionBundle.message("searching.test.progress.title"), true);
   myServerSocket = socket;
 }
Example #29
0
 public SwitchDuplexConsoleViewAction() {
   super(
       ExecutionBundle.message("run.configuration.show.command.line.action.name"),
       null,
       AllIcons.Debugger.ToolConsole);
 }
  private static boolean userApprovesStopForIncompatibleConfigurations(
      Project project,
      String configName,
      List<RunContentDescriptor> runningIncompatibleDescriptors) {
    RunManagerImpl runManager = RunManagerImpl.getInstanceImpl(project);
    final RunManagerConfig config = runManager.getConfig();
    if (!config.isStopIncompatibleRequiresConfirmation()) return true;

    DialogWrapper.DoNotAskOption option =
        new DialogWrapper.DoNotAskOption() {
          @Override
          public boolean isToBeShown() {
            return config.isStopIncompatibleRequiresConfirmation();
          }

          @Override
          public void setToBeShown(boolean value, int exitCode) {
            config.setStopIncompatibleRequiresConfirmation(value);
          }

          @Override
          public boolean canBeHidden() {
            return true;
          }

          @Override
          public boolean shouldSaveOptionsOnCancel() {
            return false;
          }

          @NotNull
          @Override
          public String getDoNotShowMessage() {
            return CommonBundle.message("dialog.options.do.not.show");
          }
        };

    final StringBuilder names = new StringBuilder();
    for (final RunContentDescriptor descriptor : runningIncompatibleDescriptors) {
      String name = descriptor.getDisplayName();
      if (names.length() > 0) {
        names.append(", ");
      }
      names.append(
          StringUtil.isEmpty(name)
              ? ExecutionBundle.message("run.configuration.no.name")
              : String.format("'%s'", name));
    }

    //noinspection DialogTitleCapitalization
    return Messages.showOkCancelDialog(
            project,
            ExecutionBundle.message(
                "stop.incompatible.confirmation.message",
                configName,
                names.toString(),
                runningIncompatibleDescriptors.size()),
            ExecutionBundle.message(
                "incompatible.configuration.is.running.dialog.title",
                runningIncompatibleDescriptors.size()),
            ExecutionBundle.message("stop.incompatible.confirmation.button.text"),
            CommonBundle.message("button.cancel"),
            Messages.getQuestionIcon(),
            option)
        == Messages.OK;
  }