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 ImportRunProfile(VirtualFile file, Project project) {
      myFile = file;
      myProject = project;
      try {
        final Document document = JDOMUtil.loadDocument(VfsUtilCore.virtualToIoFile(myFile));
        final Element config = document.getRootElement().getChild("config");
        if (config != null) {
          String configTypeId = config.getAttributeValue("configId");
          if (configTypeId != null) {
            final ConfigurationType configurationType =
                ConfigurationTypeUtil.findConfigurationType(configTypeId);
            if (configurationType != null) {
              myConfiguration =
                  configurationType.getConfigurationFactories()[0].createTemplateConfiguration(
                      project);
              myConfiguration.setName(config.getAttributeValue("name"));
              myConfiguration.readExternal(config);

              final Executor executor =
                  ExecutorRegistry.getInstance().getExecutorById(DefaultRunExecutor.EXECUTOR_ID);
              if (executor != null) {
                if (myConfiguration instanceof SMRunnerConsolePropertiesProvider) {
                  myProperties =
                      ((SMRunnerConsolePropertiesProvider) myConfiguration)
                          .createTestConsoleProperties(executor);
                }
              }
            }
          }
        }
      } catch (Exception ignore) {
      }
    }
  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());
  }
Пример #4
0
 @Override
 public void onSuccess() {
   if (myOutputFile != null && myOutputFile.exists()) {
     AbstractImportTestsAction.adjustHistory(myProject);
     TestHistoryConfiguration.getInstance(myProject)
         .registerHistoryItem(
             myOutputFile.getName(),
             myConfiguration.getName(),
             myConfiguration.getType().getId());
   }
 }
Пример #5
0
 @Override
 @Nullable
 public RunConfigurableBeforeRunTask createTask(RunConfiguration runConfiguration) {
   if (runConfiguration.getProject().isInitialized()) {
     Collection<RunnerAndConfigurationSettings> configurations =
         RunManagerImpl.getInstanceImpl(runConfiguration.getProject()).getSortedConfigurations();
     if (configurations.isEmpty()
         || (configurations.size() == 1
             && configurations.iterator().next().getConfiguration() == runConfiguration)) {
       return null;
     }
   }
   return new RunConfigurableBeforeRunTask();
 }
Пример #6
0
    @Override
    public void run(@NotNull ProgressIndicator indicator) {
      try {
        SAXTransformerFactory transformerFactory =
            (SAXTransformerFactory) TransformerFactory.newInstance();
        TransformerHandler handler = transformerFactory.newTransformerHandler();
        handler.getTransformer().setOutputProperty(OutputKeys.INDENT, "yes");
        handler
            .getTransformer()
            .setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");

        final String configurationNameIncludedDate =
            PathUtil.suggestFileName(myConfiguration.getName())
                + " - "
                + new SimpleDateFormat(HISTORY_DATE_FORMAT).format(new Date());

        myOutputFile =
            new File(
                AbstractImportTestsAction.getTestHistoryRoot(myProject),
                configurationNameIncludedDate + ".xml");
        FileUtilRt.createParentDirs(myOutputFile);
        handler.setResult(new StreamResult(new FileWriter(myOutputFile)));
        final SMTestProxy.SMRootTestProxy root = myRoot;
        final RunConfiguration configuration = myConfiguration;
        if (root != null && configuration != null) {
          TestResultsXmlFormatter.execute(root, configuration, myConsoleProperties, handler);
        }
      } catch (ProcessCanceledException e) {
        throw e;
      } catch (Exception e) {
        LOG.info("Export to history failed", e);
      }
    }
 private static JavaParameters checkCanRun(RunConfiguration configuration)
     throws ExecutionException {
   final RunProfileState state;
   state =
       ExecutionEnvironmentBuilder.create(
               DefaultRunExecutor.getRunExecutorInstance(), configuration)
           .build()
           .getState();
   assertNotNull(state);
   assertTrue(state instanceof JavaCommandLine);
   if (state instanceof TestPackage) {
     @SuppressWarnings("UnusedDeclaration")
     final JavaParameters parameters = ((TestPackage) state).getJavaParameters();
     final SearchForTestsTask task = ((TestPackage) state).createSearchingForTestsTask();
     assertNotNull(task);
     task.startSearch();
   }
   try {
     configuration.checkConfiguration();
   } catch (RuntimeConfigurationError e) {
     fail("cannot run: " + e.getMessage());
   } catch (RuntimeConfigurationException e) {
     // ignore
   }
   return ((JavaCommandLine) state).getJavaParameters();
 }
 @Nullable
 private Pair<BeforeRunTask, BeforeRunTaskProvider<BeforeRunTask>> getSelection() {
   final int index = myList.getSelectedIndex();
   if (index == -1) return null;
   BeforeRunTask task = myModel.getElementAt(index);
   Key providerId = task.getProviderId();
   BeforeRunTaskProvider<BeforeRunTask> provider =
       BeforeRunTaskProvider.getProvider(myRunConfiguration.getProject(), providerId);
   return provider != null ? Pair.create(task, provider) : null;
 }
 /**
  * Returns original {@link RunConfiguration} from this context. For example, it could be some test
  * framework runtime configuration that had been launched and that had brought a result test tree
  * on which a right-click action was performed.
  *
  * @param type {@link ConfigurationType} instance to filter original runtime configuration by its
  *     type
  * @return {@link RunConfiguration} instance, it could be null
  */
 @Nullable
 public RunConfiguration getOriginalConfiguration(@Nullable ConfigurationType type) {
   if (type == null) {
     return myRuntimeConfiguration;
   }
   if (myRuntimeConfiguration != null
       && ConfigurationTypeUtil.equals(myRuntimeConfiguration.getType(), type)) {
     return myRuntimeConfiguration;
   }
   return null;
 }
  private void getAllRunBeforeRuns(BeforeRunTask task, Set<RunConfiguration> configurationSet) {
    if (task instanceof RunConfigurationBeforeRunProvider.RunConfigurableBeforeRunTask) {
      RunConfigurationBeforeRunProvider.RunConfigurableBeforeRunTask runTask =
          (RunConfigurationBeforeRunProvider.RunConfigurableBeforeRunTask) task;
      RunConfiguration configuration = runTask.getSettings().getConfiguration();

      List<BeforeRunTask> tasks =
          RunManagerImpl.getInstanceImpl(configuration.getProject())
              .getBeforeRunTasks(configuration);
      for (BeforeRunTask beforeRunTask : tasks) {
        if (beforeRunTask
            instanceof RunConfigurationBeforeRunProvider.RunConfigurableBeforeRunTask) {
          if (configurationSet.add(
              ((RunConfigurationBeforeRunProvider.RunConfigurableBeforeRunTask) beforeRunTask)
                  .getSettings()
                  .getConfiguration())) getAllRunBeforeRuns(beforeRunTask, configurationSet);
        }
      }
    }
  }
  void doReset(RunnerAndConfigurationSettings settings) {
    myRunConfiguration = settings.getConfiguration();

    originalTasks.clear();
    RunManagerImpl runManager = RunManagerImpl.getInstanceImpl(myRunConfiguration.getProject());
    originalTasks.addAll(runManager.getBeforeRunTasks(myRunConfiguration));
    myModel.replaceAll(originalTasks);
    myShowSettingsBeforeRunCheckBox.setSelected(settings.isEditBeforeRun());
    myShowSettingsBeforeRunCheckBox.setEnabled(!(isUnknown()));
    myPanel.setVisible(checkBeforeRunTasksAbility(false));
    updateText();
  }
 private static void addAppEngineRunConfiguration(
     @NotNull Module appEngineModule, @NotNull AppEngineGradleFacet facet) {
   final RunManagerEx runManager = RunManagerEx.getInstanceEx(appEngineModule.getProject());
   for (RunConfiguration configuration : runManager.getAllConfigurationsList()) {
     if (configuration.getName().equals(appEngineModule.getName())) {
       // TODO, we might want to check if this module already has a run configuration configured
       // instead of the name
       return;
     }
   }
   final RunnerAndConfigurationSettings settings =
       runManager.createRunConfiguration(
           appEngineModule.getName(), AppEngineRunConfigurationType.getInstance().getFactory());
   settings.setSingleton(true);
   final AppEngineRunConfiguration configuration =
       (AppEngineRunConfiguration) settings.getConfiguration();
   configuration.setModule(appEngineModule);
   // pull configuration out of gradle
   configuration.setSyncWithGradle(true);
   runManager.addConfiguration(settings, false);
 }
  private void checkCantRun(RunConfiguration configuration, String reasonBeginning)
      throws ExecutionException {
    // MockRunRequest request = new MockRunRequest(myProject);
    // CantRunException rejectReason;
    // try {
    //  configuration.runRequested(request);
    //  rejectReason = request.myRejectReason;
    // }
    // catch (CantRunException e) {
    //  rejectReason = e;
    // }
    // if (rejectReason == null) fail("Should not run");
    // rejectReason.getMessage().startsWith(reasonBeginning);

    try {
      configuration.checkConfiguration();
    } catch (RuntimeConfigurationError e) {
      assertTrue(e.getLocalizedMessage().startsWith(reasonBeginning));
      return;
    } catch (RuntimeConfigurationException ignored) {

    }

    RunProfileState state =
        configuration.getState(
            DefaultRunExecutor.getRunExecutorInstance(),
            new ExecutionEnvironmentBuilder(myProject, DefaultRunExecutor.getRunExecutorInstance())
                .runProfile(configuration)
                .build());
    assertTrue(state instanceof JavaCommandLine);

    try {
      ((JavaCommandLine) state).getJavaParameters();
    } catch (Throwable e) {
      assertTrue(e.getLocalizedMessage().startsWith(reasonBeginning));
      return;
    }

    fail("Should not run");
  }
 @Nullable
 @Override
 public KevAnnotationProcessorBeforeRunTask createTask(RunConfiguration runConfiguration) {
   if (runConfiguration instanceof KevScriptRunConfiguration) {
     System.out.println(
         "KevScriptBeforeTask createTask for RunConfig:" + runConfiguration.getClass());
     return new KevAnnotationProcessorBeforeRunTask(
         ID,
         runConfiguration,
         ((KevScriptRunConfiguration) runConfiguration).getConfigurationModule().getModule());
   }
   System.out.println("KevScriptBeforeTask null");
   return null;
 }
Пример #15
0
  @NotNull
  private static List<RunnerAndConfigurationSettings> getAvailableConfigurations(
      RunConfiguration runConfiguration) {
    Project project = runConfiguration.getProject();
    if (project == null || !project.isInitialized()) return Collections.emptyList();
    final RunManagerImpl runManager = RunManagerImpl.getInstanceImpl(project);

    final ArrayList<RunnerAndConfigurationSettings> configurations =
        new ArrayList<RunnerAndConfigurationSettings>(runManager.getSortedConfigurations());
    String executorId = DefaultRunExecutor.getRunExecutorInstance().getId();
    for (Iterator<RunnerAndConfigurationSettings> iterator = configurations.iterator();
        iterator.hasNext(); ) {
      RunnerAndConfigurationSettings settings = iterator.next();
      final ProgramRunner runner = ProgramRunnerUtil.getRunner(executorId, settings);
      if (runner == null || settings.getConfiguration() == runConfiguration) iterator.remove();
    }
    return configurations;
  }
 private boolean checkBeforeRunTasksAbility(boolean checkOnlyAddAction) {
   if (isUnknown()) {
     return false;
   }
   Set<Key> activeProviderKeys = getActiveProviderKeys();
   final BeforeRunTaskProvider<BeforeRunTask>[] providers =
       Extensions.getExtensions(
           BeforeRunTaskProvider.EXTENSION_POINT_NAME, myRunConfiguration.getProject());
   for (final BeforeRunTaskProvider<BeforeRunTask> provider : providers) {
     if (provider.createTask(myRunConfiguration) != null) {
       if (!checkOnlyAddAction) {
         return true;
       } else if (!provider.isSingleton() || !activeProviderKeys.contains(provider.getId())) {
         return true;
       }
     }
   }
   return false;
 }
 @Nullable
 @Override
 public RunProfileState getState(
     @NotNull Executor executor, @NotNull ExecutionEnvironment environment)
     throws ExecutionException {
   if (!myImported) {
     myImported = true;
     return new ImportedTestRunnableState(this, VfsUtilCore.virtualToIoFile(myFile));
   }
   if (myConfiguration != null) {
     try {
       return myConfiguration.getState(executor, environment);
     } catch (Throwable e) {
       LOG.info(e);
       throw new ExecutionException("Unable to run the configuration: settings are corrupted");
     }
   }
   throw new ExecutionException(
       "Unable to run the configuration: failed to detect test framework");
 }
Пример #18
0
  private void runConfigurations(
      final Executor executor, final List<RunConfiguration> runConfigurations, final int index) {
    if (index >= runConfigurations.size()) {
      stopRunningMultirunConfiguration.doneStaringConfigurations();
      return;
    }
    if (!stopRunningMultirunConfiguration.canContinueStartingConfigurations()) {
      stopRunningMultirunConfiguration.doneStaringConfigurations();
      // don't start more configurations if user stopped the plugin work.
      return;
    }

    final RunConfiguration runConfiguration = runConfigurations.get(index);
    final Project project = runConfiguration.getProject();
    final RunnerAndConfigurationSettings configuration =
        new RunnerAndConfigurationSettingsImpl(
            RunManagerImpl.getInstanceImpl(project), runConfiguration, false);

    boolean started = false;
    try {
      ProgramRunner runner =
          RunnerRegistry.getInstance().getRunner(executor.getId(), runConfiguration);
      if (runner == null) return;
      if (!checkRunConfiguration(executor, project, configuration)) return;

      runTriggers(executor, configuration);
      RunContentDescriptor runContentDescriptor =
          getRunContentDescriptor(runConfiguration, project);
      ExecutionEnvironment executionEnvironment =
          new ExecutionEnvironment(
              runner,
              DefaultExecutionTarget.INSTANCE,
              configuration,
              runContentDescriptor,
              project);

      runner.execute(
          executor,
          executionEnvironment,
          new ProgramRunner.Callback() {
            @SuppressWarnings("ConstantConditions")
            @Override
            public void processStarted(final RunContentDescriptor descriptor) {
              if (descriptor == null) {
                if (startOneByOne) {
                  // start next configuration..
                  runConfigurations(executor, runConfigurations, index + 1);
                }
                return;
              }

              final ProcessHandler processHandler = descriptor.getProcessHandler();
              if (processHandler != null) {
                processHandler.addProcessListener(
                    new ProcessAdapter() {
                      @SuppressWarnings("ConstantConditions")
                      @Override
                      public void startNotified(ProcessEvent processEvent) {
                        Content content = descriptor.getAttachedContent();
                        if (content != null) {
                          content.setIcon(descriptor.getIcon());
                          if (!stopRunningMultirunConfiguration
                              .canContinueStartingConfigurations()) {
                            // Multirun was stopped - destroy processes that are still starting up
                            processHandler.destroyProcess();

                            if (!content.isPinned() && !startOneByOne) {
                              // checks if not pinned, to avoid destroying already existed tab
                              // checks if start one by one - no need to close the console tab, as
                              // it's won't be shown
                              // as other checks disallow starting it

                              // content.getManager() can be null, if content is removed already as
                              // part of destroy above
                              if (content.getManager() != null) {
                                content.getManager().removeContent(content, false);
                              }
                            }
                          } else {
                            // mark all current console tab as pinned
                            content.setPinned(true);

                            // mark running process tab with *
                            content.setDisplayName(descriptor.getDisplayName() + "*");
                          }
                        }
                      }

                      @Override
                      public void processTerminated(final ProcessEvent processEvent) {
                        onTermination(processEvent, true);
                      }

                      @Override
                      public void processWillTerminate(
                          ProcessEvent processEvent, boolean willBeDestroyed) {
                        onTermination(processEvent, false);
                      }

                      private void onTermination(
                          final ProcessEvent processEvent, final boolean terminated) {
                        if (descriptor.getAttachedContent() == null) {
                          return;
                        }

                        LaterInvocator.invokeLater(
                            new Runnable() {
                              @Override
                              public void run() {
                                final Content content = descriptor.getAttachedContent();
                                if (content == null) return;

                                // exit code is 0 if the process completed successfully
                                final boolean completedSuccessfully =
                                    (terminated && processEvent.getExitCode() == 0);

                                if (hideSuccessProcess && completedSuccessfully) {
                                  // close the tab for the success process and exit - nothing else
                                  // could be done
                                  if (content.getManager() != null) {
                                    content.getManager().removeContent(content, false);
                                    return;
                                  }
                                }

                                if (!separateTabs && completedSuccessfully) {
                                  // un-pin the console tab if re-use is allowed and process
                                  // completed successfully,
                                  // so the tab could be re-used for other processes
                                  content.setPinned(false);
                                }

                                // remove the * used to identify running process
                                content.setDisplayName(descriptor.getDisplayName());

                                // add the alert icon in case if process existed with non-0 status
                                if (markFailedProcess && processEvent.getExitCode() != 0) {
                                  LaterInvocator.invokeLater(
                                      new Runnable() {
                                        @Override
                                        public void run() {
                                          content.setIcon(
                                              LayeredIcon.create(
                                                  content.getIcon(), AllIcons.Nodes.TabAlert));
                                        }
                                      });
                                }
                              }
                            });
                      }
                    });
              }
              stopRunningMultirunConfiguration.addProcess(project, processHandler);

              if (startOneByOne) {
                // start next configuration..
                runConfigurations(executor, runConfigurations, index + 1);
              }
            }
          });
      started = true;
    } catch (ExecutionException e) {
      ExecutionUtil.handleExecutionError(
          project, executor.getToolWindowId(), configuration.getConfiguration(), e);
    } finally {
      // start the next one
      if (!startOneByOne) {
        runConfigurations(executor, runConfigurations, index + 1);
      } else if (!started) {
        // failed to start current, means the chain is broken
        runConfigurations(executor, runConfigurations, index + 1);
      }
    }
  }
Пример #19
0
 private Method getMethod(RunConfiguration configuration) throws NoSuchMethodException {
   return configuration.getClass().getMethod("make", Project.class);
 }
 @Override
 public String getName() {
   return myImported && myConfiguration != null
       ? myConfiguration.getName()
       : myFile.getNameWithoutExtension();
 }