From f8d0775fd4205a907abafba5ca0875d5cbbc39a7 Mon Sep 17 00:00:00 2001 From: UNV Date: Sat, 5 Oct 2024 01:04:23 +0300 Subject: [PATCH 1/4] Code reformat of execution using IJ4 code style. --- .../execution/EditMavenPropertyDialog.java | 123 +- .../MavenArgumentsCompletionProvider.java | 224 ++-- .../execution/MavenConfigurationProducer.java | 82 +- .../maven/execution/MavenEditGoalDialog.java | 282 +++-- .../execution/MavenExecuteGoalDialog.java | 27 +- .../execution/MavenExecutionOptions.java | 151 +-- .../idea/maven/execution/MavenExecutor.java | 156 +-- .../execution/MavenExternalExecutor.java | 18 +- .../execution/MavenExternalParameters.java | 1057 ++++++++--------- .../maven/execution/MavenGoalLocation.java | 19 +- .../maven/execution/MavenJUnitPatcher.java | 100 +- .../MavenOrderEnumeratorHandler.java | 58 +- .../maven/execution/MavenPropertiesPanel.java | 98 +- .../maven/execution/MavenResumeAction.java | 467 ++++---- .../execution/MavenRunConfiguration.java | 373 +++--- .../execution/MavenRunConfigurationType.java | 305 ++--- .../idea/maven/execution/MavenRunner.java | 333 +++--- .../execution/MavenRunnerConfigurable.java | 88 +- ...nerConfigurableWithUseProjectSettings.java | 96 +- .../maven/execution/MavenRunnerPanel.java | 297 +++-- .../execution/MavenRunnerParameters.java | 486 ++++---- .../execution/MavenRunnerParametersPanel.java | 317 +++-- .../MavenRunnerParametersSettingEditor.java | 77 +- .../maven/execution/MavenRunnerSettings.java | 377 +++--- .../execution/MavenRunnerSettingsEditor.java | 76 +- .../execution/MavenSelectProjectPopup.java | 325 +++-- .../idea/maven/execution/RunnerBundle.java | 34 +- .../maven/execution/SoutMavenConsole.java | 83 +- .../cmd/CommandLineCompletionProvider.java | 150 ++- .../execution/cmd/ParametersListLexer.java | 95 +- 30 files changed, 3120 insertions(+), 3254 deletions(-) diff --git a/plugin/src/main/java/org/jetbrains/idea/maven/execution/EditMavenPropertyDialog.java b/plugin/src/main/java/org/jetbrains/idea/maven/execution/EditMavenPropertyDialog.java index e8a8f35c..4527d053 100644 --- a/plugin/src/main/java/org/jetbrains/idea/maven/execution/EditMavenPropertyDialog.java +++ b/plugin/src/main/java/org/jetbrains/idea/maven/execution/EditMavenPropertyDialog.java @@ -16,88 +16,87 @@ package org.jetbrains.idea.maven.execution; import consulo.ui.ex.awt.DialogWrapper; -import consulo.util.lang.Pair; import consulo.util.collection.ArrayUtil; +import consulo.util.lang.Pair; import javax.annotation.Nullable; - import javax.swing.*; import java.awt.event.FocusAdapter; import java.awt.event.FocusEvent; import java.awt.event.ItemEvent; -import java.awt.event.ItemListener; import java.util.Arrays; import java.util.Map; -public class EditMavenPropertyDialog extends DialogWrapper -{ - private JPanel contentPane; - private JComboBox myNameBox; - private JTextField myValueField; - private final Map myAvailableProperties; +public class EditMavenPropertyDialog extends DialogWrapper { + private JPanel contentPane; + private JComboBox myNameBox; + private JTextField myValueField; + private final Map myAvailableProperties; - public EditMavenPropertyDialog(@Nullable Pair value, Map availableProperties) { - super(false); - setTitle(value == null ? "Add Maven Property" : "Edit Maven Property"); + public EditMavenPropertyDialog(@Nullable Pair value, Map availableProperties) { + super(false); + setTitle(value == null ? "Add Maven Property" : "Edit Maven Property"); - myAvailableProperties = availableProperties; + myAvailableProperties = availableProperties; - installFocusListeners(); - fillAvailableProperties(); + installFocusListeners(); + fillAvailableProperties(); - if (value != null) { - myNameBox.getEditor().setItem(value.getFirst()); - myValueField.setText(value.getSecond()); - } + if (value != null) { + myNameBox.getEditor().setItem(value.getFirst()); + myValueField.setText(value.getSecond()); + } - installPropertySelectionListener(); + installPropertySelectionListener(); - init(); - } + init(); + } - private void installFocusListeners() { - myNameBox.addFocusListener(new FocusAdapter() { - @Override - public void focusGained(FocusEvent e) { - myNameBox.getEditor().selectAll(); - } - }); - myValueField.addFocusListener(new FocusAdapter() { - @Override - public void focusGained(FocusEvent e) { - myValueField.selectAll(); - } - }); - } + private void installFocusListeners() { + myNameBox.addFocusListener(new FocusAdapter() { + @Override + public void focusGained(FocusEvent e) { + myNameBox.getEditor().selectAll(); + } + }); + myValueField.addFocusListener(new FocusAdapter() { + @Override + public void focusGained(FocusEvent e) { + myValueField.selectAll(); + } + }); + } - private void installPropertySelectionListener() { - myNameBox.addItemListener(new ItemListener() { - public void itemStateChanged(ItemEvent e) { - if (e.getStateChange() != ItemEvent.SELECTED) return; - String key = (String)e.getItem(); - String value = myAvailableProperties.get(key); - if (value != null) myValueField.setText(value); - } - }); - } + private void installPropertySelectionListener() { + myNameBox.addItemListener(e -> { + if (e.getStateChange() != ItemEvent.SELECTED) { + return; + } + String key = (String)e.getItem(); + String value = myAvailableProperties.get(key); + if (value != null) { + myValueField.setText(value); + } + }); + } - private void fillAvailableProperties() { - String[] keys = ArrayUtil.toStringArray(myAvailableProperties.keySet()); - Arrays.sort(keys); - myNameBox.setModel(new DefaultComboBoxModel(keys)); - } + private void fillAvailableProperties() { + String[] keys = ArrayUtil.toStringArray(myAvailableProperties.keySet()); + Arrays.sort(keys); + myNameBox.setModel(new DefaultComboBoxModel(keys)); + } - @Nullable - protected JComponent createCenterPanel() { - return contentPane; - } + @Nullable + protected JComponent createCenterPanel() { + return contentPane; + } - @Override - public JComponent getPreferredFocusedComponent() { - return myNameBox; - } + @Override + public JComponent getPreferredFocusedComponent() { + return myNameBox; + } - public Pair getValue() { - return new Pair((String)myNameBox.getEditor().getItem(), myValueField.getText()); - } + public Pair getValue() { + return new Pair((String)myNameBox.getEditor().getItem(), myValueField.getText()); + } } diff --git a/plugin/src/main/java/org/jetbrains/idea/maven/execution/MavenArgumentsCompletionProvider.java b/plugin/src/main/java/org/jetbrains/idea/maven/execution/MavenArgumentsCompletionProvider.java index eb3dfeed..fa2cd32a 100644 --- a/plugin/src/main/java/org/jetbrains/idea/maven/execution/MavenArgumentsCompletionProvider.java +++ b/plugin/src/main/java/org/jetbrains/idea/maven/execution/MavenArgumentsCompletionProvider.java @@ -17,101 +17,151 @@ */ @SuppressWarnings("AccessStaticViaInstance") public class MavenArgumentsCompletionProvider extends CommandLineCompletionProvider { + private static final Options ourOptions; - private static final Options ourOptions; + static { + // Copy pasted from org.apache.maven.cli.CLIManager.() - static { - // Copy pasted from org.apache.maven.cli.CLIManager.() + Options options = new Options(); + options.addOption(OptionBuilder.withLongOpt("help").withDescription("Display help information").create('h')); + options.addOption( + OptionBuilder.withLongOpt("file") + .hasArg() + .withDescription("Force the use of an alternate POM file (or directory with pom.xml).") + .create('f') + ); + options.addOption(OptionBuilder.withLongOpt("define").hasArg().withDescription("Define a system property").create('D')); + options.addOption(OptionBuilder.withLongOpt("offline").withDescription("Work offline").create('o')); + options.addOption(OptionBuilder.withLongOpt("version").withDescription("Display version information").create('v')); + options.addOption(OptionBuilder.withLongOpt("quiet").withDescription("Quiet output - only show errors").create('q')); + options.addOption(OptionBuilder.withLongOpt("debug").withDescription("Produce execution debug output").create('X')); + options.addOption(OptionBuilder.withLongOpt("errors").withDescription("Produce execution error messages").create('e')); + options.addOption(OptionBuilder.withLongOpt("non-recursive").withDescription("Do not recurse into sub-projects").create('N')); + options.addOption( + OptionBuilder.withLongOpt("update-snapshots") + .withDescription("Forces a check for updated releases and snapshots on remote repositories") + .create('U') + ); + options.addOption( + OptionBuilder.withLongOpt("activate-profiles") + .withDescription("Comma-delimited list of profiles to activate") + .hasArg() + .create('P') + ); + options.addOption(OptionBuilder.withLongOpt("batch-mode").withDescription("Run in non-interactive (batch) mode").create('B')); + options.addOption(OptionBuilder.withLongOpt("no-snapshot-updates").withDescription("Suppress SNAPSHOT updates").create("nsu")); + options.addOption( + OptionBuilder.withLongOpt("strict-checksums").withDescription("Fail the build if checksums don't match").create('C') + ); + options.addOption(OptionBuilder.withLongOpt("lax-checksums").withDescription("Warn if checksums don't match").create('c')); + options.addOption( + OptionBuilder.withLongOpt("settings") + .withDescription("Alternate path for the user settings file") + .hasArg() + .create('s') + ); + options.addOption( + OptionBuilder.withLongOpt("global-settings") + .withDescription("Alternate path for the global settings file") + .hasArg() + .create("gs") + ); + options.addOption( + OptionBuilder.withLongOpt("toolchains") + .withDescription("Alternate path for the user toolchains file") + .hasArg() + .create('t') + ); + options.addOption( + OptionBuilder.withLongOpt("fail-fast") + .withDescription("Stop at first failure in reactorized builds") + .create("ff") + ); + options.addOption( + OptionBuilder.withLongOpt("fail-at-end") + .withDescription("Only fail the build afterwards; allow all non-impacted builds to continue") + .create("fae")); + options.addOption( + OptionBuilder.withLongOpt("fail-never") + .withDescription("NEVER fail the build, regardless of project result") + .create("fn") + ); + options.addOption( + OptionBuilder.withLongOpt("resume-from") + .hasArg() + .withDescription("Resume reactor from specified project") + .create("rf") + ); + options.addOption( + OptionBuilder.withLongOpt("projects") + .withDescription( + "Comma-delimited list of specified reactor projects to build instead of all projects. " + + "A project can be specified by [groupId]:artifactId or by its relative path." + ) + .hasArg() + .create("pl") + ); + options.addOption( + OptionBuilder.withLongOpt("also-make") + .withDescription("If project list is specified, also build projects required by the list") + .create("am") + ); + options.addOption( + OptionBuilder.withLongOpt("also-make-dependents") + .withDescription("If project list is specified, also build projects that depend on projects on the list") + .create("amd") + ); + options.addOption( + OptionBuilder.withLongOpt("log-file") + .hasArg() + .withDescription("Log file to where all build output will go.") + .create("l") + ); + options.addOption( + OptionBuilder.withLongOpt("show-version") + .withDescription("Display version information WITHOUT stopping build") + .create('V') + ); + options.addOption( + OptionBuilder.withLongOpt("encrypt-master-password") + .hasArg() + .withDescription("Encrypt master security password") + .create("emp") + ); + options.addOption( + OptionBuilder.withLongOpt("encrypt-password") + .hasArg() + .withDescription("Encrypt server password") + .create("ep") + ); + options.addOption( + OptionBuilder.withLongOpt("threads") + .hasArg() + .withDescription("Thread count, for instance 2.0C where C is core multiplied") + .create("T") + ); - Options options = new Options(); - options.addOption(OptionBuilder.withLongOpt("help").withDescription("Display help information").create('h')); - options.addOption( - OptionBuilder.withLongOpt("file").hasArg().withDescription("Force the use of an alternate POM file (or directory with pom.xml).") - .create( - 'f')); - options.addOption(OptionBuilder.withLongOpt("define").hasArg().withDescription("Define a system property").create('D')); - options.addOption(OptionBuilder.withLongOpt("offline").withDescription("Work offline").create('o')); - options.addOption(OptionBuilder.withLongOpt("version").withDescription("Display version information").create('v')); - options.addOption(OptionBuilder.withLongOpt("quiet").withDescription("Quiet output - only show errors").create('q')); - options.addOption(OptionBuilder.withLongOpt("debug").withDescription("Produce execution debug output").create('X')); - options.addOption(OptionBuilder.withLongOpt("errors").withDescription("Produce execution error messages").create('e')); - options.addOption(OptionBuilder.withLongOpt("non-recursive").withDescription("Do not recurse into sub-projects").create('N')); - options.addOption(OptionBuilder.withLongOpt("update-snapshots") - .withDescription("Forces a check for updated releases and snapshots on remote repositories").create( - 'U')); - options.addOption( - OptionBuilder.withLongOpt("activate-profiles").withDescription("Comma-delimited list of profiles to activate").hasArg().create( - 'P')); - options.addOption(OptionBuilder.withLongOpt("batch-mode").withDescription("Run in non-interactive (batch) mode").create('B')); - options.addOption(OptionBuilder.withLongOpt("no-snapshot-updates").withDescription("Suppress SNAPSHOT updates").create("nsu")); - options.addOption(OptionBuilder.withLongOpt("strict-checksums").withDescription("Fail the build if checksums don't match").create( - 'C')); - options.addOption(OptionBuilder.withLongOpt("lax-checksums").withDescription("Warn if checksums don't match").create('c')); - options.addOption(OptionBuilder.withLongOpt("settings").withDescription("Alternate path for the user settings file").hasArg().create( - 's')); - options.addOption( - OptionBuilder.withLongOpt("global-settings").withDescription("Alternate path for the global settings file").hasArg().create( - "gs")); - options - .addOption(OptionBuilder.withLongOpt("toolchains").withDescription("Alternate path for the user toolchains file").hasArg().create( - 't')); - options.addOption(OptionBuilder.withLongOpt("fail-fast").withDescription("Stop at first failure in reactorized builds").create( - "ff")); - options.addOption( - OptionBuilder.withLongOpt("fail-at-end").withDescription("Only fail the build afterwards; allow all non-impacted builds to continue") - .create( - "fae")); - options.addOption(OptionBuilder.withLongOpt("fail-never").withDescription("NEVER fail the build, regardless of project result").create( - "fn")); - options.addOption(OptionBuilder.withLongOpt("resume-from").hasArg().withDescription("Resume reactor from specified project").create( - "rf")); - options.addOption(OptionBuilder.withLongOpt("projects").withDescription( - "Comma-delimited list of specified reactor projects to build instead of all projects. A project can be specified by [groupId]:artifactId or by its relative path.") - .hasArg().create( - "pl")); - options.addOption( - OptionBuilder.withLongOpt("also-make").withDescription("If project list is specified, also build projects required by the list") - .create( - "am")); - options.addOption(OptionBuilder.withLongOpt("also-make-dependents") - .withDescription("If project list is specified, also build projects that depend on projects on the list").create( - "amd")); - options.addOption(OptionBuilder.withLongOpt("log-file").hasArg().withDescription("Log file to where all build output will go.").create( - "l")); - options - .addOption(OptionBuilder.withLongOpt("show-version").withDescription("Display version information WITHOUT stopping build").create( - 'V')); - options - .addOption(OptionBuilder.withLongOpt("encrypt-master-password").hasArg().withDescription("Encrypt master security password").create( - "emp")); - options.addOption(OptionBuilder.withLongOpt("encrypt-password").hasArg().withDescription("Encrypt server password").create( - "ep")); - options.addOption( - OptionBuilder.withLongOpt("threads").hasArg().withDescription("Thread count, for instance 2.0C where C is core multiplied").create( - "T")); + ourOptions = options; + } - ourOptions = options; - } + private volatile List myCachedElements; + private final Project myProject; - private volatile List myCachedElements; - private final Project myProject; + public MavenArgumentsCompletionProvider(@Nonnull Project project) { + super(ourOptions); + myProject = project; + } - public MavenArgumentsCompletionProvider(@Nonnull Project project) { - super(ourOptions); - myProject = project; - } + @Override + protected void addArgumentVariants(@Nonnull CompletionResultSet result) { + List cachedElements = myCachedElements; + if (cachedElements == null) { + cachedElements = MavenUtil.getPhaseVariants(MavenProjectsManager.getInstance(myProject)); - @Override - protected void addArgumentVariants(@Nonnull CompletionResultSet result) { - List cachedElements = myCachedElements; - if (cachedElements == null) { - cachedElements = MavenUtil.getPhaseVariants(MavenProjectsManager.getInstance(myProject)); + myCachedElements = cachedElements; + } - myCachedElements = cachedElements; + result.addAllElements(cachedElements); } - - result.addAllElements(cachedElements); - - } } diff --git a/plugin/src/main/java/org/jetbrains/idea/maven/execution/MavenConfigurationProducer.java b/plugin/src/main/java/org/jetbrains/idea/maven/execution/MavenConfigurationProducer.java index 9242d38b..df986666 100644 --- a/plugin/src/main/java/org/jetbrains/idea/maven/execution/MavenConfigurationProducer.java +++ b/plugin/src/main/java/org/jetbrains/idea/maven/execution/MavenConfigurationProducer.java @@ -37,53 +37,59 @@ @ExtensionImpl public class MavenConfigurationProducer extends RuntimeConfigurationProducer { - private PsiElement myPsiElement; + private PsiElement myPsiElement; - public MavenConfigurationProducer() { - super(MavenRunConfigurationType.getInstance()); - } + public MavenConfigurationProducer() { + super(MavenRunConfigurationType.getInstance()); + } - @Override - public PsiElement getSourceElement() { - return myPsiElement; - } + @Override + public PsiElement getSourceElement() { + return myPsiElement; + } - @Override - protected RunnerAndConfigurationSettings createConfigurationByElement(Location location, ConfigurationContext context) { - myPsiElement = location.getPsiElement(); - final MavenRunnerParameters params = createBuildParameters(location); - if (params == null) return null; + @Override + protected RunnerAndConfigurationSettings createConfigurationByElement(Location location, ConfigurationContext context) { + myPsiElement = location.getPsiElement(); + final MavenRunnerParameters params = createBuildParameters(location); + if (params == null) { + return null; + } - return MavenRunConfigurationType.createRunnerAndConfigurationSettings(null, null, params, location.getProject()); - } + return MavenRunConfigurationType.createRunnerAndConfigurationSettings(null, null, params, location.getProject()); + } - @Override - protected RunnerAndConfigurationSettings findExistingByElement(Location location, - @Nonnull List existingConfigurations, - ConfigurationContext context) { + @Override + protected RunnerAndConfigurationSettings findExistingByElement( + Location location, + @Nonnull List existingConfigurations, + ConfigurationContext context + ) { - final MavenRunnerParameters runnerParameters = createBuildParameters(location); - for (RunnerAndConfigurationSettings existingConfiguration : existingConfigurations) { - final RunConfiguration configuration = existingConfiguration.getConfiguration(); - if (configuration instanceof MavenRunConfiguration && - ((MavenRunConfiguration)configuration).getRunnerParameters().equals(runnerParameters)) { - return existingConfiguration; - } + final MavenRunnerParameters runnerParameters = createBuildParameters(location); + for (RunnerAndConfigurationSettings existingConfiguration : existingConfigurations) { + final RunConfiguration configuration = existingConfiguration.getConfiguration(); + if (configuration instanceof MavenRunConfiguration && + ((MavenRunConfiguration)configuration).getRunnerParameters().equals(runnerParameters)) { + return existingConfiguration; + } + } + return null; } - return null; - } - private static MavenRunnerParameters createBuildParameters(Location l) { - if (!(l instanceof MavenGoalLocation)) return null; + private static MavenRunnerParameters createBuildParameters(Location l) { + if (!(l instanceof MavenGoalLocation)) { + return null; + } - VirtualFile f = ((PsiFile)l.getPsiElement()).getVirtualFile(); - List goals = ((MavenGoalLocation)l).getGoals(); - MavenExplicitProfiles profiles = MavenProjectsManager.getInstance(l.getProject()).getExplicitProfiles(); + VirtualFile f = ((PsiFile)l.getPsiElement()).getVirtualFile(); + List goals = ((MavenGoalLocation)l).getGoals(); + MavenExplicitProfiles profiles = MavenProjectsManager.getInstance(l.getProject()).getExplicitProfiles(); - return new MavenRunnerParameters(true, f.getParent().getPath(), goals, profiles); - } + return new MavenRunnerParameters(true, f.getParent().getPath(), goals, profiles); + } - public int compareTo(Object o) { - return PREFERED; //To change body of implemented methods use File | Settings | File Templates. - } + public int compareTo(Object o) { + return PREFERED; //To change body of implemented methods use File | Settings | File Templates. + } } diff --git a/plugin/src/main/java/org/jetbrains/idea/maven/execution/MavenEditGoalDialog.java b/plugin/src/main/java/org/jetbrains/idea/maven/execution/MavenEditGoalDialog.java index 70a25660..c8b7aa78 100644 --- a/plugin/src/main/java/org/jetbrains/idea/maven/execution/MavenEditGoalDialog.java +++ b/plugin/src/main/java/org/jetbrains/idea/maven/execution/MavenEditGoalDialog.java @@ -36,151 +36,139 @@ import javax.swing.*; import java.util.Collection; -public class MavenEditGoalDialog extends DialogWrapper -{ - private final Project myProject; - @Nullable - private final Collection myHistory; - - private JPanel contentPane; - - private FixedSizeButton showProjectTreeButton; - private TextFieldWithBrowseButton workDirectoryField; - - private JPanel goalsPanel; - private JLabel goalsLabel; - private ComboBox goalsComboBox; - private EditorTextField goalsEditor; - - public MavenEditGoalDialog(@Nonnull Project project) - { - this(project, null); - } - - public MavenEditGoalDialog(@Nonnull Project project, @Nullable Collection history) - { - super(project, true); - myProject = project; - myHistory = history; - - setTitle("Edit Maven Goal"); - setUpDialog(); - setModal(true); - init(); - } - - private void setUpDialog() - { - JComponent goalComponent; - if(myHistory == null) - { - goalsEditor = new EditorTextField("", myProject, PlainTextFileType.INSTANCE); - goalComponent = goalsEditor; - - goalsLabel.setLabelFor(goalsEditor); - } - else - { - goalsComboBox = new ComboBox(ArrayUtil.toStringArray(myHistory)); - goalComponent = goalsComboBox; - - goalsLabel.setLabelFor(goalsComboBox); - - goalsComboBox.setLightWeightPopupEnabled(false); - - EditorComboBoxEditor editor = new StringComboboxEditor(myProject, PlainTextFileType.INSTANCE, goalsComboBox); - goalsComboBox.setRenderer(new EditorComboBoxRenderer(editor)); - - goalsComboBox.setEditable(true); - goalsComboBox.setEditor(editor); - goalsComboBox.setFocusable(true); - - goalsEditor = editor.getEditorComponent(); - } - - goalsPanel.add(goalComponent); - - new MavenArgumentsCompletionProvider(myProject).apply(goalsEditor); - - - MavenProjectsManager projectsManager = MavenProjectsManager.getInstance(myProject); - - showProjectTreeButton.setIcon(TargetAWT.to(AllIcons.Actions.Module)); - MavenSelectProjectPopup.attachToWorkingDirectoryField(projectsManager, workDirectoryField.getTextField(), showProjectTreeButton, goalsComboBox != null ? goalsComboBox : goalsEditor); - - workDirectoryField.addBrowseFolderListener(RunnerBundle.message("maven.select.maven.project.file"), "", myProject, new FileChooserDescriptor(false, true, false, false, false, false) - { - @Override - public boolean isFileSelectable(VirtualFile file) - { - if(!super.isFileSelectable(file)) - { - return false; - } - return file.findChild(MavenConstants.POM_XML) != null; - } - }); - } - - @Nullable - @Override - protected ValidationInfo doValidate() - { - if(workDirectoryField.getText().trim().isEmpty()) - { - return new ValidationInfo("Working directory is empty", workDirectoryField); - } - - return null; - } - - @Nonnull - public String getGoals() - { - if(goalsComboBox != null) - { - return (String) goalsComboBox.getEditor().getItem(); - } - else - { - return goalsEditor.getText(); - } - } - - public void setGoals(@Nonnull String goals) - { - if(goalsComboBox != null) - { - goalsComboBox.setSelectedItem(goals); - } - - goalsEditor.setText(goals); - } - - @Nonnull - public String getWorkDirectory() - { - return workDirectoryField.getText(); - } - - public void setWorkDirectory(@Nonnull String path) - { - workDirectoryField.setText(path); - } - - public void setSelectedMavenProject(@Nullable MavenProject mavenProject) - { - workDirectoryField.setText(mavenProject == null ? "" : mavenProject.getDirectory()); - } - - protected JComponent createCenterPanel() - { - return contentPane; - } - - public JComponent getPreferredFocusedComponent() - { - return goalsComboBox; - } - +public class MavenEditGoalDialog extends DialogWrapper { + private final Project myProject; + @Nullable + private final Collection myHistory; + + private JPanel contentPane; + + private FixedSizeButton showProjectTreeButton; + private TextFieldWithBrowseButton workDirectoryField; + + private JPanel goalsPanel; + private JLabel goalsLabel; + private ComboBox goalsComboBox; + private EditorTextField goalsEditor; + + public MavenEditGoalDialog(@Nonnull Project project) { + this(project, null); + } + + public MavenEditGoalDialog(@Nonnull Project project, @Nullable Collection history) { + super(project, true); + myProject = project; + myHistory = history; + + setTitle("Edit Maven Goal"); + setUpDialog(); + setModal(true); + init(); + } + + private void setUpDialog() { + JComponent goalComponent; + if (myHistory == null) { + goalsEditor = new EditorTextField("", myProject, PlainTextFileType.INSTANCE); + goalComponent = goalsEditor; + + goalsLabel.setLabelFor(goalsEditor); + } + else { + goalsComboBox = new ComboBox(ArrayUtil.toStringArray(myHistory)); + goalComponent = goalsComboBox; + + goalsLabel.setLabelFor(goalsComboBox); + + goalsComboBox.setLightWeightPopupEnabled(false); + + EditorComboBoxEditor editor = new StringComboboxEditor(myProject, PlainTextFileType.INSTANCE, goalsComboBox); + goalsComboBox.setRenderer(new EditorComboBoxRenderer(editor)); + + goalsComboBox.setEditable(true); + goalsComboBox.setEditor(editor); + goalsComboBox.setFocusable(true); + + goalsEditor = editor.getEditorComponent(); + } + + goalsPanel.add(goalComponent); + + new MavenArgumentsCompletionProvider(myProject).apply(goalsEditor); + + + MavenProjectsManager projectsManager = MavenProjectsManager.getInstance(myProject); + + showProjectTreeButton.setIcon(TargetAWT.to(AllIcons.Actions.Module)); + MavenSelectProjectPopup.attachToWorkingDirectoryField( + projectsManager, + workDirectoryField.getTextField(), + showProjectTreeButton, + goalsComboBox != null ? goalsComboBox : goalsEditor + ); + + workDirectoryField.addBrowseFolderListener( + RunnerBundle.message("maven.select.maven.project.file"), + "", + myProject, + new FileChooserDescriptor(false, true, false, false, false, false) { + @Override + public boolean isFileSelectable(VirtualFile file) { + if (!super.isFileSelectable(file)) { + return false; + } + return file.findChild(MavenConstants.POM_XML) != null; + } + } + ); + } + + @Nullable + @Override + protected ValidationInfo doValidate() { + if (workDirectoryField.getText().trim().isEmpty()) { + return new ValidationInfo("Working directory is empty", workDirectoryField); + } + + return null; + } + + @Nonnull + public String getGoals() { + if (goalsComboBox != null) { + return (String)goalsComboBox.getEditor().getItem(); + } + else { + return goalsEditor.getText(); + } + } + + public void setGoals(@Nonnull String goals) { + if (goalsComboBox != null) { + goalsComboBox.setSelectedItem(goals); + } + + goalsEditor.setText(goals); + } + + @Nonnull + public String getWorkDirectory() { + return workDirectoryField.getText(); + } + + public void setWorkDirectory(@Nonnull String path) { + workDirectoryField.setText(path); + } + + public void setSelectedMavenProject(@Nullable MavenProject mavenProject) { + workDirectoryField.setText(mavenProject == null ? "" : mavenProject.getDirectory()); + } + + protected JComponent createCenterPanel() { + return contentPane; + } + + public JComponent getPreferredFocusedComponent() { + return goalsComboBox; + } } diff --git a/plugin/src/main/java/org/jetbrains/idea/maven/execution/MavenExecuteGoalDialog.java b/plugin/src/main/java/org/jetbrains/idea/maven/execution/MavenExecuteGoalDialog.java index 13feca53..173fdcdb 100644 --- a/plugin/src/main/java/org/jetbrains/idea/maven/execution/MavenExecuteGoalDialog.java +++ b/plugin/src/main/java/org/jetbrains/idea/maven/execution/MavenExecuteGoalDialog.java @@ -26,21 +26,18 @@ /** * @author Sergey Evdokimov */ -public class MavenExecuteGoalDialog extends MavenEditGoalDialog -{ - public MavenExecuteGoalDialog(@Nonnull Project project, @Nullable Collection history) - { - super(project, history); +public class MavenExecuteGoalDialog extends MavenEditGoalDialog { + public MavenExecuteGoalDialog(@Nonnull Project project, @Nullable Collection history) { + super(project, history); - setTitle("Execute Maven Goal"); - } + setTitle("Execute Maven Goal"); + } - @Nonnull - @Override - protected Action getOKAction() - { - Action action = super.getOKAction(); - action.putValue(Action.NAME, "&Execute"); - return action; - } + @Nonnull + @Override + protected Action getOKAction() { + Action action = super.getOKAction(); + action.putValue(Action.NAME, "&Execute"); + return action; + } } diff --git a/plugin/src/main/java/org/jetbrains/idea/maven/execution/MavenExecutionOptions.java b/plugin/src/main/java/org/jetbrains/idea/maven/execution/MavenExecutionOptions.java index 341e4006..1c3baa50 100644 --- a/plugin/src/main/java/org/jetbrains/idea/maven/execution/MavenExecutionOptions.java +++ b/plugin/src/main/java/org/jetbrains/idea/maven/execution/MavenExecutionOptions.java @@ -19,98 +19,101 @@ import consulo.maven.rt.server.common.server.MavenServerSettings; public class MavenExecutionOptions { - public enum LoggingLevel { - DEBUG("Debug", MavenServerConsole.LEVEL_DEBUG), - INFO("Info", MavenServerConsole.LEVEL_INFO), - WARN("Warn", MavenServerConsole.LEVEL_WARN), - ERROR("Error", MavenServerConsole.LEVEL_ERROR), - FATAL("Fatal", MavenServerConsole.LEVEL_FATAL), - DISABLED("Disabled", MavenServerConsole.LEVEL_DISABLED); - - private final String myDisplayString; - private final int myLevel; - - LoggingLevel(String displayString, int level) { - myDisplayString = displayString; - myLevel = level; + public enum LoggingLevel { + DEBUG("Debug", MavenServerConsole.LEVEL_DEBUG), + INFO("Info", MavenServerConsole.LEVEL_INFO), + WARN("Warn", MavenServerConsole.LEVEL_WARN), + ERROR("Error", MavenServerConsole.LEVEL_ERROR), + FATAL("Fatal", MavenServerConsole.LEVEL_FATAL), + DISABLED("Disabled", MavenServerConsole.LEVEL_DISABLED); + + private final String myDisplayString; + private final int myLevel; + + LoggingLevel(String displayString, int level) { + myDisplayString = displayString; + myLevel = level; + } + + public String getDisplayString() { + return myDisplayString; + } + + public int getLevel() { + return myLevel; + } } - public String getDisplayString() { - return myDisplayString; - } + public enum FailureMode { + NOT_SET("Default", ""), + FAST("Fail Fast", "--fail-fast"), + AT_END("Fail At End", "--fail-at-end"), + NEVER("Never Fail", "--fail-never"); - public int getLevel() { - return myLevel; - } - } + private final String myDisplayString; + private final String myCommandLineOption; - public enum FailureMode { - NOT_SET("Default", ""), FAST("Fail Fast", "--fail-fast"), AT_END("Fail At End", "--fail-at-end"), NEVER("Never Fail", "--fail-never"); + FailureMode(String displayString, String commandLineOption) { + myDisplayString = displayString; + myCommandLineOption = commandLineOption; + } - private final String myDisplayString; - private final String myCommandLineOption; + public String getDisplayString() { + return myDisplayString; + } - FailureMode(String displayString, String commandLineOption) { - myDisplayString = displayString; - myCommandLineOption = commandLineOption; + public String getCommandLineOption() { + return myCommandLineOption; + } } - public String getDisplayString() { - return myDisplayString; - } + public enum ChecksumPolicy { + NOT_SET("No Global Policy", ""), + FAIL("Fail", "--strict-checksums"), + WARN("Warn", "--lax-checksums"); - public String getCommandLineOption() { - return myCommandLineOption; - } - } + private final String myDisplayString; + private final String myCommandLineOption; - public enum ChecksumPolicy { - NOT_SET("No Global Policy", ""), - FAIL("Fail", "--strict-checksums"), - WARN("Warn", "--lax-checksums"); + ChecksumPolicy(String displayString, String commandLineOption) { + myDisplayString = displayString; + myCommandLineOption = commandLineOption; + } - private final String myDisplayString; - private final String myCommandLineOption; + public String getDisplayString() { + return myDisplayString; + } - ChecksumPolicy(String displayString, String commandLineOption) { - myDisplayString = displayString; - myCommandLineOption = commandLineOption; + public String getCommandLineOption() { + return myCommandLineOption; + } } - public String getDisplayString() { - return myDisplayString; - } + public enum PluginUpdatePolicy { + UPDATE("Check For Updates", "--check-plugin-updates", MavenServerSettings.UpdatePolicy.ALWAYS_UPDATE), + DO_NOT_UPDATE("Do Not Update", "--no-plugin-updates", MavenServerSettings.UpdatePolicy.DO_NOT_UPDATE), + DEFAULT("Default", "", MavenServerSettings.UpdatePolicy.DO_NOT_UPDATE); - public String getCommandLineOption() { - return myCommandLineOption; - } - } + private final String myDisplayString; + private final String myCommandLineOption; + private final MavenServerSettings.UpdatePolicy myServerPolicy; - public enum PluginUpdatePolicy { - UPDATE("Check For Updates", "--check-plugin-updates", MavenServerSettings.UpdatePolicy.ALWAYS_UPDATE), - DO_NOT_UPDATE("Do Not Update", "--no-plugin-updates", MavenServerSettings.UpdatePolicy.DO_NOT_UPDATE), - DEFAULT("Default", "", MavenServerSettings.UpdatePolicy.DO_NOT_UPDATE); + PluginUpdatePolicy(String displayString, String commandLineOption, MavenServerSettings.UpdatePolicy policy) { + myDisplayString = displayString; + myCommandLineOption = commandLineOption; + myServerPolicy = policy; + } - private final String myDisplayString; - private final String myCommandLineOption; - private final MavenServerSettings.UpdatePolicy myServerPolicy; + public String getDisplayString() { + return myDisplayString; + } - PluginUpdatePolicy(String displayString, String commandLineOption, MavenServerSettings.UpdatePolicy policy) { - myDisplayString = displayString; - myCommandLineOption = commandLineOption; - myServerPolicy = policy; - } - - public String getDisplayString() { - return myDisplayString; - } - - public String getCommandLineOption() { - return myCommandLineOption; - } + public String getCommandLineOption() { + return myCommandLineOption; + } - public MavenServerSettings.UpdatePolicy getServerPolicy() { - return myServerPolicy; + public MavenServerSettings.UpdatePolicy getServerPolicy() { + return myServerPolicy; + } } - } } diff --git a/plugin/src/main/java/org/jetbrains/idea/maven/execution/MavenExecutor.java b/plugin/src/main/java/org/jetbrains/idea/maven/execution/MavenExecutor.java index 7fd1bb6a..8de66ea2 100644 --- a/plugin/src/main/java/org/jetbrains/idea/maven/execution/MavenExecutor.java +++ b/plugin/src/main/java/org/jetbrains/idea/maven/execution/MavenExecutor.java @@ -20,92 +20,98 @@ import consulo.application.progress.ProgressIndicator; import consulo.application.progress.ProgressManager; + import javax.annotation.Nullable; + import org.jetbrains.idea.maven.project.MavenConsole; import consulo.maven.rt.server.common.server.MavenServerConsole; import java.text.MessageFormat; public abstract class MavenExecutor { - final MavenRunnerParameters myParameters; - private final String myCaption; - protected MavenConsole myConsole; - private String myAction; - - private boolean stopped = true; - private boolean cancelled = false; - private int exitCode = 0; - - public MavenExecutor(MavenRunnerParameters parameters, - String caption, - MavenConsole console) { - myParameters = parameters; - myCaption = caption; - myConsole = console; - } - - public String getCaption() { - return myCaption; - } - - public MavenConsole getConsole() { - return myConsole; - } - - public void setAction(@Nullable final String action) { - myAction = action; - } - - public boolean isStopped() { - return stopped; - } - - void start() { - stopped = false; - } - - void stop() { - stopped = true; - myConsole.setOutputPaused(false); - } - - boolean isCancelled() { - return cancelled; - } - - public void cancel() { - cancelled = true; - stop(); - } - - protected void setExitCode(int exitCode) { - this.exitCode = exitCode; - } - - void displayProgress() { - final ProgressIndicator indicator = ProgressManager.getInstance().getProgressIndicator(); - if (indicator != null) { - indicator.setText(MessageFormat.format("{0} {1}", myAction != null ? myAction : RunnerBundle.message("maven.running"), - myParameters.getWorkingDirPath())); - indicator.setText2(myParameters.getGoals().toString()); + final MavenRunnerParameters myParameters; + private final String myCaption; + protected MavenConsole myConsole; + private String myAction; + + private boolean stopped = true; + private boolean cancelled = false; + private int exitCode = 0; + + public MavenExecutor(MavenRunnerParameters parameters, String caption, MavenConsole console) { + myParameters = parameters; + myCaption = caption; + myConsole = console; + } + + public String getCaption() { + return myCaption; + } + + public MavenConsole getConsole() { + return myConsole; + } + + public void setAction(@Nullable final String action) { + myAction = action; + } + + public boolean isStopped() { + return stopped; } - } - protected boolean printExitSummary() { - if (isCancelled()) { - myConsole.systemMessage(MavenServerConsole.LEVEL_INFO, RunnerBundle.message("maven.execution.aborted"), null); - return false; + void start() { + stopped = false; } - else if (exitCode == 0) { - myConsole.systemMessage(MavenServerConsole.LEVEL_INFO, RunnerBundle.message("maven.execution.finished"), null); - return true; + + void stop() { + stopped = true; + myConsole.setOutputPaused(false); + } + + boolean isCancelled() { + return cancelled; + } + + public void cancel() { + cancelled = true; + stop(); } - else { - myConsole - .systemMessage(MavenServerConsole.LEVEL_ERROR, RunnerBundle.message("maven.execution.terminated.abnormally", exitCode), null); - return false; + + protected void setExitCode(int exitCode) { + this.exitCode = exitCode; + } + + void displayProgress() { + final ProgressIndicator indicator = ProgressManager.getInstance().getProgressIndicator(); + if (indicator != null) { + indicator.setText(MessageFormat.format( + "{0} {1}", + myAction != null ? myAction : RunnerBundle.message("maven.running"), + myParameters.getWorkingDirPath() + )); + indicator.setText2(myParameters.getGoals().toString()); + } + } + + protected boolean printExitSummary() { + if (isCancelled()) { + myConsole.systemMessage(MavenServerConsole.LEVEL_INFO, RunnerBundle.message("maven.execution.aborted"), null); + return false; + } + else if (exitCode == 0) { + myConsole.systemMessage(MavenServerConsole.LEVEL_INFO, RunnerBundle.message("maven.execution.finished"), null); + return true; + } + else { + myConsole.systemMessage( + MavenServerConsole.LEVEL_ERROR, + RunnerBundle.message("maven.execution.terminated.abnormally", exitCode), + null + ); + return false; + } } - } - public abstract boolean execute(@Nullable ProgressIndicator indicator); + public abstract boolean execute(@Nullable ProgressIndicator indicator); } diff --git a/plugin/src/main/java/org/jetbrains/idea/maven/execution/MavenExternalExecutor.java b/plugin/src/main/java/org/jetbrains/idea/maven/execution/MavenExternalExecutor.java index 92e8b6ee..1f5fb1ba 100644 --- a/plugin/src/main/java/org/jetbrains/idea/maven/execution/MavenExternalExecutor.java +++ b/plugin/src/main/java/org/jetbrains/idea/maven/execution/MavenExternalExecutor.java @@ -47,11 +47,13 @@ public class MavenExternalExecutor extends MavenExecutor { private OwnJavaParameters myJavaParameters; private ExecutionException myParameterCreationError; - public MavenExternalExecutor(Project project, - @Nonnull MavenRunnerParameters parameters, - @Nullable MavenGeneralSettings coreSettings, - @Nullable MavenRunnerSettings runnerSettings, - @Nonnull MavenConsole console) { + public MavenExternalExecutor( + Project project, + @Nonnull MavenRunnerParameters parameters, + @Nullable MavenGeneralSettings coreSettings, + @Nullable MavenRunnerSettings runnerSettings, + @Nonnull MavenConsole console + ) { super(parameters, RunnerBundle.message("external.executor.caption"), console); try { @@ -80,7 +82,11 @@ public void onTextAvailable(ProcessEvent event, Key outputType) { myConsole.attachToProcess(myProcessHandler); } catch (ExecutionException e) { - myConsole.systemMessage(MavenServerConsole.LEVEL_FATAL, RunnerBundle.message("external.startup.failed", e.getMessage()), null); + myConsole.systemMessage( + MavenServerConsole.LEVEL_FATAL, + RunnerBundle.message("external.startup.failed", e.getMessage()), + null + ); return false; } diff --git a/plugin/src/main/java/org/jetbrains/idea/maven/execution/MavenExternalParameters.java b/plugin/src/main/java/org/jetbrains/idea/maven/execution/MavenExternalParameters.java index 4caf07e6..19be3d24 100644 --- a/plugin/src/main/java/org/jetbrains/idea/maven/execution/MavenExternalParameters.java +++ b/plugin/src/main/java/org/jetbrains/idea/maven/execution/MavenExternalParameters.java @@ -63,546 +63,519 @@ /** * @author Ralf Quebbemann */ -public class MavenExternalParameters -{ - private static final Logger LOG = Logger.getInstance(MavenExternalParameters.class); - - public static final String MAVEN_LAUNCHER_CLASS = "org.codehaus.classworlds.Launcher"; - - @NonNls - private static final String MAVEN_OPTS = "MAVEN_OPTS"; - - @Deprecated // Use createJavaParameters(Project,MavenRunnerParameters, MavenGeneralSettings,MavenRunnerSettings,MavenRunConfiguration) - @RequiredReadAction - public static OwnJavaParameters createJavaParameters(@Nullable final Project project, - @Nonnull final MavenRunnerParameters parameters, - @Nullable MavenGeneralSettings coreSettings, - @Nullable MavenRunnerSettings runnerSettings) throws ExecutionException - { - return createJavaParameters(project, parameters, coreSettings, runnerSettings, null); - } - - @RequiredReadAction - public static OwnJavaParameters createJavaParameters(@Nullable final Project project, @Nonnull final MavenRunnerParameters parameters) throws ExecutionException - { - return createJavaParameters(project, parameters, null, null, null); - } - - /** - * @param project - * @param parameters - * @param coreSettings - * @param runnerSettings - * @param runConfiguration used to creation fix if maven home not found - * @return - * @throws ExecutionException - */ - @RequiredReadAction - public static OwnJavaParameters createJavaParameters(@Nullable final Project project, - @Nonnull final MavenRunnerParameters parameters, - @Nullable MavenGeneralSettings coreSettings, - @Nullable MavenRunnerSettings runnerSettings, - @Nullable MavenRunConfiguration runConfiguration) throws ExecutionException - { - final OwnJavaParameters params = new OwnJavaParameters(); - - ApplicationManager.getApplication().assertReadAccessAllowed(); - - if(coreSettings == null) - { - coreSettings = project == null ? new MavenGeneralSettings() : MavenProjectsManager.getInstance(project).getGeneralSettings(); - } - if(runnerSettings == null) - { - runnerSettings = project == null ? new MavenRunnerSettings() : MavenRunner.getInstance(project).getState(); - } - - params.setWorkingDirectory(parameters.getWorkingDirFile()); - - final String mavenHome = resolveMavenHome(coreSettings, project, runConfiguration); - final String mavenVersion = MavenUtil.getMavenVersion(mavenHome); - - LanguageLevel defaultRunLevel = MavenJdkUtil.getDefaultRunLevel(mavenVersion); - - Sdk jdk = getJdk(runnerSettings, defaultRunLevel, project != null && MavenRunner.getInstance(project).getState() == runnerSettings); - - params.setJdk(jdk); - - if(StringUtil.compareVersionNumbers(mavenVersion, "3.3") >= 0) - { - params.getVMParametersList().addProperty("maven.multiModuleProjectDirectory", MavenServerUtil.findMavenBasedir(parameters.getWorkingDirFile()).getPath()); - } - - addVMParameters(params.getVMParametersList(), mavenHome, runnerSettings); - - File confFile = MavenUtil.getMavenConfFile(new File(mavenHome)); - if(!confFile.isFile()) - { - throw new ExecutionException("Configuration file is not exists in maven home: " + confFile.getAbsolutePath()); - } - - if(project != null && parameters.isResolveToWorkspace()) - { - try - { - confFile = patchConfFile(confFile, getArtifactResolverJars(mavenVersion)); - - File modulesPathsFile = dumpModulesPaths(project); - params.getVMParametersList().addProperty(MavenModuleMap.PATHS_FILE_PROPERTY, modulesPathsFile.getAbsolutePath()); - } - catch(IOException e) - { - LOG.error(e); - throw new ExecutionException("Failed to run maven configuration", e); - } - } - - params.getVMParametersList().addProperty("classworlds.conf", confFile.getPath()); - - for(String path : getMavenClasspathEntries(mavenHome)) - { - params.getClassPath().add(path); - } - - params.setEnv(new HashMap<>(runnerSettings.getEnvironmentProperties())); - params.setPassParentEnvs(runnerSettings.isPassParentEnv()); - - params.setMainClass(MAVEN_LAUNCHER_CLASS); - EncodingManager encodingManager = project == null ? EncodingManager.getInstance() : EncodingProjectManager.getInstance(project); - params.setCharset(encodingManager.getDefaultCharset()); - - addMavenParameters(params.getProgramParametersList(), mavenHome, coreSettings, runnerSettings, parameters); - - return params; - } - - private static File patchConfFile(File conf, List libraries) throws IOException - { - File tmpConf = FileUtil.createTempFile("idea-", "-mvn.conf"); - tmpConf.deleteOnExit(); - patchConfFile(conf, tmpConf, libraries); - - return tmpConf; - } - - private static void patchConfFile(File originalConf, File dest, List libraries) throws IOException - { - try (Scanner sc = new Scanner(originalConf)) - { - try (BufferedWriter out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(dest)))) - { - boolean patched = false; - - while(sc.hasNextLine()) - { - String line = sc.nextLine(); - - out.append(line); - out.newLine(); - - if(!patched && "[plexus.core]".equals(line)) - { - for(String library : libraries) - { - out.append("load ").append(library); - out.newLine(); - } - - patched = true; - } - } - } - } - } - - private static List getArtifactResolverJars(@Nullable String mavenVersion) throws IOException - { - Class marker = MavenArtifactResolvedM3RtMarker.class; - - if (mavenVersion != null) - { - if (StringUtil.compareVersionNumbers(mavenVersion, "3.1") >= 0) - { - marker = MavenArtifactResolvedM31RtMarker.class; - } - } - - List classpath = new ArrayList<>(2); - classpath.add(PathUtil.getJarPathForClass(MavenModuleMap.class)); - classpath.add(PathUtil.getJarPathForClass(marker)); - return classpath; - } - - private static File dumpModulesPaths(@Nonnull Project project) throws IOException - { - ApplicationManager.getApplication().assertReadAccessAllowed(); - - Properties res = new Properties(); - - MavenProjectsManager manager = MavenProjectsManager.getInstance(project); - - for(Module module : ModuleManager.getInstance(project).getModules()) - { - if(manager.isMavenizedModule(module)) - { - MavenProject mavenProject = manager.findProject(module); - if(mavenProject != null && !manager.isIgnored(mavenProject)) - { - res.setProperty(mavenProject.getMavenId().getGroupId() + ':' + mavenProject.getMavenId().getArtifactId() + ":pom" + ':' + mavenProject.getMavenId().getVersion(), mavenProject - .getFile().getPath()); - - res.setProperty(mavenProject.getMavenId().getGroupId() + ':' + mavenProject.getMavenId().getArtifactId() + ":test-jar" + ':' + mavenProject.getMavenId().getVersion(), - mavenProject.getTestOutputDirectory()); - - res.setProperty(mavenProject.getMavenId().getGroupId() + ':' + mavenProject.getMavenId().getArtifactId() + ':' + mavenProject.getPackaging() + ':' + mavenProject.getMavenId() - .getVersion(), mavenProject.getOutputDirectory()); - - } - } - } - - File file = new File(ContainerPathManager.get().getSystemPath(), "Maven/idea-projects-state-" + project.getLocationHash() + ".properties"); - FileUtil.ensureExists(file.getParentFile()); - - try (OutputStream out = new BufferedOutputStream(new FileOutputStream(file))) - { - res.store(out, null); - } - - return file; - } - - @Nullable - private static Sdk getJdk(MavenRunnerSettings runnerSettings, LanguageLevel languageLevel, boolean isGlobalRunnerSettings) throws ExecutionException - { - String name = runnerSettings.getJreName(); - - if(name != null) - { - return SdkTable.getInstance().findSdk(name); - } - - Sdk sdk = MavenJdkUtil.findSdkOfLevel(languageLevel, null); - if(sdk != null) - { - return sdk; - } - - throw new ExecutionException(RunnerBundle.message("maven.java.not.resolved")); - } - - public static void addVMParameters(ParametersList parametersList, String mavenHome, MavenRunnerSettings runnerSettings) - { - parametersList.addParametersString(System.getenv(MAVEN_OPTS)); - - parametersList.addParametersString(runnerSettings.getVmOptions()); - - parametersList.addProperty("maven.home", mavenHome); - } - - private static void addMavenParameters(ParametersList parametersList, String mavenHome, MavenGeneralSettings coreSettings, MavenRunnerSettings runnerSettings, MavenRunnerParameters parameters) - { - encodeCoreAndRunnerSettings(coreSettings, mavenHome, parametersList); - - if(runnerSettings.isSkipTests()) - { - parametersList.addProperty("skipTests", "true"); - } - - for(Map.Entry entry : runnerSettings.getMavenProperties().entrySet()) - { - if(entry.getKey().length() > 0) - { - parametersList.addProperty(entry.getKey(), entry.getValue()); - } - } - - for(String goal : parameters.getGoals()) - { - parametersList.add(goal); - } - - addOption(parametersList, "P", encodeProfiles(parameters.getProfilesMap())); - } - - private static void addOption(ParametersList cmdList, @NonNls String key, @NonNls String value) - { - if(!StringUtil.isEmptyOrSpaces(value)) - { - cmdList.add("-" + key); - cmdList.add(value); - } - } - - @Nonnull - public static String resolveMavenHome(@Nonnull MavenGeneralSettings coreSettings) throws ExecutionException - { - return resolveMavenHome(coreSettings, null, null); - } - - /** - * @param coreSettings - * @param project used to creation fix if maven home not found - * @param runConfiguration used to creation fix if maven home not found - * @return - * @throws ExecutionException - */ - @Nonnull - public static String resolveMavenHome(@Nonnull MavenGeneralSettings coreSettings, @Nullable Project project, @Nullable MavenRunConfiguration runConfiguration) throws ExecutionException - { - final File file = MavenUtil.resolveMavenHomeDirectory(coreSettings.getMavenBundleName()); - - if(file == null) - { - throw createExecutionException(RunnerBundle.message("external.maven.home.no.default"), RunnerBundle.message("external.maven.home.no.default.with.fix"), coreSettings, project, - runConfiguration); - } - - if(!file.exists()) - { - throw createExecutionException(RunnerBundle.message("external.maven.home.does.not.exist", file.getPath()), RunnerBundle.message("external.maven.home.does.not.exist.with.fix", file - .getPath()), coreSettings, project, runConfiguration); - } - - if(!MavenUtil.isValidMavenHome(file)) - { - throw createExecutionException(RunnerBundle.message("external.maven.home.invalid", file.getPath()), RunnerBundle.message("external.maven.home.invalid.with.fix", file.getPath()), - coreSettings, project, runConfiguration); - } - - try - { - return file.getCanonicalPath(); - } - catch(IOException e) - { - throw new ExecutionException(e.getMessage(), e); - } - } - - private static ExecutionException createExecutionException(String text, - String textWithFix, - @Nonnull MavenGeneralSettings coreSettings, - @Nullable Project project, - @Nullable MavenRunConfiguration runConfiguration) - { - Project notNullProject = project; - if(notNullProject == null) - { - if(runConfiguration == null) - { - return new ExecutionException(text); - } - notNullProject = runConfiguration.getProject(); - if(notNullProject == null) - { - return new ExecutionException(text); - } - } - - if(coreSettings == MavenProjectsManager.getInstance(notNullProject).getGeneralSettings()) - { - return new ProjectSettingsOpenerExecutionException(textWithFix, notNullProject); - } - - if(runConfiguration != null) - { - Project runCfgProject = runConfiguration.getProject(); - if(runCfgProject != null) - { - if(RunManager.getInstance(runCfgProject).findSettings(runConfiguration) != null) - { - return new RunConfigurationOpenerExecutionException(textWithFix, runConfiguration); - } - } - } - - return new ExecutionException(text); - } - - @SuppressWarnings({"HardCodedStringLiteral"}) - private static List getMavenClasspathEntries(final String mavenHome) - { - File mavenHomeBootAsFile = new File(new File(mavenHome, "core"), "boot"); - // if the dir "core/boot" does not exist we are using a Maven version > 2.0.5 - // in this case the classpath must be constructed from the dir "boot" - if(!mavenHomeBootAsFile.exists()) - { - mavenHomeBootAsFile = new File(mavenHome, "boot"); - } - - List classpathEntries = new ArrayList<>(); - - File[] files = mavenHomeBootAsFile.listFiles(); - if(files != null) - { - for(File file : files) - { - if(file.getName().contains("classworlds")) - { - classpathEntries.add(file.getAbsolutePath()); - } - } - } - - return classpathEntries; - } - - private static void encodeCoreAndRunnerSettings(MavenGeneralSettings coreSettings, String mavenHome, ParametersList cmdList) - { - if(coreSettings.isWorkOffline()) - { - cmdList.add("--offline"); - } - - boolean atLeastMaven3 = MavenUtil.isMaven3(mavenHome); - - if(!atLeastMaven3) - { - addIfNotEmpty(cmdList, coreSettings.getPluginUpdatePolicy().getCommandLineOption()); - - if(!coreSettings.isUsePluginRegistry()) - { - cmdList.add("--no-plugin-registry"); - } - } - - if(coreSettings.getOutputLevel() == MavenExecutionOptions.LoggingLevel.DEBUG) - { - cmdList.add("--debug"); - } - if(coreSettings.isNonRecursive()) - { - cmdList.add("--non-recursive"); - } - if(coreSettings.isPrintErrorStackTraces()) - { - cmdList.add("--errors"); - } - - if(coreSettings.isAlwaysUpdateSnapshots()) - { - cmdList.add("--update-snapshots"); - } - - if(StringUtil.isNotEmpty(coreSettings.getThreads())) - { - cmdList.add("-T", coreSettings.getThreads()); - } - - addIfNotEmpty(cmdList, coreSettings.getFailureBehavior().getCommandLineOption()); - addIfNotEmpty(cmdList, coreSettings.getChecksumPolicy().getCommandLineOption()); - - addOption(cmdList, "s", coreSettings.getUserSettingsFile()); - if(!StringUtil.isEmptyOrSpaces(coreSettings.getLocalRepository())) - { - cmdList.addProperty("maven.repo.local", coreSettings.getLocalRepository()); - } - } - - private static void addIfNotEmpty(ParametersList parametersList, @Nullable String value) - { - if(!StringUtil.isEmptyOrSpaces(value)) - { - parametersList.add(value); - } - } - - private static String encodeProfiles(Map profiles) - { - StringBuilder stringBuilder = new StringBuilder(); - for(Map.Entry entry : profiles.entrySet()) - { - if(stringBuilder.length() != 0) - { - stringBuilder.append(","); - } - if(!entry.getValue()) - { - stringBuilder.append("!"); - } - stringBuilder.append(entry.getKey()); - } - return stringBuilder.toString(); - } - - private static class ProjectSettingsOpenerExecutionException extends WithHyperlinkExecutionException - { - private final Project myProject; - - public ProjectSettingsOpenerExecutionException(final String s, Project project) - { - super(s); - myProject = project; - } - - @Override - protected void hyperlinkClicked() - { - ShowSettingsUtil.getInstance().showSettingsDialog(myProject, MavenSettings.DISPLAY_NAME); - } - } - - private static class ProjectJdkSettingsOpenerExecutionException extends WithHyperlinkExecutionException - { - - private final Project myProject; - - public ProjectJdkSettingsOpenerExecutionException(final String s, Project project) - { - super(s); - myProject = project; - } - - @Override - protected void hyperlinkClicked() - { - ShowSettingsUtil.getInstance().showProjectStructureDialog(myProject); - } - } - - private static class RunConfigurationOpenerExecutionException extends WithHyperlinkExecutionException - { - - private final MavenRunConfiguration myRunConfiguration; - - public RunConfigurationOpenerExecutionException(final String s, MavenRunConfiguration runConfiguration) - { - super(s); - myRunConfiguration = runConfiguration; - } - - @Override - protected void hyperlinkClicked() - { - Project project = myRunConfiguration.getProject(); - EditConfigurationsDialog dialog = new EditConfigurationsDialog(project); - dialog.show(); - } - } - - private static abstract class WithHyperlinkExecutionException extends ExecutionException implements HyperlinkListener, NotificationListener - { - public WithHyperlinkExecutionException(String s) - { - super(s); - } - - protected abstract void hyperlinkClicked(); - - @Override - public final void hyperlinkUpdate(HyperlinkEvent e) - { - if(e.getEventType() == HyperlinkEvent.EventType.ACTIVATED) - { - hyperlinkClicked(); - } - } - - @Override - public final void hyperlinkUpdate(@Nonnull Notification notification, @Nonnull HyperlinkEvent event) - { - hyperlinkUpdate(event); - } - } +public class MavenExternalParameters { + private static final Logger LOG = Logger.getInstance(MavenExternalParameters.class); + + public static final String MAVEN_LAUNCHER_CLASS = "org.codehaus.classworlds.Launcher"; + + @NonNls + private static final String MAVEN_OPTS = "MAVEN_OPTS"; + + @Deprecated // Use createJavaParameters(Project,MavenRunnerParameters, MavenGeneralSettings,MavenRunnerSettings,MavenRunConfiguration) + @RequiredReadAction + public static OwnJavaParameters createJavaParameters( + @Nullable final Project project, + @Nonnull final MavenRunnerParameters parameters, + @Nullable MavenGeneralSettings coreSettings, + @Nullable MavenRunnerSettings runnerSettings + ) throws ExecutionException { + return createJavaParameters(project, parameters, coreSettings, runnerSettings, null); + } + + @RequiredReadAction + public static OwnJavaParameters createJavaParameters( + @Nullable final Project project, + @Nonnull final MavenRunnerParameters parameters + ) throws ExecutionException { + return createJavaParameters(project, parameters, null, null, null); + } + + /** + * @param project + * @param parameters + * @param coreSettings + * @param runnerSettings + * @param runConfiguration used to creation fix if maven home not found + * @return + * @throws ExecutionException + */ + @RequiredReadAction + public static OwnJavaParameters createJavaParameters( + @Nullable final Project project, + @Nonnull final MavenRunnerParameters parameters, + @Nullable MavenGeneralSettings coreSettings, + @Nullable MavenRunnerSettings runnerSettings, + @Nullable MavenRunConfiguration runConfiguration + ) throws ExecutionException { + final OwnJavaParameters params = new OwnJavaParameters(); + + ApplicationManager.getApplication().assertReadAccessAllowed(); + + if (coreSettings == null) { + coreSettings = project == null ? new MavenGeneralSettings() : MavenProjectsManager.getInstance(project).getGeneralSettings(); + } + if (runnerSettings == null) { + runnerSettings = project == null ? new MavenRunnerSettings() : MavenRunner.getInstance(project).getState(); + } + + params.setWorkingDirectory(parameters.getWorkingDirFile()); + + final String mavenHome = resolveMavenHome(coreSettings, project, runConfiguration); + final String mavenVersion = MavenUtil.getMavenVersion(mavenHome); + + LanguageLevel defaultRunLevel = MavenJdkUtil.getDefaultRunLevel(mavenVersion); + + Sdk jdk = getJdk( + runnerSettings, + defaultRunLevel, + project != null && MavenRunner.getInstance(project).getState() == runnerSettings + ); + + params.setJdk(jdk); + + if (StringUtil.compareVersionNumbers(mavenVersion, "3.3") >= 0) { + params.getVMParametersList().addProperty( + "maven.multiModuleProjectDirectory", + MavenServerUtil.findMavenBasedir(parameters.getWorkingDirFile()).getPath() + ); + } + + addVMParameters(params.getVMParametersList(), mavenHome, runnerSettings); + + File confFile = MavenUtil.getMavenConfFile(new File(mavenHome)); + if (!confFile.isFile()) { + throw new ExecutionException("Configuration file is not exists in maven home: " + confFile.getAbsolutePath()); + } + + if (project != null && parameters.isResolveToWorkspace()) { + try { + confFile = patchConfFile(confFile, getArtifactResolverJars(mavenVersion)); + + File modulesPathsFile = dumpModulesPaths(project); + params.getVMParametersList().addProperty(MavenModuleMap.PATHS_FILE_PROPERTY, modulesPathsFile.getAbsolutePath()); + } + catch (IOException e) { + LOG.error(e); + throw new ExecutionException("Failed to run maven configuration", e); + } + } + + params.getVMParametersList().addProperty("classworlds.conf", confFile.getPath()); + + for (String path : getMavenClasspathEntries(mavenHome)) { + params.getClassPath().add(path); + } + + params.setEnv(new HashMap<>(runnerSettings.getEnvironmentProperties())); + params.setPassParentEnvs(runnerSettings.isPassParentEnv()); + + params.setMainClass(MAVEN_LAUNCHER_CLASS); + EncodingManager encodingManager = project == null ? EncodingManager.getInstance() : EncodingProjectManager.getInstance(project); + params.setCharset(encodingManager.getDefaultCharset()); + + addMavenParameters(params.getProgramParametersList(), mavenHome, coreSettings, runnerSettings, parameters); + + return params; + } + + private static File patchConfFile(File conf, List libraries) throws IOException { + File tmpConf = FileUtil.createTempFile("idea-", "-mvn.conf"); + tmpConf.deleteOnExit(); + patchConfFile(conf, tmpConf, libraries); + + return tmpConf; + } + + private static void patchConfFile(File originalConf, File dest, List libraries) throws IOException { + try (Scanner sc = new Scanner(originalConf)) { + try (BufferedWriter out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(dest)))) { + boolean patched = false; + + while (sc.hasNextLine()) { + String line = sc.nextLine(); + + out.append(line); + out.newLine(); + + if (!patched && "[plexus.core]".equals(line)) { + for (String library : libraries) { + out.append("load ").append(library); + out.newLine(); + } + + patched = true; + } + } + } + } + } + + private static List getArtifactResolverJars(@Nullable String mavenVersion) throws IOException { + Class marker = MavenArtifactResolvedM3RtMarker.class; + + if (mavenVersion != null) { + if (StringUtil.compareVersionNumbers(mavenVersion, "3.1") >= 0) { + marker = MavenArtifactResolvedM31RtMarker.class; + } + } + + List classpath = new ArrayList<>(2); + classpath.add(PathUtil.getJarPathForClass(MavenModuleMap.class)); + classpath.add(PathUtil.getJarPathForClass(marker)); + return classpath; + } + + private static File dumpModulesPaths(@Nonnull Project project) throws IOException { + ApplicationManager.getApplication().assertReadAccessAllowed(); + + Properties res = new Properties(); + + MavenProjectsManager manager = MavenProjectsManager.getInstance(project); + + for (Module module : ModuleManager.getInstance(project).getModules()) { + if (manager.isMavenizedModule(module)) { + MavenProject mavenProject = manager.findProject(module); + if (mavenProject != null && !manager.isIgnored(mavenProject)) { + res.setProperty( + mavenProject.getMavenId().getGroupId() + ':' + + mavenProject.getMavenId().getArtifactId() + ":pom:" + + mavenProject.getMavenId().getVersion(), + mavenProject.getFile().getPath() + ); + + res.setProperty( + mavenProject.getMavenId().getGroupId() + ':' + + mavenProject.getMavenId().getArtifactId() + ":test-jar:" + + mavenProject.getMavenId().getVersion(), + mavenProject.getTestOutputDirectory() + ); + + res.setProperty( + mavenProject.getMavenId().getGroupId() + ':' + + mavenProject.getMavenId().getArtifactId() + ':' + + mavenProject.getPackaging() + ':' + + mavenProject.getMavenId().getVersion(), + mavenProject.getOutputDirectory() + ); + + } + } + } + + File file = new File( + ContainerPathManager.get().getSystemPath(), + "Maven/idea-projects-state-" + project.getLocationHash() + ".properties" + ); + FileUtil.ensureExists(file.getParentFile()); + + try (OutputStream out = new BufferedOutputStream(new FileOutputStream(file))) { + res.store(out, null); + } + + return file; + } + + @Nullable + private static Sdk getJdk( + MavenRunnerSettings runnerSettings, + LanguageLevel languageLevel, + boolean isGlobalRunnerSettings + ) throws ExecutionException { + String name = runnerSettings.getJreName(); + + if (name != null) { + return SdkTable.getInstance().findSdk(name); + } + + Sdk sdk = MavenJdkUtil.findSdkOfLevel(languageLevel, null); + if (sdk != null) { + return sdk; + } + + throw new ExecutionException(RunnerBundle.message("maven.java.not.resolved")); + } + + public static void addVMParameters(ParametersList parametersList, String mavenHome, MavenRunnerSettings runnerSettings) { + parametersList.addParametersString(System.getenv(MAVEN_OPTS)); + + parametersList.addParametersString(runnerSettings.getVmOptions()); + + parametersList.addProperty("maven.home", mavenHome); + } + + private static void addMavenParameters( + ParametersList parametersList, + String mavenHome, + MavenGeneralSettings coreSettings, + MavenRunnerSettings runnerSettings, + MavenRunnerParameters parameters + ) { + encodeCoreAndRunnerSettings(coreSettings, mavenHome, parametersList); + + if (runnerSettings.isSkipTests()) { + parametersList.addProperty("skipTests", "true"); + } + + for (Map.Entry entry : runnerSettings.getMavenProperties().entrySet()) { + if (entry.getKey().length() > 0) { + parametersList.addProperty(entry.getKey(), entry.getValue()); + } + } + + for (String goal : parameters.getGoals()) { + parametersList.add(goal); + } + + addOption(parametersList, "P", encodeProfiles(parameters.getProfilesMap())); + } + + private static void addOption(ParametersList cmdList, @NonNls String key, @NonNls String value) { + if (!StringUtil.isEmptyOrSpaces(value)) { + cmdList.add("-" + key); + cmdList.add(value); + } + } + + @Nonnull + public static String resolveMavenHome(@Nonnull MavenGeneralSettings coreSettings) throws ExecutionException { + return resolveMavenHome(coreSettings, null, null); + } + + /** + * @param coreSettings + * @param project used to creation fix if maven home not found + * @param runConfiguration used to creation fix if maven home not found + * @return + * @throws ExecutionException + */ + @Nonnull + public static String resolveMavenHome( + @Nonnull MavenGeneralSettings coreSettings, + @Nullable Project project, + @Nullable MavenRunConfiguration runConfiguration + ) throws ExecutionException { + final File file = MavenUtil.resolveMavenHomeDirectory(coreSettings.getMavenBundleName()); + + if (file == null) { + throw createExecutionException( + RunnerBundle.message("external.maven.home.no.default"), + RunnerBundle.message("external.maven.home.no.default.with.fix"), + coreSettings, + project, + runConfiguration + ); + } + + if (!file.exists()) { + throw createExecutionException( + RunnerBundle.message("external.maven.home.does.not.exist", file.getPath()), + RunnerBundle.message("external.maven.home.does.not.exist.with.fix", file.getPath()), + coreSettings, + project, + runConfiguration + ); + } + + if (!MavenUtil.isValidMavenHome(file)) { + throw createExecutionException( + RunnerBundle.message("external.maven.home.invalid", file.getPath()), + RunnerBundle.message("external.maven.home.invalid.with.fix", file.getPath()), + coreSettings, + project, + runConfiguration + ); + } + + try { + return file.getCanonicalPath(); + } + catch (IOException e) { + throw new ExecutionException(e.getMessage(), e); + } + } + + private static ExecutionException createExecutionException( + String text, + String textWithFix, + @Nonnull MavenGeneralSettings coreSettings, + @Nullable Project project, + @Nullable MavenRunConfiguration runConfiguration + ) { + Project notNullProject = project; + if (notNullProject == null) { + if (runConfiguration == null) { + return new ExecutionException(text); + } + notNullProject = runConfiguration.getProject(); + if (notNullProject == null) { + return new ExecutionException(text); + } + } + + if (coreSettings == MavenProjectsManager.getInstance(notNullProject).getGeneralSettings()) { + return new ProjectSettingsOpenerExecutionException(textWithFix, notNullProject); + } + + if (runConfiguration != null) { + Project runCfgProject = runConfiguration.getProject(); + if (runCfgProject != null) { + if (RunManager.getInstance(runCfgProject).findSettings(runConfiguration) != null) { + return new RunConfigurationOpenerExecutionException(textWithFix, runConfiguration); + } + } + } + + return new ExecutionException(text); + } + + @SuppressWarnings({"HardCodedStringLiteral"}) + private static List getMavenClasspathEntries(final String mavenHome) { + File mavenHomeBootAsFile = new File(new File(mavenHome, "core"), "boot"); + // if the dir "core/boot" does not exist we are using a Maven version > 2.0.5 + // in this case the classpath must be constructed from the dir "boot" + if (!mavenHomeBootAsFile.exists()) { + mavenHomeBootAsFile = new File(mavenHome, "boot"); + } + + List classpathEntries = new ArrayList<>(); + + File[] files = mavenHomeBootAsFile.listFiles(); + if (files != null) { + for (File file : files) { + if (file.getName().contains("classworlds")) { + classpathEntries.add(file.getAbsolutePath()); + } + } + } + + return classpathEntries; + } + + private static void encodeCoreAndRunnerSettings(MavenGeneralSettings coreSettings, String mavenHome, ParametersList cmdList) { + if (coreSettings.isWorkOffline()) { + cmdList.add("--offline"); + } + + boolean atLeastMaven3 = MavenUtil.isMaven3(mavenHome); + + if (!atLeastMaven3) { + addIfNotEmpty(cmdList, coreSettings.getPluginUpdatePolicy().getCommandLineOption()); + + if (!coreSettings.isUsePluginRegistry()) { + cmdList.add("--no-plugin-registry"); + } + } + + if (coreSettings.getOutputLevel() == MavenExecutionOptions.LoggingLevel.DEBUG) { + cmdList.add("--debug"); + } + if (coreSettings.isNonRecursive()) { + cmdList.add("--non-recursive"); + } + if (coreSettings.isPrintErrorStackTraces()) { + cmdList.add("--errors"); + } + + if (coreSettings.isAlwaysUpdateSnapshots()) { + cmdList.add("--update-snapshots"); + } + + if (StringUtil.isNotEmpty(coreSettings.getThreads())) { + cmdList.add("-T", coreSettings.getThreads()); + } + + addIfNotEmpty(cmdList, coreSettings.getFailureBehavior().getCommandLineOption()); + addIfNotEmpty(cmdList, coreSettings.getChecksumPolicy().getCommandLineOption()); + + addOption(cmdList, "s", coreSettings.getUserSettingsFile()); + if (!StringUtil.isEmptyOrSpaces(coreSettings.getLocalRepository())) { + cmdList.addProperty("maven.repo.local", coreSettings.getLocalRepository()); + } + } + + private static void addIfNotEmpty(ParametersList parametersList, @Nullable String value) { + if (!StringUtil.isEmptyOrSpaces(value)) { + parametersList.add(value); + } + } + + private static String encodeProfiles(Map profiles) { + StringBuilder stringBuilder = new StringBuilder(); + for (Map.Entry entry : profiles.entrySet()) { + if (stringBuilder.length() != 0) { + stringBuilder.append(","); + } + if (!entry.getValue()) { + stringBuilder.append("!"); + } + stringBuilder.append(entry.getKey()); + } + return stringBuilder.toString(); + } + + private static class ProjectSettingsOpenerExecutionException extends WithHyperlinkExecutionException { + private final Project myProject; + + public ProjectSettingsOpenerExecutionException(final String s, Project project) { + super(s); + myProject = project; + } + + @Override + protected void hyperlinkClicked() { + ShowSettingsUtil.getInstance().showSettingsDialog(myProject, MavenSettings.DISPLAY_NAME); + } + } + + private static class ProjectJdkSettingsOpenerExecutionException extends WithHyperlinkExecutionException { + + private final Project myProject; + + public ProjectJdkSettingsOpenerExecutionException(final String s, Project project) { + super(s); + myProject = project; + } + + @Override + protected void hyperlinkClicked() { + ShowSettingsUtil.getInstance().showProjectStructureDialog(myProject); + } + } + + private static class RunConfigurationOpenerExecutionException extends WithHyperlinkExecutionException { + + private final MavenRunConfiguration myRunConfiguration; + + public RunConfigurationOpenerExecutionException(final String s, MavenRunConfiguration runConfiguration) { + super(s); + myRunConfiguration = runConfiguration; + } + + @Override + protected void hyperlinkClicked() { + Project project = myRunConfiguration.getProject(); + EditConfigurationsDialog dialog = new EditConfigurationsDialog(project); + dialog.show(); + } + } + + private static abstract class WithHyperlinkExecutionException extends ExecutionException implements HyperlinkListener, NotificationListener { + public WithHyperlinkExecutionException(String s) { + super(s); + } + + protected abstract void hyperlinkClicked(); + + @Override + public final void hyperlinkUpdate(HyperlinkEvent e) { + if (e.getEventType() == HyperlinkEvent.EventType.ACTIVATED) { + hyperlinkClicked(); + } + } + + @Override + public final void hyperlinkUpdate(@Nonnull Notification notification, @Nonnull HyperlinkEvent event) { + hyperlinkUpdate(event); + } + } } diff --git a/plugin/src/main/java/org/jetbrains/idea/maven/execution/MavenGoalLocation.java b/plugin/src/main/java/org/jetbrains/idea/maven/execution/MavenGoalLocation.java index bf403724..c783eaf4 100644 --- a/plugin/src/main/java/org/jetbrains/idea/maven/execution/MavenGoalLocation.java +++ b/plugin/src/main/java/org/jetbrains/idea/maven/execution/MavenGoalLocation.java @@ -21,16 +21,15 @@ import java.util.List; -public class MavenGoalLocation extends PsiLocation -{ - private final List myGoals; +public class MavenGoalLocation extends PsiLocation { + private final List myGoals; - public MavenGoalLocation(Project p, PsiFile file, List goals) { - super(p, file); - myGoals = goals; - } + public MavenGoalLocation(Project p, PsiFile file, List goals) { + super(p, file); + myGoals = goals; + } - public List getGoals() { - return myGoals; - } + public List getGoals() { + return myGoals; + } } diff --git a/plugin/src/main/java/org/jetbrains/idea/maven/execution/MavenJUnitPatcher.java b/plugin/src/main/java/org/jetbrains/idea/maven/execution/MavenJUnitPatcher.java index 248fe036..3a94a48f 100644 --- a/plugin/src/main/java/org/jetbrains/idea/maven/execution/MavenJUnitPatcher.java +++ b/plugin/src/main/java/org/jetbrains/idea/maven/execution/MavenJUnitPatcher.java @@ -34,71 +34,57 @@ * @author Sergey Evdokimov */ @ExtensionImpl -public class MavenJUnitPatcher implements JavaTestPatcher -{ - @Override - public void patchJavaParameters(@Nullable Module module, OwnJavaParameters javaParameters) - { - if(module == null) - { - return; - } +public class MavenJUnitPatcher implements JavaTestPatcher { + @Override + public void patchJavaParameters(@Nullable Module module, OwnJavaParameters javaParameters) { + if (module == null) { + return; + } - MavenProject mavenProject = MavenProjectsManager.getInstance(module.getProject()).findProject(module); - if(mavenProject == null) - { - return; - } + MavenProject mavenProject = MavenProjectsManager.getInstance(module.getProject()).findProject(module); + if (mavenProject == null) { + return; + } - Element config = mavenProject.getPluginConfiguration("org.apache.maven.plugins", "maven-surefire-plugin"); - if(config == null) - { - return; - } + Element config = mavenProject.getPluginConfiguration("org.apache.maven.plugins", "maven-surefire-plugin"); + if (config == null) { + return; + } - List paths = MavenJDOMUtil.findChildrenValuesByPath(config, "additionalClasspathElements", "additionalClasspathElement"); + List paths = MavenJDOMUtil.findChildrenValuesByPath(config, "additionalClasspathElements", "additionalClasspathElement"); - if(paths.size() > 0) - { - MavenDomProjectModel domModel = MavenDomUtil.getMavenDomProjectModel(module.getProject(), mavenProject.getFile()); + if (paths.size() > 0) { + MavenDomProjectModel domModel = MavenDomUtil.getMavenDomProjectModel(module.getProject(), mavenProject.getFile()); - for(String path : paths) - { - if(domModel != null) - { - path = MavenPropertyResolver.resolve(path, domModel); - } + for (String path : paths) { + if (domModel != null) { + path = MavenPropertyResolver.resolve(path, domModel); + } - javaParameters.getClassPath().add(path); - } - } + javaParameters.getClassPath().add(path); + } + } - Element systemPropertyVariables = config.getChild("systemPropertyVariables"); - if(systemPropertyVariables != null) - { - for(Element element : systemPropertyVariables.getChildren()) - { - String propertyName = element.getName(); + Element systemPropertyVariables = config.getChild("systemPropertyVariables"); + if (systemPropertyVariables != null) { + for (Element element : systemPropertyVariables.getChildren()) { + String propertyName = element.getName(); - if(!javaParameters.getVMParametersList().hasProperty(propertyName)) - { - javaParameters.getVMParametersList().addProperty(propertyName, element.getValue()); - } - } - } + if (!javaParameters.getVMParametersList().hasProperty(propertyName)) { + javaParameters.getVMParametersList().addProperty(propertyName, element.getValue()); + } + } + } - Element environmentVariables = config.getChild("environmentVariables"); - if(environmentVariables != null) - { - for(Element element : environmentVariables.getChildren()) - { - String variableName = element.getName(); + Element environmentVariables = config.getChild("environmentVariables"); + if (environmentVariables != null) { + for (Element element : environmentVariables.getChildren()) { + String variableName = element.getName(); - if(javaParameters.getEnv() == null || !javaParameters.getEnv().containsKey(variableName)) - { - javaParameters.addEnv(variableName, element.getValue()); - } - } - } - } + if (javaParameters.getEnv() == null || !javaParameters.getEnv().containsKey(variableName)) { + javaParameters.addEnv(variableName, element.getValue()); + } + } + } + } } diff --git a/plugin/src/main/java/org/jetbrains/idea/maven/execution/MavenOrderEnumeratorHandler.java b/plugin/src/main/java/org/jetbrains/idea/maven/execution/MavenOrderEnumeratorHandler.java index 2166b57d..8dc60a0d 100644 --- a/plugin/src/main/java/org/jetbrains/idea/maven/execution/MavenOrderEnumeratorHandler.java +++ b/plugin/src/main/java/org/jetbrains/idea/maven/execution/MavenOrderEnumeratorHandler.java @@ -25,36 +25,30 @@ import javax.annotation.Nonnull; @ExtensionImpl -public class MavenOrderEnumeratorHandler implements OrderEnumerationPolicy -{ - @Override - public boolean isApplicable(@Nonnull Project project) - { - return MavenProjectsManager.getInstance(project).isMavenizedProject(); - } - - @Override - public boolean isApplicable(@Nonnull Module module) - { - final MavenProjectsManager manager = MavenProjectsManager.getInstance(module.getProject()); - return manager.isMavenizedModule(module); - } - - @Override - public boolean shouldAddRuntimeDependenciesToTestCompilationClasspath() - { - return true; - } - - @Override - public boolean shouldIncludeTestsFromDependentModulesToTestClasspath() - { - return false; - } - - @Override - public boolean shouldProcessDependenciesRecursively() - { - return false; - } +public class MavenOrderEnumeratorHandler implements OrderEnumerationPolicy { + @Override + public boolean isApplicable(@Nonnull Project project) { + return MavenProjectsManager.getInstance(project).isMavenizedProject(); + } + + @Override + public boolean isApplicable(@Nonnull Module module) { + final MavenProjectsManager manager = MavenProjectsManager.getInstance(module.getProject()); + return manager.isMavenizedModule(module); + } + + @Override + public boolean shouldAddRuntimeDependenciesToTestCompilationClasspath() { + return true; + } + + @Override + public boolean shouldIncludeTestsFromDependentModulesToTestClasspath() { + return false; + } + + @Override + public boolean shouldProcessDependenciesRecursively() { + return false; + } } diff --git a/plugin/src/main/java/org/jetbrains/idea/maven/execution/MavenPropertiesPanel.java b/plugin/src/main/java/org/jetbrains/idea/maven/execution/MavenPropertiesPanel.java index 47040b88..185f279b 100644 --- a/plugin/src/main/java/org/jetbrains/idea/maven/execution/MavenPropertiesPanel.java +++ b/plugin/src/main/java/org/jetbrains/idea/maven/execution/MavenPropertiesPanel.java @@ -26,66 +26,66 @@ import java.util.List; /** -* @author Sergey Evdokimov -*/ -public class MavenPropertiesPanel extends AddEditRemovePanel> -{ - private Map myAvailableProperties; - - public MavenPropertiesPanel(Map availableProperties) { - super(new MyPropertiesTableModel(), new ArrayList>(), null); - setPreferredSize(new Dimension(100, 100)); - myAvailableProperties = availableProperties; - } - - protected Pair addItem() { - return doAddOrEdit(null); - } - - protected boolean removeItem(Pair o) { - return true; - } + * @author Sergey Evdokimov + */ +public class MavenPropertiesPanel extends AddEditRemovePanel> { + private Map myAvailableProperties; - protected Pair editItem(@Nonnull Pair o) { - return doAddOrEdit(o); - } + public MavenPropertiesPanel(Map availableProperties) { + super(new MyPropertiesTableModel(), new ArrayList<>(), null); + setPreferredSize(new Dimension(100, 100)); + myAvailableProperties = availableProperties; + } - @Nullable - private Pair doAddOrEdit(@Nullable Pair o) { - EditMavenPropertyDialog d = new EditMavenPropertyDialog(o, myAvailableProperties); - d.show(); - if (!d.isOK()) return null; - return d.getValue(); - } + protected Pair addItem() { + return doAddOrEdit(null); + } - public Map getDataAsMap() { - Map result = new LinkedHashMap(); - for (Pair p : getData()) { - result.put(p.getFirst(), p.getSecond()); + protected boolean removeItem(Pair o) { + return true; } - return result; - } - public void setDataFromMap(Map map) { - List> result = new ArrayList>(); - for (Map.Entry e : map.entrySet()) { - result.add(new Pair(e.getKey(), e.getValue())); + protected Pair editItem(@Nonnull Pair o) { + return doAddOrEdit(o); } - setData(result); - } - private static class MyPropertiesTableModel extends AddEditRemovePanel.TableModel> { - public int getColumnCount() { - return 2; + @Nullable + private Pair doAddOrEdit(@Nullable Pair o) { + EditMavenPropertyDialog d = new EditMavenPropertyDialog(o, myAvailableProperties); + d.show(); + if (!d.isOK()) { + return null; + } + return d.getValue(); } - public String getColumnName(int c) { - return c == 0 ? "Name" : "Value"; + public Map getDataAsMap() { + Map result = new LinkedHashMap<>(); + for (Pair p : getData()) { + result.put(p.getFirst(), p.getSecond()); + } + return result; } - public Object getField(Pair o, int c) { - return c == 0 ? o.getFirst() : o.getSecond(); + public void setDataFromMap(Map map) { + List> result = new ArrayList<>(); + for (Map.Entry e : map.entrySet()) { + result.add(new Pair(e.getKey(), e.getValue())); + } + setData(result); } - } + private static class MyPropertiesTableModel extends AddEditRemovePanel.TableModel> { + public int getColumnCount() { + return 2; + } + + public String getColumnName(int c) { + return c == 0 ? "Name" : "Value"; + } + + public Object getField(Pair o, int c) { + return c == 0 ? o.getFirst() : o.getSecond(); + } + } } diff --git a/plugin/src/main/java/org/jetbrains/idea/maven/execution/MavenResumeAction.java b/plugin/src/main/java/org/jetbrains/idea/maven/execution/MavenResumeAction.java index 67b95c12..5bc279be 100644 --- a/plugin/src/main/java/org/jetbrains/idea/maven/execution/MavenResumeAction.java +++ b/plugin/src/main/java/org/jetbrains/idea/maven/execution/MavenResumeAction.java @@ -48,259 +48,284 @@ */ public class MavenResumeAction extends AnAction { - private static final Logger LOG = Logger.getInstance(MavenResumeAction.class); - - private static final Set PARAMS_DISABLING_RESUME = Set.of("-rf", "-resume-from", "-pl", "-projects", "-am", "-also-make", "-amd", "-also-make-dependents"); - - public static final int STATE_INITIAL = 0; - public static final int STATE_READING_PROJECT_LIST = 1; - public static final int STATE_READING_PROJECT_LIST_OLD_MAVEN = 5; - public static final int STATE_WAIT_FOR_BUILD = 2; - public static final int STATE_WAIT_FOR______ = 3; - public static final int STATE_WTF = -1; - - private final ProgramRunner myRunner; - private final ExecutionEnvironment myEnvironment; - - private int myState = STATE_INITIAL; - - private int myBuildingProjectIndex = 0; - - private final List myMavenProjectNames = new ArrayList(); - - private String myResumeFromModuleName; - - private String myResumeModuleId; + private static final Logger LOG = Logger.getInstance(MavenResumeAction.class); + + private static final Set PARAMS_DISABLING_RESUME = Set.of( + "-rf", + "-resume-from", + "-pl", + "-projects", + "-am", + "-also-make", + "-amd", + "-also-make-dependents" + ); + + public static final int STATE_INITIAL = 0; + public static final int STATE_READING_PROJECT_LIST = 1; + public static final int STATE_READING_PROJECT_LIST_OLD_MAVEN = 5; + public static final int STATE_WAIT_FOR_BUILD = 2; + public static final int STATE_WAIT_FOR______ = 3; + public static final int STATE_WTF = -1; + + private final ProgramRunner myRunner; + private final ExecutionEnvironment myEnvironment; + + private int myState = STATE_INITIAL; + + private int myBuildingProjectIndex = 0; + + private final List myMavenProjectNames = new ArrayList(); + + private String myResumeFromModuleName; + + private String myResumeModuleId; + + public MavenResumeAction( + ProcessHandler processHandler, + ProgramRunner runner, + ExecutionEnvironment environment + ) { + super("Resume build from specified module", null, AllIcons.RunConfigurations.RerunFailedTests); + myRunner = runner; + myEnvironment = environment; + + final MavenRunConfiguration runConfiguration = (MavenRunConfiguration)environment.getRunProfile(); + + getTemplatePresentation().setEnabled(false); + + processHandler.addProcessListener(new ProcessAdapter() { + @Override + public void processTerminated(ProcessEvent event) { + if (myState == STATE_WTF) { + return; + } + + if (event.getExitCode() == 0 && myBuildingProjectIndex != myMavenProjectNames.size()) { + log(String.format( + "Build was success, but not all project was build. Project build order: %s, build index: %d", + myMavenProjectNames, + myBuildingProjectIndex + )); + } + + if (event.getExitCode() == 1 && myBuildingProjectIndex > 0) { + if (myBuildingProjectIndex == 1 && !hasResumeFromParameter(runConfiguration)) { + return; + } + + myResumeFromModuleName = myMavenProjectNames.get(myBuildingProjectIndex - 1); + + MavenProject mavenProject = findProjectByName(myResumeFromModuleName); + if (mavenProject != null) { + myResumeModuleId = mavenProject.getMavenId().getGroupId() + ':' + mavenProject.getMavenId().getArtifactId(); + } + } + } - public MavenResumeAction(ProcessHandler processHandler, - ProgramRunner runner, - ExecutionEnvironment environment) { - super("Resume build from specified module", null, AllIcons.RunConfigurations.RerunFailedTests); - myRunner = runner; - myEnvironment = environment; + @Override + public void onTextAvailable(ProcessEvent event, Key outputType) { + if (outputType != ProcessOutputTypes.STDOUT) { + return; + } + + String text = event.getText().trim(); + if (text.isEmpty()) { + return; + } + + String textWithoutInfo = ""; + if (text.startsWith("[INFO] ")) { + textWithoutInfo = text.substring("[INFO] ".length()).trim(); + } + + switch (myState) { + case STATE_INITIAL: // initial state. + if (textWithoutInfo.equals("Reactor build order:")) { + myState = STATE_READING_PROJECT_LIST_OLD_MAVEN; + } + else if (textWithoutInfo.equals("Reactor Build Order:")) { + myState = STATE_READING_PROJECT_LIST; + } + break; + + case STATE_READING_PROJECT_LIST: + if (textWithoutInfo.equals("------------------------------------------------------------------------")) { + myState = STATE_WAIT_FOR_BUILD; + } + else if (textWithoutInfo.length() > 0) { + myMavenProjectNames.add(textWithoutInfo); + } + break; + + case STATE_READING_PROJECT_LIST_OLD_MAVEN: + if (textWithoutInfo.length() > 0) { + if (text.startsWith("[INFO] ")) { + myMavenProjectNames.add(textWithoutInfo); + } + else { + myState = STATE_WAIT_FOR_BUILD; + } + } + break; + + case STATE_WAIT_FOR_BUILD: + if (textWithoutInfo.startsWith("Building ")) { + String projectName = textWithoutInfo.substring("Building ".length()); + if (myBuildingProjectIndex >= myMavenProjectNames.size() || + !projectName.startsWith(myMavenProjectNames.get(myBuildingProjectIndex))) { + myState = STATE_WTF; + log(String.format("Invalid project building order. Defined order: %s, error index: %d, invalid line: %s", + myMavenProjectNames, myBuildingProjectIndex, text + )); + break; + } + + myBuildingProjectIndex++; + } + myState = STATE_WAIT_FOR______; + break; + + case STATE_WAIT_FOR______: + if (textWithoutInfo.equals("------------------------------------------------------------------------")) { + myState = STATE_WAIT_FOR_BUILD; + } + break; + + case STATE_WTF: + break; + + default: + throw new IllegalStateException(); + } + } + }); + } - final MavenRunConfiguration runConfiguration = (MavenRunConfiguration)environment.getRunProfile(); + private static boolean hasResumeFromParameter(MavenRunConfiguration runConfiguration) { + List goals = runConfiguration.getRunnerParameters().getGoals(); + return goals.size() > 2 && "-rf".equals(goals.get(goals.size() - 2)); + } - getTemplatePresentation().setEnabled(false); + @Nullable + private MavenProject findProjectByName(@Nonnull String projectName) { + List projects = MavenProjectsManager.getInstance(myEnvironment.getProject()).getProjects(); - processHandler.addProcessListener(new ProcessAdapter() { - @Override - public void processTerminated(ProcessEvent event) { - if (myState == STATE_WTF) return; + MavenProject candidate = null; - if (event.getExitCode() == 0 && myBuildingProjectIndex != myMavenProjectNames.size()) { - log(String.format("Build was success, but not all project was build. Project build order: %s, build index: %d", - myMavenProjectNames, - myBuildingProjectIndex )); + for (MavenProject mavenProject : projects) { + if (projectName.equals(mavenProject.getName())) { + if (candidate == null) { + candidate = mavenProject; + } + else { + return null; + } + } } - if (event.getExitCode() == 1 && myBuildingProjectIndex > 0) { - if (myBuildingProjectIndex == 1 && !hasResumeFromParameter(runConfiguration)) { - return; - } - - myResumeFromModuleName = myMavenProjectNames.get(myBuildingProjectIndex - 1); - - MavenProject mavenProject = findProjectByName(myResumeFromModuleName); - if (mavenProject != null) { - myResumeModuleId = mavenProject.getMavenId().getGroupId() + ':' + mavenProject.getMavenId().getArtifactId(); - } + if (candidate != null) { + return candidate; } - } - @Override - public void onTextAvailable(ProcessEvent event, Key outputType) { - if (outputType != ProcessOutputTypes.STDOUT) return; - - String text = event.getText().trim(); - if (text.isEmpty()) return; + for (MavenProject mavenProject : projects) { + String id = mavenProject.getMavenId().getGroupId() + ':' + mavenProject.getMavenId() + .getArtifactId() + ':' + mavenProject.getPackaging(); + if (projectName.contains(id)) { + if (candidate == null) { + candidate = mavenProject; + } + else { + return null; + } + } + } - String textWithoutInfo = ""; - if (text.startsWith("[INFO] ")) { - textWithoutInfo = text.substring("[INFO] ".length()).trim(); + if (candidate != null) { + return candidate; } - switch (myState) { - case STATE_INITIAL: // initial state. - if (textWithoutInfo.equals("Reactor build order:")) { - myState = STATE_READING_PROJECT_LIST_OLD_MAVEN; - } - else if (textWithoutInfo.equals("Reactor Build Order:")) { - myState = STATE_READING_PROJECT_LIST; + for (MavenProject mavenProject : projects) { + if (projectName.equals(mavenProject.getMavenId().getArtifactId())) { + if (candidate == null) { + candidate = mavenProject; + } + else { + return null; + } } - break; + } - case STATE_READING_PROJECT_LIST: - if (textWithoutInfo.equals("------------------------------------------------------------------------")) { - myState = STATE_WAIT_FOR_BUILD; - } - else if (textWithoutInfo.length() > 0) { - myMavenProjectNames.add(textWithoutInfo); - } - break; - - case STATE_READING_PROJECT_LIST_OLD_MAVEN: - if (textWithoutInfo.length() > 0) { - if (text.startsWith("[INFO] ")) { - myMavenProjectNames.add(textWithoutInfo); - } - else { - myState = STATE_WAIT_FOR_BUILD; - } - } - break; - - case STATE_WAIT_FOR_BUILD: - if (textWithoutInfo.startsWith("Building ")) { - String projectName = textWithoutInfo.substring("Building ".length()); - if (myBuildingProjectIndex >= myMavenProjectNames.size() || - !projectName.startsWith(myMavenProjectNames.get(myBuildingProjectIndex))) { - myState = STATE_WTF; - log(String.format("Invalid project building order. Defined order: %s, error index: %d, invalid line: %s", - myMavenProjectNames, myBuildingProjectIndex, text)); - break; - } - - myBuildingProjectIndex++; - } - myState = STATE_WAIT_FOR______; - break; + return candidate; + } - case STATE_WAIT_FOR______: - if (textWithoutInfo.equals("------------------------------------------------------------------------")) { - myState = STATE_WAIT_FOR_BUILD; + public static boolean isApplicable( + @Nullable Project project, + OwnJavaParameters javaParameters, + MavenRunConfiguration runConfiguration + ) { + if (hasResumeFromParameter(runConfiguration)) { // This runConfiguration was created by other MavenResumeAction. + MavenRunConfiguration clonedRunConf = runConfiguration.clone(); + List clonedGoals = clonedRunConf.getRunnerParameters().getGoals(); + clonedGoals.remove(clonedGoals.size() - 1); + clonedGoals.remove(clonedGoals.size() - 1); + try { + javaParameters = clonedRunConf.createJavaParameters(project); + } + catch (ExecutionException e) { + return false; } - break; - - case STATE_WTF: - break; - - default: - throw new IllegalStateException(); } - } - }); - } - - private static boolean hasResumeFromParameter(MavenRunConfiguration runConfiguration) { - List goals = runConfiguration.getRunnerParameters().getGoals(); - return goals.size() > 2 && "-rf".equals(goals.get(goals.size() - 2)); - } - @Nullable - private MavenProject findProjectByName(@Nonnull String projectName) { - List projects = MavenProjectsManager.getInstance(myEnvironment.getProject()).getProjects(); - - MavenProject candidate = null; - - for (MavenProject mavenProject : projects) { - if (projectName.equals(mavenProject.getName())) { - if (candidate == null) { - candidate = mavenProject; - } - else { - return null; + for (String params : javaParameters.getProgramParametersList().getList()) { + if (PARAMS_DISABLING_RESUME.contains(params)) { + return false; + } } - } - } - if (candidate != null) { - return candidate; + return true; } - for (MavenProject mavenProject : projects) { - String id = mavenProject.getMavenId().getGroupId() + ':' + mavenProject.getMavenId().getArtifactId() + ':' + mavenProject.getPackaging(); - if (projectName.contains(id)) { - if (candidate == null) { - candidate = mavenProject; + private static void log(String message) { + if (ApplicationManager.getApplication().isInternal()) { + LOG.error(message, new Exception()); } else { - return null; + LOG.warn(message, new Exception()); } - } - } - - if (candidate != null) { - return candidate; } - for (MavenProject mavenProject : projects) { - if (projectName.equals(mavenProject.getMavenId().getArtifactId())) { - if (candidate == null) { - candidate = mavenProject; - } - else { - return null; + @Override + public void update(AnActionEvent e) { + if (myResumeFromModuleName != null && myResumeModuleId != null) { + e.getPresentation().setEnabled(true); + e.getPresentation().setText("Resume build from \"" + myResumeFromModuleName + "\""); } - } - } - - return candidate; - } - - public static boolean isApplicable(@Nullable Project project, OwnJavaParameters javaParameters, MavenRunConfiguration runConfiguration) { - if (hasResumeFromParameter(runConfiguration)) { // This runConfiguration was created by other MavenResumeAction. - MavenRunConfiguration clonedRunConf = runConfiguration.clone(); - List clonedGoals = clonedRunConf.getRunnerParameters().getGoals(); - clonedGoals.remove(clonedGoals.size() - 1); - clonedGoals.remove(clonedGoals.size() - 1); - try { - javaParameters = clonedRunConf.createJavaParameters(project); - } - catch (ExecutionException e) { - return false; - } - } - - for (String params : javaParameters.getProgramParametersList().getList()) { - if (PARAMS_DISABLING_RESUME.contains(params)) { - return false; - } } - return true; - } + @Override + public void actionPerformed(AnActionEvent e) { + Project project = myEnvironment.getProject(); + try { + MavenRunConfiguration runConfiguration = ((MavenRunConfiguration)myEnvironment.getRunProfile()).clone(); - private static void log(String message) { - if (ApplicationManager.getApplication().isInternal()) { - LOG.error(message, new Exception()); - } - else { - LOG.warn(message, new Exception()); - } - - } - - @Override - public void update(AnActionEvent e) { - if (myResumeFromModuleName != null && myResumeModuleId != null) { - e.getPresentation().setEnabled(true); - e.getPresentation().setText("Resume build from \"" + myResumeFromModuleName + "\""); - } - } - - @Override - public void actionPerformed(AnActionEvent e) { - Project project = myEnvironment.getProject(); - try { - MavenRunConfiguration runConfiguration = ((MavenRunConfiguration)myEnvironment.getRunProfile()).clone(); - - List goals = runConfiguration.getRunnerParameters().getGoals(); + List goals = runConfiguration.getRunnerParameters().getGoals(); - if (goals.size() > 2 && "-rf".equals(goals.get(goals.size() - 2))) { // This runConfiguration was created by other MavenResumeAction. - goals.set(goals.size() - 1, myResumeModuleId); - } - else { - goals.add("-rf"); - goals.add(myResumeModuleId); - } + if (goals.size() > 2 && "-rf".equals(goals.get(goals.size() - 2))) { + // This runConfiguration was created by other MavenResumeAction. + goals.set(goals.size() - 1, myResumeModuleId); + } + else { + goals.add("-rf"); + goals.add(myResumeModuleId); + } - myRunner.execute(new ExecutionEnvironmentBuilder(myEnvironment).contentToReuse(null).build()); - } - catch (RunCanceledByUserException ignore) { - } - catch (ExecutionException e1) { - Messages.showErrorDialog(project, e1.getMessage(), ExecutionBundle.message("restart.error.message.title")); + myRunner.execute(new ExecutionEnvironmentBuilder(myEnvironment).contentToReuse(null).build()); + } + catch (RunCanceledByUserException ignore) { + } + catch (ExecutionException e1) { + Messages.showErrorDialog(project, e1.getMessage(), ExecutionBundle.message("restart.error.message.title")); + } } - } } diff --git a/plugin/src/main/java/org/jetbrains/idea/maven/execution/MavenRunConfiguration.java b/plugin/src/main/java/org/jetbrains/idea/maven/execution/MavenRunConfiguration.java index ac8795c9..82a1f602 100644 --- a/plugin/src/main/java/org/jetbrains/idea/maven/execution/MavenRunConfiguration.java +++ b/plugin/src/main/java/org/jetbrains/idea/maven/execution/MavenRunConfiguration.java @@ -48,204 +48,177 @@ import javax.annotation.Nonnull; import javax.annotation.Nullable; -public class MavenRunConfiguration extends LocatableConfigurationBase implements GenericDebugRunnerConfiguration -{ - private MavenSettings mySettings; - - protected MavenRunConfiguration(Project project, ConfigurationFactory factory, String name) - { - super(project, factory, name); - mySettings = new MavenSettings(project); - } - - @Override - public MavenRunConfiguration clone() - { - MavenRunConfiguration clone = (MavenRunConfiguration) super.clone(); - clone.mySettings = mySettings.clone(); - return clone; - } - - @Nonnull - @Override - public SettingsEditor getConfigurationEditor() - { - SettingsEditorGroup group = new SettingsEditorGroup(); - - group.addEditor(RunnerBundle.message("maven.runner.parameters.title"), new MavenRunnerParametersSettingEditor(getProject())); - group.addEditor(ProjectBundle.message("maven.tab.general"), new MavenGeneralSettingsEditor(getProject())); - group.addEditor(RunnerBundle.message("maven.tab.runner"), new MavenRunnerSettingsEditor(getProject())); - group.addEditor(ExecutionBundle.message("logs.tab.title"), new LogConfigurationPanel()); - return group; - } - - public OwnJavaParameters createJavaParameters(@Nullable Project project) throws ExecutionException - { - return MavenExternalParameters.createJavaParameters(project, mySettings.myRunnerParameters, mySettings.myGeneralSettings, - mySettings.myRunnerSettings, this); - } - - @Override - public RunProfileState getState(@Nonnull final Executor executor, @Nonnull final ExecutionEnvironment env) throws ExecutionException - { - JavaCommandLineState state = new JavaCommandLineState(env) - { - @Override - protected OwnJavaParameters createJavaParameters() throws ExecutionException - { - return MavenRunConfiguration.this.createJavaParameters(env.getProject()); - } - - @Nonnull - @Override - public ExecutionResult execute(@Nonnull Executor executor, @Nonnull ProgramRunner runner) throws ExecutionException - { - DefaultExecutionResult res = (DefaultExecutionResult) super.execute(executor, runner); - if(executor.getId().equals(ToolWindowId.RUN) && MavenResumeAction.isApplicable(env.getProject(), getJavaParameters(), - MavenRunConfiguration.this)) - { - MavenResumeAction resumeAction = new MavenResumeAction(res.getProcessHandler(), runner, env); - res.setRestartActions(resumeAction); - } - return res; - } - - @Override - protected void buildProcessHandler(@Nonnull ProcessHandlerBuilder builder) throws ExecutionException - { - super.buildProcessHandler(builder); - - builder.shouldDestroyProcessRecursively(true); - } - - @Override - protected void setupProcessHandler(@Nonnull ProcessHandler handler) - { - super.setupProcessHandler(handler); - handler.addProcessListener(new ProcessListener() - { - @Override - public void processTerminated(ProcessEvent event) - { - updateProjectsFolders(); - } - }); - } - }; - state.setConsoleBuilder(MavenConsoleImpl.createConsoleBuilder(getProject())); - return state; - } - - private void updateProjectsFolders() - { - MavenProjectsManager.getInstance(getProject()).updateProjectTargetFolders(); - } - - @Override - @Nonnull - public consulo.module.Module[] getModules() - { - return Module.EMPTY_ARRAY; - } - - @Nullable - public MavenGeneralSettings getGeneralSettings() - { - return mySettings.myGeneralSettings; - } - - public void setGeneralSettings(@Nullable MavenGeneralSettings settings) - { - mySettings.myGeneralSettings = settings; - } - - @Nullable - public MavenRunnerSettings getRunnerSettings() - { - return mySettings.myRunnerSettings; - } - - public void setRunnerSettings(@Nullable MavenRunnerSettings settings) - { - mySettings.myRunnerSettings = settings; - } - - public MavenRunnerParameters getRunnerParameters() - { - return mySettings.myRunnerParameters; - } - - public void setRunnerParameters(MavenRunnerParameters p) - { - mySettings.myRunnerParameters = p; - } - - @Override - public void readExternal(Element element) throws InvalidDataException - { - super.readExternal(element); - - Element mavenSettingsElement = element.getChild(MavenSettings.TAG); - if(mavenSettingsElement != null) - { - mySettings = XmlSerializer.deserialize(mavenSettingsElement, MavenSettings.class); - if(mySettings == null) - { - mySettings = new MavenSettings(); - } - - if(mySettings.myRunnerParameters == null) - { - mySettings.myRunnerParameters = new MavenRunnerParameters(); - } - - // fix old settings format - mySettings.myRunnerParameters.fixAfterLoadingFromOldFormat(); - } - } - - @Override - public void writeExternal(Element element) throws WriteExternalException - { - super.writeExternal(element); - element.addContent(XmlSerializer.serialize(mySettings)); - } - - @Override - public String suggestedName() - { - return MavenRunConfigurationType.generateName(getProject(), mySettings.myRunnerParameters); - } - - public static class MavenSettings implements Cloneable - { - public static final String TAG = "MavenSettings"; - - public MavenGeneralSettings myGeneralSettings; - public MavenRunnerSettings myRunnerSettings; - public MavenRunnerParameters myRunnerParameters; - - /* reflection only */ - public MavenSettings() - { - } - - public MavenSettings(Project project) - { - this(null, null, new MavenRunnerParameters()); - } - - private MavenSettings(@Nullable MavenGeneralSettings cs, @Nullable MavenRunnerSettings rs, MavenRunnerParameters rp) - { - myGeneralSettings = cs == null ? null : cs.clone(); - myRunnerSettings = rs == null ? null : rs.clone(); - myRunnerParameters = rp.clone(); - } - - @Override - protected MavenSettings clone() - { - return new MavenSettings(myGeneralSettings, myRunnerSettings, myRunnerParameters); - } - } +public class MavenRunConfiguration extends LocatableConfigurationBase implements GenericDebugRunnerConfiguration { + private MavenSettings mySettings; + + protected MavenRunConfiguration(Project project, ConfigurationFactory factory, String name) { + super(project, factory, name); + mySettings = new MavenSettings(project); + } + + @Override + public MavenRunConfiguration clone() { + MavenRunConfiguration clone = (MavenRunConfiguration)super.clone(); + clone.mySettings = mySettings.clone(); + return clone; + } + + @Nonnull + @Override + public SettingsEditor getConfigurationEditor() { + SettingsEditorGroup group = new SettingsEditorGroup(); + + group.addEditor(RunnerBundle.message("maven.runner.parameters.title"), new MavenRunnerParametersSettingEditor(getProject())); + group.addEditor(ProjectBundle.message("maven.tab.general"), new MavenGeneralSettingsEditor(getProject())); + group.addEditor(RunnerBundle.message("maven.tab.runner"), new MavenRunnerSettingsEditor(getProject())); + group.addEditor(ExecutionBundle.message("logs.tab.title"), new LogConfigurationPanel<>()); + return group; + } + + public OwnJavaParameters createJavaParameters(@Nullable Project project) throws ExecutionException { + return MavenExternalParameters.createJavaParameters( + project, + mySettings.myRunnerParameters, + mySettings.myGeneralSettings, + mySettings.myRunnerSettings, + this + ); + } + + @Override + public RunProfileState getState(@Nonnull final Executor executor, @Nonnull final ExecutionEnvironment env) throws ExecutionException { + JavaCommandLineState state = new JavaCommandLineState(env) { + @Override + protected OwnJavaParameters createJavaParameters() throws ExecutionException { + return MavenRunConfiguration.this.createJavaParameters(env.getProject()); + } + + @Nonnull + @Override + public ExecutionResult execute(@Nonnull Executor executor, @Nonnull ProgramRunner runner) throws ExecutionException { + DefaultExecutionResult res = (DefaultExecutionResult)super.execute(executor, runner); + if (executor.getId().equals(ToolWindowId.RUN) && MavenResumeAction.isApplicable(env.getProject(), getJavaParameters(), + MavenRunConfiguration.this + )) { + MavenResumeAction resumeAction = new MavenResumeAction(res.getProcessHandler(), runner, env); + res.setRestartActions(resumeAction); + } + return res; + } + + @Override + protected void buildProcessHandler(@Nonnull ProcessHandlerBuilder builder) throws ExecutionException { + super.buildProcessHandler(builder); + + builder.shouldDestroyProcessRecursively(true); + } + + @Override + protected void setupProcessHandler(@Nonnull ProcessHandler handler) { + super.setupProcessHandler(handler); + handler.addProcessListener(new ProcessListener() { + @Override + public void processTerminated(ProcessEvent event) { + updateProjectsFolders(); + } + }); + } + }; + state.setConsoleBuilder(MavenConsoleImpl.createConsoleBuilder(getProject())); + return state; + } + + private void updateProjectsFolders() { + MavenProjectsManager.getInstance(getProject()).updateProjectTargetFolders(); + } + + @Override + @Nonnull + public consulo.module.Module[] getModules() { + return Module.EMPTY_ARRAY; + } + + @Nullable + public MavenGeneralSettings getGeneralSettings() { + return mySettings.myGeneralSettings; + } + + public void setGeneralSettings(@Nullable MavenGeneralSettings settings) { + mySettings.myGeneralSettings = settings; + } + + @Nullable + public MavenRunnerSettings getRunnerSettings() { + return mySettings.myRunnerSettings; + } + + public void setRunnerSettings(@Nullable MavenRunnerSettings settings) { + mySettings.myRunnerSettings = settings; + } + + public MavenRunnerParameters getRunnerParameters() { + return mySettings.myRunnerParameters; + } + + public void setRunnerParameters(MavenRunnerParameters p) { + mySettings.myRunnerParameters = p; + } + + @Override + public void readExternal(Element element) throws InvalidDataException { + super.readExternal(element); + + Element mavenSettingsElement = element.getChild(MavenSettings.TAG); + if (mavenSettingsElement != null) { + mySettings = XmlSerializer.deserialize(mavenSettingsElement, MavenSettings.class); + if (mySettings == null) { + mySettings = new MavenSettings(); + } + + if (mySettings.myRunnerParameters == null) { + mySettings.myRunnerParameters = new MavenRunnerParameters(); + } + + // fix old settings format + mySettings.myRunnerParameters.fixAfterLoadingFromOldFormat(); + } + } + + @Override + public void writeExternal(Element element) throws WriteExternalException { + super.writeExternal(element); + element.addContent(XmlSerializer.serialize(mySettings)); + } + + @Override + public String suggestedName() { + return MavenRunConfigurationType.generateName(getProject(), mySettings.myRunnerParameters); + } + + public static class MavenSettings implements Cloneable { + public static final String TAG = "MavenSettings"; + + public MavenGeneralSettings myGeneralSettings; + public MavenRunnerSettings myRunnerSettings; + public MavenRunnerParameters myRunnerParameters; + + /* reflection only */ + public MavenSettings() { + } + + public MavenSettings(Project project) { + this(null, null, new MavenRunnerParameters()); + } + + private MavenSettings(@Nullable MavenGeneralSettings cs, @Nullable MavenRunnerSettings rs, MavenRunnerParameters rp) { + myGeneralSettings = cs == null ? null : cs.clone(); + myRunnerSettings = rs == null ? null : rs.clone(); + myRunnerParameters = rp.clone(); + } + + @Override + protected MavenSettings clone() { + return new MavenSettings(myGeneralSettings, myRunnerSettings, myRunnerParameters); + } + } } diff --git a/plugin/src/main/java/org/jetbrains/idea/maven/execution/MavenRunConfigurationType.java b/plugin/src/main/java/org/jetbrains/idea/maven/execution/MavenRunConfigurationType.java index abf02737..8bc6f97a 100644 --- a/plugin/src/main/java/org/jetbrains/idea/maven/execution/MavenRunConfigurationType.java +++ b/plugin/src/main/java/org/jetbrains/idea/maven/execution/MavenRunConfigurationType.java @@ -55,173 +55,186 @@ */ @ExtensionImpl public class MavenRunConfigurationType implements ConfigurationType { - private final ConfigurationFactory myFactory; - private static final int MAX_NAME_LENGTH = 40; + private final ConfigurationFactory myFactory; + private static final int MAX_NAME_LENGTH = 40; - public static MavenRunConfigurationType getInstance() { - return ConfigurationTypeUtil.findConfigurationType(MavenRunConfigurationType.class); - } + public static MavenRunConfigurationType getInstance() { + return ConfigurationTypeUtil.findConfigurationType(MavenRunConfigurationType.class); + } - public MavenRunConfigurationType() { - myFactory = new ConfigurationFactory(this) { - @Nonnull - @Override - public String getId() { - // return not localized string - do not break compability - return "Maven"; - } + public MavenRunConfigurationType() { + myFactory = new ConfigurationFactory(this) { + @Nonnull + @Override + public String getId() { + // return not localized string - do not break compability + return "Maven"; + } + + public RunConfiguration createTemplateConfiguration(Project project) { + return new MavenRunConfiguration(project, this, ""); + } + + public RunConfiguration createTemplateConfiguration(Project project, RunManager runManager) { + return new MavenRunConfiguration(project, this, ""); + } + + @Override + public RunConfiguration createConfiguration(String name, RunConfiguration template) { + MavenRunConfiguration cfg = (MavenRunConfiguration)super.createConfiguration(name, template); + + if (!StringUtil.isEmptyOrSpaces(cfg.getRunnerParameters().getWorkingDirPath())) { + return cfg; + } + + Project project = cfg.getProject(); + if (project == null) { + return cfg; + } + + MavenProjectsManager projectsManager = MavenProjectsManager.getInstance(project); + + List projects = projectsManager.getProjects(); + if (projects.size() != 1) { + return cfg; + } + + VirtualFile directory = projects.get(0).getDirectoryFile(); + + cfg.getRunnerParameters().setWorkingDirPath(directory.getPath()); + + return cfg; + } + + @Override + public void configureBeforeRunTaskDefaults(Key providerID, BeforeRunTask task) { + if (providerID == CompileStepBeforeRun.ID || providerID == CompileStepBeforeRunNoErrorCheck.ID) { + task.setEnabled(false); + } + } + }; + } - public RunConfiguration createTemplateConfiguration(Project project) { - return new MavenRunConfiguration(project, this, ""); - } + public LocalizeValue getDisplayName() { + return MavenRunnerLocalize.mavenRunConfigurationName(); + } - public RunConfiguration createTemplateConfiguration(Project project, RunManager runManager) { - return new MavenRunConfiguration(project, this, ""); - } + public LocalizeValue getConfigurationTypeDescription() { + return MavenRunnerLocalize.mavenRunConfigurationDescription(); + } - @Override - public RunConfiguration createConfiguration(String name, RunConfiguration template) { - MavenRunConfiguration cfg = (MavenRunConfiguration)super.createConfiguration(name, template); + public Image getIcon() { + return MavenIconGroup.mavenlogo(); + } - if (!StringUtil.isEmptyOrSpaces(cfg.getRunnerParameters().getWorkingDirPath())) return cfg; + public ConfigurationFactory[] getConfigurationFactories() { + return new ConfigurationFactory[]{myFactory}; + } - Project project = cfg.getProject(); - if (project == null) return cfg; + @NonNls + @Nonnull + public String getId() { + return "MavenRunConfiguration"; + } - MavenProjectsManager projectsManager = MavenProjectsManager.getInstance(project); + public static String generateName(Project project, MavenRunnerParameters runnerParameters) { + StringBuilder stringBuilder = new StringBuilder(); - List projects = projectsManager.getProjects(); - if (projects.size() != 1) { - return cfg; + final String name = getMavenProjectName(project, runnerParameters); + if (!StringUtil.isEmptyOrSpaces(name)) { + stringBuilder.append(name); + stringBuilder.append(" "); } - VirtualFile directory = projects.get(0).getDirectoryFile(); + stringBuilder.append("["); + listGoals(stringBuilder, runnerParameters.getGoals()); + stringBuilder.append("]"); - cfg.getRunnerParameters().setWorkingDirPath(directory.getPath()); + return stringBuilder.toString(); + } - return cfg; - } + private static void listGoals(final StringBuilder stringBuilder, final List goals) { + int index = 0; + for (String goal : goals) { + if (index != 0) { + if (stringBuilder.length() + goal.length() < MAX_NAME_LENGTH) { + stringBuilder.append(","); + } + else { + stringBuilder.append("..."); + break; + } + } + stringBuilder.append(goal); + index++; + } + } - @Override - public void configureBeforeRunTaskDefaults(Key providerID, BeforeRunTask task) { - if (providerID == CompileStepBeforeRun.ID || providerID == CompileStepBeforeRunNoErrorCheck.ID) { - task.setEnabled(false); + @Nullable + private static String getMavenProjectName(final Project project, final MavenRunnerParameters runnerParameters) { + final VirtualFile virtualFile = + LocalFileSystem.getInstance().refreshAndFindFileByPath(runnerParameters.getWorkingDirPath() + "/pom.xml"); + if (virtualFile != null) { + MavenProject mavenProject = MavenProjectsManager.getInstance(project).findProject(virtualFile); + if (mavenProject != null) { + if (!StringUtil.isEmptyOrSpaces(mavenProject.getMavenId().getArtifactId())) { + return mavenProject.getMavenId().getArtifactId(); + } + } } - } - }; - } - - public LocalizeValue getDisplayName() { - return MavenRunnerLocalize.mavenRunConfigurationName(); - } - - public LocalizeValue getConfigurationTypeDescription() { - return MavenRunnerLocalize.mavenRunConfigurationDescription(); - } - - public Image getIcon() { - return MavenIconGroup.mavenlogo(); - } - - public ConfigurationFactory[] getConfigurationFactories() { - return new ConfigurationFactory[]{myFactory}; - } - - @NonNls - @Nonnull - public String getId() { - return "MavenRunConfiguration"; - } - - public static String generateName(Project project, MavenRunnerParameters runnerParameters) { - StringBuilder stringBuilder = new StringBuilder(); - - final String name = getMavenProjectName(project, runnerParameters); - if (!StringUtil.isEmptyOrSpaces(name)) { - stringBuilder.append(name); - stringBuilder.append(" "); + return null; } - stringBuilder.append("["); - listGoals(stringBuilder, runnerParameters.getGoals()); - stringBuilder.append("]"); - return stringBuilder.toString(); - } + public static void runConfiguration( + Project project, + MavenRunnerParameters params, + @Nullable ProgramRunner.Callback callback + ) { + runConfiguration(project, params, null, null, callback); + } - private static void listGoals(final StringBuilder stringBuilder, final List goals) { - int index = 0; - for (String goal : goals) { - if (index != 0) { - if (stringBuilder.length() + goal.length() < MAX_NAME_LENGTH) { - stringBuilder.append(","); + public static void runConfiguration( + Project project, + @Nonnull MavenRunnerParameters params, + @Nullable MavenGeneralSettings settings, + @Nullable MavenRunnerSettings runnerSettings, + @Nullable ProgramRunner.Callback callback + ) { + RunnerAndConfigurationSettings configSettings = createRunnerAndConfigurationSettings( + settings, + runnerSettings, + params, + project + ); + + ProgramRunner runner = DefaultJavaProgramRunner.getInstance(); + Executor executor = DefaultRunExecutor.getRunExecutorInstance(); + ExecutionEnvironment env = new ExecutionEnvironment(executor, runner, configSettings, project); + + try { + runner.execute(env, callback); } - else { - stringBuilder.append("..."); - break; + catch (ExecutionException e) { + MavenUtil.showError(project, "Failed to execute Maven goal", e); } - } - stringBuilder.append(goal); - index++; } - } - - @Nullable - private static String getMavenProjectName(final Project project, final MavenRunnerParameters runnerParameters) { - final VirtualFile virtualFile = LocalFileSystem.getInstance().refreshAndFindFileByPath(runnerParameters.getWorkingDirPath() + "/pom.xml"); - if (virtualFile != null) { - MavenProject mavenProject = MavenProjectsManager.getInstance(project).findProject(virtualFile); - if (mavenProject != null) { - if (!StringUtil.isEmptyOrSpaces(mavenProject.getMavenId().getArtifactId())) { - return mavenProject.getMavenId().getArtifactId(); - } - } - } - return null; - } - - - public static void runConfiguration(Project project, - MavenRunnerParameters params, - @Nullable ProgramRunner.Callback callback) { - runConfiguration(project, params, null, null, callback); - } - - public static void runConfiguration(Project project, - @Nonnull MavenRunnerParameters params, - @Nullable MavenGeneralSettings settings, - @Nullable MavenRunnerSettings runnerSettings, - @Nullable ProgramRunner.Callback callback) { - RunnerAndConfigurationSettings configSettings = createRunnerAndConfigurationSettings(settings, - runnerSettings, - params, - project); - - ProgramRunner runner = DefaultJavaProgramRunner.getInstance(); - Executor executor = DefaultRunExecutor.getRunExecutorInstance(); - ExecutionEnvironment env = new ExecutionEnvironment(executor, runner, configSettings, project); - - try { - runner.execute(env, callback); - } - catch (ExecutionException e) { - MavenUtil.showError(project, "Failed to execute Maven goal", e); + + public static RunnerAndConfigurationSettings createRunnerAndConfigurationSettings( + @Nullable MavenGeneralSettings generalSettings, + @Nullable MavenRunnerSettings runnerSettings, + MavenRunnerParameters params, + Project project + ) { + MavenRunConfigurationType type = ConfigurationTypeUtil.findConfigurationType(MavenRunConfigurationType.class); + + final RunnerAndConfigurationSettings settings = + RunManager.getInstance(project).createRunConfiguration(generateName(project, params), type.myFactory); + MavenRunConfiguration runConfiguration = (MavenRunConfiguration)settings.getConfiguration(); + runConfiguration.setRunnerParameters(params); + runConfiguration.setGeneralSettings(generalSettings); + runConfiguration.setRunnerSettings(runnerSettings); + + return settings; } - } - - public static RunnerAndConfigurationSettings createRunnerAndConfigurationSettings(@Nullable MavenGeneralSettings generalSettings, - @Nullable MavenRunnerSettings runnerSettings, - MavenRunnerParameters params, - Project project) { - MavenRunConfigurationType type = ConfigurationTypeUtil.findConfigurationType(MavenRunConfigurationType.class); - - final RunnerAndConfigurationSettings settings = RunManager.getInstance(project) - .createRunConfiguration(generateName(project, params), type.myFactory); - MavenRunConfiguration runConfiguration = (MavenRunConfiguration)settings.getConfiguration(); - runConfiguration.setRunnerParameters(params); - runConfiguration.setGeneralSettings(generalSettings); - runConfiguration.setRunnerSettings(runnerSettings); - - return settings; - } } diff --git a/plugin/src/main/java/org/jetbrains/idea/maven/execution/MavenRunner.java b/plugin/src/main/java/org/jetbrains/idea/maven/execution/MavenRunner.java index f664f2f6..6ceff252 100644 --- a/plugin/src/main/java/org/jetbrains/idea/maven/execution/MavenRunner.java +++ b/plugin/src/main/java/org/jetbrains/idea/maven/execution/MavenRunner.java @@ -48,185 +48,156 @@ @Singleton @ServiceAPI(ComponentScope.PROJECT) @ServiceImpl -public class MavenRunner implements PersistentStateComponent -{ - private static final Logger LOG = Logger.getInstance(MavenRunner.class); - - private MavenRunnerSettings mySettings = new MavenRunnerSettings(); - private final Project myProject; - - public static MavenRunner getInstance(Project project) - { - return ServiceManager.getService(project, MavenRunner.class); - } - - @Inject - public MavenRunner(final Project project) - { - myProject = project; - } - - public MavenRunnerSettings getSettings() - { - return mySettings; - } - - public MavenRunnerSettings getState() - { - return mySettings; - } - - public void loadState(MavenRunnerSettings settings) - { - mySettings = settings; - } - - public void run(final MavenRunnerParameters parameters, final MavenRunnerSettings settings, final Runnable onComplete) - { - FileDocumentManager.getInstance().saveAllDocuments(); - - final MavenConsole console = createConsole(); - try - { - final MavenExecutor[] executor = new MavenExecutor[]{createExecutor(parameters, null, settings, console)}; - - ProgressManager.getInstance().run(new Task.Backgroundable(myProject, executor[0].getCaption(), true) - { - public void run(@Nonnull ProgressIndicator indicator) - { - try - { - try - { - if(executor[0].execute(indicator)) - { - if(onComplete != null) - { - onComplete.run(); - } - } - } - catch(ProcessCanceledException ignore) - { - } - - executor[0] = null; - updateTargetFolders(); - } - finally - { - console.finish(); - } - } - - @Nullable - public NotificationInfo getNotificationInfo() - { - return new NotificationInfo("Maven", "Maven Task Finished", ""); - } - - public boolean shouldStartInBackground() - { - return settings.isRunMavenInBackground(); - } - - public void processSentToBackground() - { - settings.setRunMavenInBackground(true); - } - - public void processRestoredToForeground() - { - settings.setRunMavenInBackground(false); - } - }); - } - catch(Exception e) - { - console.printException(e); - console.finish(); - MavenLog.LOG.warn(e); - } - } - - public boolean runBatch(List commands, - @Nullable MavenGeneralSettings coreSettings, - @Nullable MavenRunnerSettings runnerSettings, - @Nullable final String action, - @Nullable ProgressIndicator indicator) - { - LOG.assertTrue(!ApplicationManager.getApplication().isReadAccessAllowed()); - - if(commands.isEmpty()) - { - return true; - } - - MavenConsole console = ReadAction.compute(() -> myProject.isDisposed() ? null : createConsole()); - - if(console == null) - { - return false; - } - - try - { - int count = 0; - for(MavenRunnerParameters command : commands) - { - if(indicator != null) - { - indicator.setFraction(((double) count++) / commands.size()); - } - - MavenExecutor executor = ReadAction.compute(() -> myProject.isDisposed() ? null : createExecutor(command, coreSettings, runnerSettings, console)); - - if(executor == null) - { - break; - } - - executor.setAction(action); - if(!executor.execute(indicator)) - { - updateTargetFolders(); - return false; - } - } - - updateTargetFolders(); - } - finally - { - console.finish(); - } - - return true; - } - - private void updateTargetFolders() - { - if(myProject.isDisposed()) - { - return; // project was closed before task finished. - } - MavenProjectsManager.getInstance(myProject).updateProjectTargetFolders(); - } - - private MavenConsole createConsole() - { - if(ApplicationManager.getApplication().isUnitTestMode()) - { - return new SoutMavenConsole(); - } - return new MavenConsoleImpl("Maven Goal", myProject); - } - - private MavenExecutor createExecutor(MavenRunnerParameters taskParameters, - @Nullable MavenGeneralSettings coreSettings, - @Nullable MavenRunnerSettings runnerSettings, - MavenConsole console) - { - return new MavenExternalExecutor(myProject, taskParameters, coreSettings, runnerSettings, console); - } +public class MavenRunner implements PersistentStateComponent { + private static final Logger LOG = Logger.getInstance(MavenRunner.class); + + private MavenRunnerSettings mySettings = new MavenRunnerSettings(); + private final Project myProject; + + public static MavenRunner getInstance(Project project) { + return ServiceManager.getService(project, MavenRunner.class); + } + + @Inject + public MavenRunner(final Project project) { + myProject = project; + } + + public MavenRunnerSettings getSettings() { + return mySettings; + } + + public MavenRunnerSettings getState() { + return mySettings; + } + + public void loadState(MavenRunnerSettings settings) { + mySettings = settings; + } + + public void run(final MavenRunnerParameters parameters, final MavenRunnerSettings settings, final Runnable onComplete) { + FileDocumentManager.getInstance().saveAllDocuments(); + + final MavenConsole console = createConsole(); + try { + final MavenExecutor[] executor = new MavenExecutor[]{createExecutor(parameters, null, settings, console)}; + + ProgressManager.getInstance().run(new Task.Backgroundable(myProject, executor[0].getCaption(), true) { + public void run(@Nonnull ProgressIndicator indicator) { + try { + try { + if (executor[0].execute(indicator) && onComplete != null) { + onComplete.run(); + } + } + catch (ProcessCanceledException ignore) { + } + + executor[0] = null; + updateTargetFolders(); + } + finally { + console.finish(); + } + } + + @Nullable + public NotificationInfo getNotificationInfo() { + return new NotificationInfo("Maven", "Maven Task Finished", ""); + } + + public boolean shouldStartInBackground() { + return settings.isRunMavenInBackground(); + } + + public void processSentToBackground() { + settings.setRunMavenInBackground(true); + } + + public void processRestoredToForeground() { + settings.setRunMavenInBackground(false); + } + }); + } + catch (Exception e) { + console.printException(e); + console.finish(); + MavenLog.LOG.warn(e); + } + } + + public boolean runBatch( + List commands, + @Nullable MavenGeneralSettings coreSettings, + @Nullable MavenRunnerSettings runnerSettings, + @Nullable final String action, + @Nullable ProgressIndicator indicator + ) { + LOG.assertTrue(!ApplicationManager.getApplication().isReadAccessAllowed()); + + if (commands.isEmpty()) { + return true; + } + + MavenConsole console = ReadAction.compute(() -> myProject.isDisposed() ? null : createConsole()); + + if (console == null) { + return false; + } + + try { + int count = 0; + for (MavenRunnerParameters command : commands) { + if (indicator != null) { + indicator.setFraction(((double)count++) / commands.size()); + } + + MavenExecutor executor = ReadAction.compute(() -> myProject.isDisposed() ? null : createExecutor(command, + coreSettings, + runnerSettings, + console + )); + + if (executor == null) { + break; + } + + executor.setAction(action); + if (!executor.execute(indicator)) { + updateTargetFolders(); + return false; + } + } + + updateTargetFolders(); + } + finally { + console.finish(); + } + + return true; + } + + private void updateTargetFolders() { + if (myProject.isDisposed()) { + return; // project was closed before task finished. + } + MavenProjectsManager.getInstance(myProject).updateProjectTargetFolders(); + } + + private MavenConsole createConsole() { + if (ApplicationManager.getApplication().isUnitTestMode()) { + return new SoutMavenConsole(); + } + return new MavenConsoleImpl("Maven Goal", myProject); + } + + private MavenExecutor createExecutor( + MavenRunnerParameters taskParameters, + @Nullable MavenGeneralSettings coreSettings, + @Nullable MavenRunnerSettings runnerSettings, + MavenConsole console + ) { + return new MavenExternalExecutor(myProject, taskParameters, coreSettings, runnerSettings, console); + } } diff --git a/plugin/src/main/java/org/jetbrains/idea/maven/execution/MavenRunnerConfigurable.java b/plugin/src/main/java/org/jetbrains/idea/maven/execution/MavenRunnerConfigurable.java index 54182779..e1bbd03e 100644 --- a/plugin/src/main/java/org/jetbrains/idea/maven/execution/MavenRunnerConfigurable.java +++ b/plugin/src/main/java/org/jetbrains/idea/maven/execution/MavenRunnerConfigurable.java @@ -14,49 +14,47 @@ */ public abstract class MavenRunnerConfigurable extends MavenRunnerPanel implements SearchableConfigurable, Configurable.NoScroll { - public MavenRunnerConfigurable(@Nonnull Project p, boolean isRunConfiguration) { - super(p, isRunConfiguration); - } - - @Nullable - protected abstract MavenRunnerSettings getState(); - - public boolean isModified() { - MavenRunnerSettings s = new MavenRunnerSettings(); - apply(s); - return !s.equals(getState()); - } - - public void apply() throws ConfigurationException - { - apply(getState()); - } - - public void reset() { - reset(getState()); - } - - @Nls - public String getDisplayName() { - return RunnerBundle.message("maven.tab.runner"); - } - - @Nullable - public String getHelpTopic() { - return "reference.settings.project.maven.runner"; - } - - @Nonnull - public String getId() { - //noinspection ConstantConditions - return getHelpTopic(); - } - - public Runnable enableSearch(String option) { - return null; - } - - public void disposeUIResources() { - - } + public MavenRunnerConfigurable(@Nonnull Project p, boolean isRunConfiguration) { + super(p, isRunConfiguration); + } + + @Nullable + protected abstract MavenRunnerSettings getState(); + + public boolean isModified() { + MavenRunnerSettings s = new MavenRunnerSettings(); + apply(s); + return !s.equals(getState()); + } + + public void apply() throws ConfigurationException { + apply(getState()); + } + + public void reset() { + reset(getState()); + } + + @Nls + public String getDisplayName() { + return RunnerBundle.message("maven.tab.runner"); + } + + @Nullable + public String getHelpTopic() { + return "reference.settings.project.maven.runner"; + } + + @Nonnull + public String getId() { + //noinspection ConstantConditions + return getHelpTopic(); + } + + public Runnable enableSearch(String option) { + return null; + } + + public void disposeUIResources() { + } } diff --git a/plugin/src/main/java/org/jetbrains/idea/maven/execution/MavenRunnerConfigurableWithUseProjectSettings.java b/plugin/src/main/java/org/jetbrains/idea/maven/execution/MavenRunnerConfigurableWithUseProjectSettings.java index 51108ac1..a69bdd30 100644 --- a/plugin/src/main/java/org/jetbrains/idea/maven/execution/MavenRunnerConfigurableWithUseProjectSettings.java +++ b/plugin/src/main/java/org/jetbrains/idea/maven/execution/MavenRunnerConfigurableWithUseProjectSettings.java @@ -29,63 +29,63 @@ * @author Sergey Evdokimov */ public abstract class MavenRunnerConfigurableWithUseProjectSettings extends MavenRunnerConfigurable { + private JCheckBox myUseProjectSettings; - private JCheckBox myUseProjectSettings; - - public MavenRunnerConfigurableWithUseProjectSettings(@Nonnull Project project) { - super(project, true); - } + public MavenRunnerConfigurableWithUseProjectSettings(@Nonnull Project project) { + super(project, true); + } - public abstract void setState(@Nullable MavenRunnerSettings state); + public abstract void setState(@Nullable MavenRunnerSettings state); - @Override - public boolean isModified() { - if (myUseProjectSettings.isSelected()) { - return getState() != null; - } - else { - return getState() == null || super.isModified(); + @Override + public boolean isModified() { + if (myUseProjectSettings.isSelected()) { + return getState() != null; + } + else { + return getState() == null || super.isModified(); + } } - } - @Override - public void apply() { - if (myUseProjectSettings.isSelected()) { - setState(null); + @Override + public void apply() { + if (myUseProjectSettings.isSelected()) { + setState(null); + } + else { + MavenRunnerSettings state = getState(); + if (state != null) { + apply(state); + } + else { + MavenRunnerSettings settings = MavenRunner.getInstance(myProject).getSettings().clone(); + apply(settings); + setState(settings); + } + } } - else { - MavenRunnerSettings state = getState(); - if (state != null) { - apply(state); - } - else { - MavenRunnerSettings settings = MavenRunner.getInstance(myProject).getSettings().clone(); - apply(settings); - setState(settings); - } - } - } - @Override - public void reset() { - MavenRunnerSettings state = getState(); - myUseProjectSettings.setSelected(state == null); + @Override + public void reset() { + MavenRunnerSettings state = getState(); + myUseProjectSettings.setSelected(state == null); - if (state == null) { - MavenRunnerSettings settings = MavenRunner.getInstance(myProject).getSettings(); - reset(settings); - } - else { - reset(state); + if (state == null) { + MavenRunnerSettings settings = MavenRunner.getInstance(myProject).getSettings(); + reset(settings); + } + else { + reset(state); + } } - } - @RequiredUIAccess - @Override - public JComponent createComponent(@Nonnull Disposable uiDisposable) { - Pair pair = MavenDisablePanelCheckbox.createPanel(super.createComponent(uiDisposable), "Use project settings"); + @RequiredUIAccess + @Override + public JComponent createComponent(@Nonnull Disposable uiDisposable) { + Pair pair = + MavenDisablePanelCheckbox.createPanel(super.createComponent(uiDisposable), "Use project settings"); - myUseProjectSettings = pair.second; - return pair.first; - } + myUseProjectSettings = pair.second; + return pair.first; + } } diff --git a/plugin/src/main/java/org/jetbrains/idea/maven/execution/MavenRunnerPanel.java b/plugin/src/main/java/org/jetbrains/idea/maven/execution/MavenRunnerPanel.java index 2424abaa..1877130a 100644 --- a/plugin/src/main/java/org/jetbrains/idea/maven/execution/MavenRunnerPanel.java +++ b/plugin/src/main/java/org/jetbrains/idea/maven/execution/MavenRunnerPanel.java @@ -37,154 +37,151 @@ import java.util.Map; import java.util.Properties; -public class MavenRunnerPanel -{ - protected final Project myProject; - private final boolean myRunConfigurationMode; - - private JCheckBox myRunInBackgroundCheckbox; - private RawCommandLineEditor myVMParametersEditor; - private EnvironmentVariablesComponent myEnvVariablesComponent; - private SdkComboBox myJdkCombo; - private JCheckBox mySkipTestsCheckBox; - private MavenPropertiesPanel myPropertiesPanel; - - private Map myProperties; - - public MavenRunnerPanel(@Nonnull Project p, boolean isRunConfiguration) - { - myProject = p; - myRunConfigurationMode = isRunConfiguration; - } - - public JComponent createComponent(@Nonnull Disposable uiDiposable) - { - JPanel panel = new JPanel(new GridBagLayout()); - - GridBagConstraints c = new GridBagConstraints(); - c.fill = GridBagConstraints.HORIZONTAL; - c.anchor = GridBagConstraints.WEST; - c.insets.bottom = 5; - - myRunInBackgroundCheckbox = new JCheckBox("Run in background"); - myRunInBackgroundCheckbox.setMnemonic('b'); - if(!myRunConfigurationMode) - { - c.gridx = 0; - c.gridy++; - c.weightx = 1; - c.gridwidth = GridBagConstraints.REMAINDER; - - panel.add(myRunInBackgroundCheckbox, c); - } - c.gridwidth = 1; - - JLabel labelVMParameters = new JLabel("VM Options:"); - labelVMParameters.setDisplayedMnemonic('v'); - labelVMParameters.setLabelFor(myVMParametersEditor = new RawCommandLineEditor()); - myVMParametersEditor.setDialogCaption(labelVMParameters.getText()); - - c.gridx = 0; - c.gridy++; - c.weightx = 0; - panel.add(labelVMParameters, c); - - c.gridx = 1; - c.weightx = 1; - c.insets.left = 10; - panel.add(myVMParametersEditor, c); - c.insets.left = 0; - - JLabel jdkLabel = new JLabel("JRE:"); - jdkLabel.setDisplayedMnemonic('j'); - SdkModel sdksModel = ShowSettingsUtil.getInstance().getSdksModel(); - myJdkCombo = new SdkComboBox(sdksModel, it -> it instanceof JavaSdkType, null, "Auto Select", AllIcons.Actions.FindPlain); - - jdkLabel.setLabelFor(myJdkCombo); - c.gridx = 0; - c.gridy++; - c.weightx = 0; - panel.add(jdkLabel, c); - c.gridx = 1; - c.weightx = 1; - c.fill = GridBagConstraints.NONE; - c.insets.left = 10; - panel.add(myJdkCombo, c); - c.insets.left = 0; - c.fill = GridBagConstraints.HORIZONTAL; - - myEnvVariablesComponent = new EnvironmentVariablesComponent(); - myEnvVariablesComponent.setPassParentEnvs(true); - myEnvVariablesComponent.setLabelLocation(BorderLayout.WEST); - c.gridx = 0; - c.gridy++; - c.weightx = 1; - c.gridwidth = 2; - panel.add(myEnvVariablesComponent, c); - c.gridwidth = 1; - - JPanel propertiesPanel = new JPanel(new BorderLayout()); - propertiesPanel.setBorder(IdeBorderFactory.createTitledBorder("Properties", false)); - - propertiesPanel.add(mySkipTestsCheckBox = new JCheckBox("Skip tests"), BorderLayout.NORTH); - mySkipTestsCheckBox.setMnemonic('t'); - - collectProperties(); - propertiesPanel.add(myPropertiesPanel = new MavenPropertiesPanel(myProperties), BorderLayout.CENTER); - myPropertiesPanel.getEmptyText().setText("No properties defined"); - - c.gridx = 0; - c.gridy++; - c.weightx = c.weighty = 1; - c.gridwidth = c.gridheight = GridBagConstraints.REMAINDER; - c.fill = GridBagConstraints.BOTH; - panel.add(propertiesPanel, c); - - return panel; - } - - private void collectProperties() - { - MavenProjectsManager s = MavenProjectsManager.getInstance(myProject); - Map result = new LinkedHashMap(); - - for(MavenProject each : s.getProjects()) - { - Properties properties = each.getProperties(); - result.putAll((Map) properties); - } - - myProperties = result; - } - - protected void reset(MavenRunnerSettings data) - { - myRunInBackgroundCheckbox.setSelected(data.isRunMavenInBackground()); - myVMParametersEditor.setText(data.getVmOptions()); - mySkipTestsCheckBox.setSelected(data.isSkipTests()); - - myJdkCombo.setSelectedSdk(data.getJreName()); - myPropertiesPanel.setDataFromMap(data.getMavenProperties()); - - myEnvVariablesComponent.setEnvs(data.getEnvironmentProperties()); - myEnvVariablesComponent.setPassParentEnvs(data.isPassParentEnv()); - } - - protected void apply(MavenRunnerSettings data) - { - data.setRunMavenInBackground(myRunInBackgroundCheckbox.isSelected()); - data.setVmOptions(myVMParametersEditor.getText().trim()); - data.setSkipTests(mySkipTestsCheckBox.isSelected()); - data.setJreName(myJdkCombo.getSelectedSdkName()); - - data.setMavenProperties(myPropertiesPanel.getDataAsMap()); - - data.setEnvironmentProperties(myEnvVariablesComponent.getEnvs()); - data.setPassParentEnv(myEnvVariablesComponent.isPassParentEnvs()); - } - - public Project getProject() - { - return myProject; - } +public class MavenRunnerPanel { + protected final Project myProject; + private final boolean myRunConfigurationMode; + + private JCheckBox myRunInBackgroundCheckbox; + private RawCommandLineEditor myVMParametersEditor; + private EnvironmentVariablesComponent myEnvVariablesComponent; + private SdkComboBox myJdkCombo; + private JCheckBox mySkipTestsCheckBox; + private MavenPropertiesPanel myPropertiesPanel; + + private Map myProperties; + + public MavenRunnerPanel(@Nonnull Project p, boolean isRunConfiguration) { + myProject = p; + myRunConfigurationMode = isRunConfiguration; + } + + public JComponent createComponent(@Nonnull Disposable uiDiposable) { + JPanel panel = new JPanel(new GridBagLayout()); + + GridBagConstraints c = new GridBagConstraints(); + c.fill = GridBagConstraints.HORIZONTAL; + c.anchor = GridBagConstraints.WEST; + c.insets.bottom = 5; + + myRunInBackgroundCheckbox = new JCheckBox("Run in background"); + myRunInBackgroundCheckbox.setMnemonic('b'); + if (!myRunConfigurationMode) { + c.gridx = 0; + c.gridy++; + c.weightx = 1; + c.gridwidth = GridBagConstraints.REMAINDER; + + panel.add(myRunInBackgroundCheckbox, c); + } + c.gridwidth = 1; + + JLabel labelVMParameters = new JLabel("VM Options:"); + labelVMParameters.setDisplayedMnemonic('v'); + labelVMParameters.setLabelFor(myVMParametersEditor = new RawCommandLineEditor()); + myVMParametersEditor.setDialogCaption(labelVMParameters.getText()); + + c.gridx = 0; + c.gridy++; + c.weightx = 0; + panel.add(labelVMParameters, c); + + c.gridx = 1; + c.weightx = 1; + c.insets.left = 10; + panel.add(myVMParametersEditor, c); + c.insets.left = 0; + + JLabel jdkLabel = new JLabel("JRE:"); + jdkLabel.setDisplayedMnemonic('j'); + SdkModel sdksModel = ShowSettingsUtil.getInstance().getSdksModel(); + myJdkCombo = new SdkComboBox( + sdksModel, + it -> it instanceof JavaSdkType, + null, + "Auto Select", + AllIcons.Actions.FindPlain + ); + + jdkLabel.setLabelFor(myJdkCombo); + c.gridx = 0; + c.gridy++; + c.weightx = 0; + panel.add(jdkLabel, c); + c.gridx = 1; + c.weightx = 1; + c.fill = GridBagConstraints.NONE; + c.insets.left = 10; + panel.add(myJdkCombo, c); + c.insets.left = 0; + c.fill = GridBagConstraints.HORIZONTAL; + + myEnvVariablesComponent = new EnvironmentVariablesComponent(); + myEnvVariablesComponent.setPassParentEnvs(true); + myEnvVariablesComponent.setLabelLocation(BorderLayout.WEST); + c.gridx = 0; + c.gridy++; + c.weightx = 1; + c.gridwidth = 2; + panel.add(myEnvVariablesComponent, c); + c.gridwidth = 1; + + JPanel propertiesPanel = new JPanel(new BorderLayout()); + propertiesPanel.setBorder(IdeBorderFactory.createTitledBorder("Properties", false)); + + propertiesPanel.add(mySkipTestsCheckBox = new JCheckBox("Skip tests"), BorderLayout.NORTH); + mySkipTestsCheckBox.setMnemonic('t'); + + collectProperties(); + propertiesPanel.add(myPropertiesPanel = new MavenPropertiesPanel(myProperties), BorderLayout.CENTER); + myPropertiesPanel.getEmptyText().setText("No properties defined"); + + c.gridx = 0; + c.gridy++; + c.weightx = c.weighty = 1; + c.gridwidth = c.gridheight = GridBagConstraints.REMAINDER; + c.fill = GridBagConstraints.BOTH; + panel.add(propertiesPanel, c); + + return panel; + } + + private void collectProperties() { + MavenProjectsManager s = MavenProjectsManager.getInstance(myProject); + Map result = new LinkedHashMap<>(); + + for (MavenProject each : s.getProjects()) { + Properties properties = each.getProperties(); + result.putAll((Map)properties); + } + + myProperties = result; + } + + protected void reset(MavenRunnerSettings data) { + myRunInBackgroundCheckbox.setSelected(data.isRunMavenInBackground()); + myVMParametersEditor.setText(data.getVmOptions()); + mySkipTestsCheckBox.setSelected(data.isSkipTests()); + + myJdkCombo.setSelectedSdk(data.getJreName()); + myPropertiesPanel.setDataFromMap(data.getMavenProperties()); + + myEnvVariablesComponent.setEnvs(data.getEnvironmentProperties()); + myEnvVariablesComponent.setPassParentEnvs(data.isPassParentEnv()); + } + + protected void apply(MavenRunnerSettings data) { + data.setRunMavenInBackground(myRunInBackgroundCheckbox.isSelected()); + data.setVmOptions(myVMParametersEditor.getText().trim()); + data.setSkipTests(mySkipTestsCheckBox.isSelected()); + data.setJreName(myJdkCombo.getSelectedSdkName()); + + data.setMavenProperties(myPropertiesPanel.getDataAsMap()); + + data.setEnvironmentProperties(myEnvVariablesComponent.getEnvs()); + data.setPassParentEnv(myEnvVariablesComponent.isPassParentEnvs()); + } + + public Project getProject() { + return myProject; + } } diff --git a/plugin/src/main/java/org/jetbrains/idea/maven/execution/MavenRunnerParameters.java b/plugin/src/main/java/org/jetbrains/idea/maven/execution/MavenRunnerParameters.java index 14b399db..298c2c2e 100644 --- a/plugin/src/main/java/org/jetbrains/idea/maven/execution/MavenRunnerParameters.java +++ b/plugin/src/main/java/org/jetbrains/idea/maven/execution/MavenRunnerParameters.java @@ -29,262 +29,232 @@ import java.io.File; import java.util.*; -public class MavenRunnerParameters implements Cloneable -{ - private boolean isPomExecution; - private Path myWorkingDirPath; - private final List myGoals = new ArrayList(); - - private boolean myResolveToWorkspace; - - private final Map myProfilesMap = new LinkedHashMap(); - - private final Collection myEnabledProfilesForXmlSerializer = new TreeSet(); - - public MavenRunnerParameters() - { - this(true, "", null, null, null); - } - - public MavenRunnerParameters(boolean isPomExecution, @Nonnull String workingDirPath, @Nullable List goals, @Nullable Collection explicitEnabledProfiles) - { - this(isPomExecution, workingDirPath, goals, explicitEnabledProfiles, null); - } - - public MavenRunnerParameters(boolean isPomExecution, @Nonnull String workingDirPath, @Nullable List goals, @Nonnull MavenExplicitProfiles explicitProfiles) - { - this(isPomExecution, workingDirPath, goals, explicitProfiles.getEnabledProfiles(), explicitProfiles.getDisabledProfiles()); - } - - public MavenRunnerParameters(boolean isPomExecution, - @Nonnull String workingDirPath, - @Nullable List goals, - @Nullable Collection explicitEnabledProfiles, - @Nullable Collection explicitDisabledProfiles) - { - this.isPomExecution = isPomExecution; - setWorkingDirPath(workingDirPath); - setGoals(goals); - - if(explicitEnabledProfiles != null) - { - for(String profile : explicitEnabledProfiles) - { - myProfilesMap.put(profile, Boolean.TRUE); - } - } - - if(explicitDisabledProfiles != null) - { - for(String profile : explicitDisabledProfiles) - { - myProfilesMap.put(profile, Boolean.FALSE); - } - } - } - - public MavenRunnerParameters(String workingDirPath, boolean isPomExecution, @Nullable List goals, @Nonnull Map profilesMap) - { - this.isPomExecution = isPomExecution; - setWorkingDirPath(workingDirPath); - setGoals(goals); - setProfilesMap(profilesMap); - } - - public MavenRunnerParameters(MavenRunnerParameters that) - { - this(that.getWorkingDirPath(), that.isPomExecution, that.myGoals, that.myProfilesMap); - myResolveToWorkspace = that.myResolveToWorkspace; - } - - public boolean isPomExecution() - { - return isPomExecution; - } - - @Nonnull - public String getWorkingDirPath() - { - return myWorkingDirPath.getPath(); - } - - public void setWorkingDirPath(@Nonnull String workingDirPath) - { - myWorkingDirPath = new Path(workingDirPath); - } - - @Nonnull - public File getWorkingDirFile() - { - return new File(myWorkingDirPath.getPath()); - } - - public List getGoals() - { - return myGoals; - } - - public void setGoals(@Nullable List goals) - { - if(myGoals == goals) - { - return; // Called from XML Serializer - } - myGoals.clear(); - - if(goals != null) - { - myGoals.addAll(goals); - } - } - - @Deprecated // Must be used by XML Serializer only!!! - @OptionTag("profiles") - public Collection getEnabledProfilesForXmlSerializer() - { - return myEnabledProfilesForXmlSerializer; - } - - @Deprecated // Must be used by XML Serializer only!!! - public void setEnabledProfilesForXmlSerializer(@Nullable Collection enabledProfilesForXmlSerializer) - { - if(enabledProfilesForXmlSerializer != null) - { - if(myEnabledProfilesForXmlSerializer == enabledProfilesForXmlSerializer) - { - return; // Called from XML Serializer - } - myEnabledProfilesForXmlSerializer.retainAll(enabledProfilesForXmlSerializer); - myEnabledProfilesForXmlSerializer.addAll(enabledProfilesForXmlSerializer); - } - } - - public void fixAfterLoadingFromOldFormat() - { - for(String profile : myEnabledProfilesForXmlSerializer) - { - myProfilesMap.put(profile, true); - } - myEnabledProfilesForXmlSerializer.clear(); - - File workingDir = getWorkingDirFile(); - if(MavenConstants.POM_XML.equals(workingDir.getName())) - { - setWorkingDirPath(workingDir.getParent()); - } - } - - @OptionTag("profilesMap") - @MapAnnotation(sortBeforeSave = false) - public Map getProfilesMap() - { - return myProfilesMap; - } - - public void setProfilesMap(@Nonnull Map profilesMap) - { - if(myProfilesMap == profilesMap) - { - return; // Called from XML Serializer - } - myProfilesMap.clear(); - for(Map.Entry entry : profilesMap.entrySet()) - { - if(entry.getValue() != null) - { - myProfilesMap.put(entry.getKey(), entry.getValue()); - } - } - } - - /** - * Was left for compatibility with old plugins. - * - * @return - * @deprecated use getProfileMap() - */ - @Transient - public Collection getProfiles() - { - return Maps.filterValues(myProfilesMap, Predicates.equalTo(true)).keySet(); - } - - /** - * Was left for compatibility with old plugins. - * - * @param profiles - * @deprecated use getProfileMap() - */ - public void setProfiles(@Nullable Collection profiles) - { - if(profiles != null) - { - for(String profile : profiles) - { - myProfilesMap.put(profile, true); - } - } - } - - public boolean isResolveToWorkspace() - { - return myResolveToWorkspace; - } - - public void setResolveToWorkspace(boolean resolveToWorkspace) - { - myResolveToWorkspace = resolveToWorkspace; - } - - public MavenRunnerParameters clone() - { - return new MavenRunnerParameters(this); - } - - public boolean equals(Object o) - { - if(this == o) - { - return true; - } - if(o == null || getClass() != o.getClass()) - { - return false; - } - - final MavenRunnerParameters that = (MavenRunnerParameters) o; - - if(isPomExecution != that.isPomExecution) - { - return false; - } - if(myResolveToWorkspace != that.myResolveToWorkspace) - { - return false; - } - if(!myGoals.equals(that.myGoals)) - { - return false; - } - if(myWorkingDirPath != null ? !myWorkingDirPath.equals(that.myWorkingDirPath) : that.myWorkingDirPath != null) - { - return false; - } - if(!myProfilesMap.equals(that.myProfilesMap)) - { - return false; - } - - return true; - } - - public int hashCode() - { - int result; - result = isPomExecution ? 1 : 0; - result = 31 * result + (myWorkingDirPath != null ? myWorkingDirPath.hashCode() : 0); - result = 31 * result + myGoals.hashCode(); - result = 31 * result + myProfilesMap.hashCode(); - return result; - } +public class MavenRunnerParameters implements Cloneable { + private boolean isPomExecution; + private Path myWorkingDirPath; + private final List myGoals = new ArrayList(); + + private boolean myResolveToWorkspace; + + private final Map myProfilesMap = new LinkedHashMap(); + + private final Collection myEnabledProfilesForXmlSerializer = new TreeSet(); + + public MavenRunnerParameters() { + this(true, "", null, null, null); + } + + public MavenRunnerParameters( + boolean isPomExecution, + @Nonnull String workingDirPath, + @Nullable List goals, + @Nullable Collection explicitEnabledProfiles + ) { + this(isPomExecution, workingDirPath, goals, explicitEnabledProfiles, null); + } + + public MavenRunnerParameters( + boolean isPomExecution, + @Nonnull String workingDirPath, + @Nullable List goals, + @Nonnull MavenExplicitProfiles explicitProfiles + ) { + this(isPomExecution, workingDirPath, goals, explicitProfiles.getEnabledProfiles(), explicitProfiles.getDisabledProfiles()); + } + + public MavenRunnerParameters( + boolean isPomExecution, + @Nonnull String workingDirPath, + @Nullable List goals, + @Nullable Collection explicitEnabledProfiles, + @Nullable Collection explicitDisabledProfiles + ) { + this.isPomExecution = isPomExecution; + setWorkingDirPath(workingDirPath); + setGoals(goals); + + if (explicitEnabledProfiles != null) { + for (String profile : explicitEnabledProfiles) { + myProfilesMap.put(profile, Boolean.TRUE); + } + } + + if (explicitDisabledProfiles != null) { + for (String profile : explicitDisabledProfiles) { + myProfilesMap.put(profile, Boolean.FALSE); + } + } + } + + public MavenRunnerParameters( + String workingDirPath, + boolean isPomExecution, + @Nullable List goals, + @Nonnull Map profilesMap + ) { + this.isPomExecution = isPomExecution; + setWorkingDirPath(workingDirPath); + setGoals(goals); + setProfilesMap(profilesMap); + } + + public MavenRunnerParameters(MavenRunnerParameters that) { + this(that.getWorkingDirPath(), that.isPomExecution, that.myGoals, that.myProfilesMap); + myResolveToWorkspace = that.myResolveToWorkspace; + } + + public boolean isPomExecution() { + return isPomExecution; + } + + @Nonnull + public String getWorkingDirPath() { + return myWorkingDirPath.getPath(); + } + + public void setWorkingDirPath(@Nonnull String workingDirPath) { + myWorkingDirPath = new Path(workingDirPath); + } + + @Nonnull + public File getWorkingDirFile() { + return new File(myWorkingDirPath.getPath()); + } + + public List getGoals() { + return myGoals; + } + + public void setGoals(@Nullable List goals) { + if (myGoals == goals) { + return; // Called from XML Serializer + } + myGoals.clear(); + + if (goals != null) { + myGoals.addAll(goals); + } + } + + @Deprecated // Must be used by XML Serializer only!!! + @OptionTag("profiles") + public Collection getEnabledProfilesForXmlSerializer() { + return myEnabledProfilesForXmlSerializer; + } + + @Deprecated // Must be used by XML Serializer only!!! + public void setEnabledProfilesForXmlSerializer(@Nullable Collection enabledProfilesForXmlSerializer) { + if (enabledProfilesForXmlSerializer != null) { + if (myEnabledProfilesForXmlSerializer == enabledProfilesForXmlSerializer) { + return; // Called from XML Serializer + } + myEnabledProfilesForXmlSerializer.retainAll(enabledProfilesForXmlSerializer); + myEnabledProfilesForXmlSerializer.addAll(enabledProfilesForXmlSerializer); + } + } + + public void fixAfterLoadingFromOldFormat() { + for (String profile : myEnabledProfilesForXmlSerializer) { + myProfilesMap.put(profile, true); + } + myEnabledProfilesForXmlSerializer.clear(); + + File workingDir = getWorkingDirFile(); + if (MavenConstants.POM_XML.equals(workingDir.getName())) { + setWorkingDirPath(workingDir.getParent()); + } + } + + @OptionTag("profilesMap") + @MapAnnotation(sortBeforeSave = false) + public Map getProfilesMap() { + return myProfilesMap; + } + + public void setProfilesMap(@Nonnull Map profilesMap) { + if (myProfilesMap == profilesMap) { + return; // Called from XML Serializer + } + myProfilesMap.clear(); + for (Map.Entry entry : profilesMap.entrySet()) { + if (entry.getValue() != null) { + myProfilesMap.put(entry.getKey(), entry.getValue()); + } + } + } + + /** + * Was left for compatibility with old plugins. + * + * @return + * @deprecated use getProfileMap() + */ + @Transient + public Collection getProfiles() { + return Maps.filterValues(myProfilesMap, Predicates.equalTo(true)).keySet(); + } + + /** + * Was left for compatibility with old plugins. + * + * @param profiles + * @deprecated use getProfileMap() + */ + public void setProfiles(@Nullable Collection profiles) { + if (profiles != null) { + for (String profile : profiles) { + myProfilesMap.put(profile, true); + } + } + } + + public boolean isResolveToWorkspace() { + return myResolveToWorkspace; + } + + public void setResolveToWorkspace(boolean resolveToWorkspace) { + myResolveToWorkspace = resolveToWorkspace; + } + + public MavenRunnerParameters clone() { + return new MavenRunnerParameters(this); + } + + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + + final MavenRunnerParameters that = (MavenRunnerParameters)o; + + if (isPomExecution != that.isPomExecution) { + return false; + } + if (myResolveToWorkspace != that.myResolveToWorkspace) { + return false; + } + if (!myGoals.equals(that.myGoals)) { + return false; + } + if (myWorkingDirPath != null ? !myWorkingDirPath.equals(that.myWorkingDirPath) : that.myWorkingDirPath != null) { + return false; + } + if (!myProfilesMap.equals(that.myProfilesMap)) { + return false; + } + + return true; + } + + public int hashCode() { + int result; + result = isPomExecution ? 1 : 0; + result = 31 * result + (myWorkingDirPath != null ? myWorkingDirPath.hashCode() : 0); + result = 31 * result + myGoals.hashCode(); + result = 31 * result + myProfilesMap.hashCode(); + return result; + } } diff --git a/plugin/src/main/java/org/jetbrains/idea/maven/execution/MavenRunnerParametersPanel.java b/plugin/src/main/java/org/jetbrains/idea/maven/execution/MavenRunnerParametersPanel.java index 97fb7670..74808c91 100644 --- a/plugin/src/main/java/org/jetbrains/idea/maven/execution/MavenRunnerParametersPanel.java +++ b/plugin/src/main/java/org/jetbrains/idea/maven/execution/MavenRunnerParametersPanel.java @@ -49,168 +49,157 @@ /** * @author Vladislav.Kaznacheev */ -public class MavenRunnerParametersPanel -{ - private EditorTextField myGoalsEditor; - private EditorTextField myProfilesEditor; - private JCheckBox myResolveToWorkspaceCheckBox; - - private FileChooserTextBoxBuilder.Controller myWorkingDirectory; - private FormBuilder myFormBuilder = FormBuilder.createFormBuilder(); - - @RequiredUIAccess - public MavenRunnerParametersPanel(@Nonnull final Project project) - { - FileChooserTextBoxBuilder workDirBuilder = FileChooserTextBoxBuilder.create(project); - workDirBuilder.dialogTitle(RunnerBundle.message("maven.select.maven.project.file")); - workDirBuilder.fileChooserDescriptor(new FileChooserDescriptor(false, true, false, false, false, false) - { - @RequiredUIAccess - @Override - public boolean isFileSelectable(VirtualFile file) - { - if(!super.isFileSelectable(file)) - { - return false; - } - return file.findChild(MavenConstants.POM_XML) != null; - } - }); - - myWorkingDirectory = workDirBuilder.build(); - - JComponent workTextField = (JComponent) TargetAWT.to(myWorkingDirectory.getComponent()); - if(workTextField instanceof JTextField) - { - // TODO [VISTALL] dirty hack with old UI form builder which change filling by cols option - ((JTextField) workTextField).setColumns(0); - } - myFormBuilder.addLabeledComponent("Working directory", workTextField); - - if(!project.isDefault()) - { - TextFieldCompletionProvider profilesCompletionProvider = new TextFieldCompletionProvider(true) - { - @Override - public final void addCompletionVariants(@Nonnull String text, int offset, @Nonnull String prefix, @Nonnull CompletionResultSet result) - { - MavenProjectsManager manager = MavenProjectsManager.getInstance(project); - for(String profile : manager.getAvailableProfiles()) - { - result.addElement(LookupElementBuilder.create(ParametersListUtil.join(profile))); - } - } - - @Nonnull - @Override - public String getPrefix(@Nonnull String currentTextPrefix) - { - ParametersListLexer lexer = new ParametersListLexer(currentTextPrefix); - while(lexer.nextToken()) - { - if(lexer.getTokenEnd() == currentTextPrefix.length()) - { - String prefix = lexer.getCurrentToken(); - if(prefix.startsWith("-") || prefix.startsWith("!")) - { - prefix = prefix.substring(1); - } - return prefix; - } - } - - return ""; - } - }; - - myGoalsEditor = new MavenArgumentsCompletionProvider(project).createEditor(project); - myFormBuilder.addLabeledComponent("Command line", myGoalsEditor); - - myProfilesEditor = profilesCompletionProvider.createEditor(project); - myFormBuilder.addLabeledComponent("Profiles (separated with space)", myProfilesEditor); - JLabel label = new JBLabel("add prefix '-' to disable profile, e.g. '-test'"); - label.setFont(UIUtil.getLabelFont(UIUtil.FontSize.SMALL)); - label.setForeground(JBColor.GRAY); - - myFormBuilder.addComponentToRightColumn(label); - } - - myResolveToWorkspaceCheckBox = new JBCheckBox("Resolve Workspace artifacts"); - myResolveToWorkspaceCheckBox.setToolTipText("In case of multi-project workspace, dependencies will be looked for in the workspace first, and only after that in local repository."); - - myFormBuilder.addComponent(myResolveToWorkspaceCheckBox); - - myWorkingDirectory.getComponent().addFirstExtension(new TextBoxWithExtensions.Extension(false, MavenIconGroup.mavenlogotransparent(), MavenIconGroup.mavenlogo(), clickEvent -> { - MavenSelectProjectPopup.buildPopup(MavenProjectsManager.getInstance(project), mavenProject -> { - myWorkingDirectory.setValue(mavenProject.getDirectory()); - }).show(new RelativePoint(MouseInfo.getPointerInfo().getLocation())); - })); - } - - @Nonnull - public JComponent createComponent() - { - return myFormBuilder.getPanel(); - } - - public void disposeUIResources() - { - } - - public String getDisplayName() - { - return RunnerBundle.message("maven.runner.parameters.title"); - } - - protected void setData(final MavenRunnerParameters data) - { - data.setWorkingDirPath(myWorkingDirectory.getValue()); - data.setGoals(ParametersListUtil.parse(myGoalsEditor.getText())); - data.setResolveToWorkspace(myResolveToWorkspaceCheckBox.isSelected()); - - Map profilesMap = new LinkedHashMap<>(); - - List profiles = ParametersListUtil.parse(myProfilesEditor.getText()); - - for(String profile : profiles) - { - Boolean isEnabled = true; - if(profile.startsWith("-") || profile.startsWith("!")) - { - profile = profile.substring(1); - if(profile.isEmpty()) - { - continue; - } - - isEnabled = false; - } - - profilesMap.put(profile, isEnabled); - } - data.setProfilesMap(profilesMap); - } - - protected void getData(final MavenRunnerParameters data) - { - myWorkingDirectory.setValue(data.getWorkingDirPath()); - myGoalsEditor.setText(ParametersList.join(data.getGoals())); - myResolveToWorkspaceCheckBox.setSelected(data.isResolveToWorkspace()); - - ParametersList parametersList = new ParametersList(); - - for(Map.Entry entry : data.getProfilesMap().entrySet()) - { - String profileName = entry.getKey(); - - if(!entry.getValue()) - { - profileName = '-' + profileName; - } - - parametersList.add(profileName); - } - - myProfilesEditor.setText(parametersList.getParametersString()); - } +public class MavenRunnerParametersPanel { + private EditorTextField myGoalsEditor; + private EditorTextField myProfilesEditor; + private JCheckBox myResolveToWorkspaceCheckBox; + + private FileChooserTextBoxBuilder.Controller myWorkingDirectory; + private FormBuilder myFormBuilder = FormBuilder.createFormBuilder(); + + @RequiredUIAccess + public MavenRunnerParametersPanel(@Nonnull final Project project) { + FileChooserTextBoxBuilder workDirBuilder = FileChooserTextBoxBuilder.create(project); + workDirBuilder.dialogTitle(RunnerBundle.message("maven.select.maven.project.file")); + workDirBuilder.fileChooserDescriptor(new FileChooserDescriptor(false, true, false, false, false, false) { + @RequiredUIAccess + @Override + public boolean isFileSelectable(VirtualFile file) { + if (!super.isFileSelectable(file)) { + return false; + } + return file.findChild(MavenConstants.POM_XML) != null; + } + }); + + myWorkingDirectory = workDirBuilder.build(); + + JComponent workTextField = (JComponent)TargetAWT.to(myWorkingDirectory.getComponent()); + if (workTextField instanceof JTextField) { + // TODO [VISTALL] dirty hack with old UI form builder which change filling by cols option + ((JTextField)workTextField).setColumns(0); + } + myFormBuilder.addLabeledComponent("Working directory", workTextField); + + if (!project.isDefault()) { + TextFieldCompletionProvider profilesCompletionProvider = new TextFieldCompletionProvider(true) { + @Override + public final void addCompletionVariants( + @Nonnull String text, + int offset, + @Nonnull String prefix, + @Nonnull CompletionResultSet result + ) { + MavenProjectsManager manager = MavenProjectsManager.getInstance(project); + for (String profile : manager.getAvailableProfiles()) { + result.addElement(LookupElementBuilder.create(ParametersListUtil.join(profile))); + } + } + + @Nonnull + @Override + public String getPrefix(@Nonnull String currentTextPrefix) { + ParametersListLexer lexer = new ParametersListLexer(currentTextPrefix); + while (lexer.nextToken()) { + if (lexer.getTokenEnd() == currentTextPrefix.length()) { + String prefix = lexer.getCurrentToken(); + if (prefix.startsWith("-") || prefix.startsWith("!")) { + prefix = prefix.substring(1); + } + return prefix; + } + } + + return ""; + } + }; + + myGoalsEditor = new MavenArgumentsCompletionProvider(project).createEditor(project); + myFormBuilder.addLabeledComponent("Command line", myGoalsEditor); + + myProfilesEditor = profilesCompletionProvider.createEditor(project); + myFormBuilder.addLabeledComponent("Profiles (separated with space)", myProfilesEditor); + JLabel label = new JBLabel("add prefix '-' to disable profile, e.g. '-test'"); + label.setFont(UIUtil.getLabelFont(UIUtil.FontSize.SMALL)); + label.setForeground(JBColor.GRAY); + + myFormBuilder.addComponentToRightColumn(label); + } + + myResolveToWorkspaceCheckBox = new JBCheckBox("Resolve Workspace artifacts"); + myResolveToWorkspaceCheckBox.setToolTipText( + "In case of multi-project workspace, dependencies will be looked for in the workspace first, " + + "and only after that in local repository." + ); + + myFormBuilder.addComponent(myResolveToWorkspaceCheckBox); + + myWorkingDirectory.getComponent() + .addFirstExtension(new TextBoxWithExtensions.Extension(false, + MavenIconGroup.mavenlogotransparent(), + MavenIconGroup.mavenlogo(), + clickEvent -> { + MavenSelectProjectPopup.buildPopup(MavenProjectsManager.getInstance(project), mavenProject -> { + myWorkingDirectory.setValue(mavenProject.getDirectory()); + }).show(new RelativePoint(MouseInfo.getPointerInfo().getLocation())); + } + )); + } + + @Nonnull + public JComponent createComponent() { + return myFormBuilder.getPanel(); + } + + public void disposeUIResources() { + } + + public String getDisplayName() { + return RunnerBundle.message("maven.runner.parameters.title"); + } + + protected void setData(final MavenRunnerParameters data) { + data.setWorkingDirPath(myWorkingDirectory.getValue()); + data.setGoals(ParametersListUtil.parse(myGoalsEditor.getText())); + data.setResolveToWorkspace(myResolveToWorkspaceCheckBox.isSelected()); + + Map profilesMap = new LinkedHashMap<>(); + + List profiles = ParametersListUtil.parse(myProfilesEditor.getText()); + + for (String profile : profiles) { + Boolean isEnabled = true; + if (profile.startsWith("-") || profile.startsWith("!")) { + profile = profile.substring(1); + if (profile.isEmpty()) { + continue; + } + + isEnabled = false; + } + + profilesMap.put(profile, isEnabled); + } + data.setProfilesMap(profilesMap); + } + + protected void getData(final MavenRunnerParameters data) { + myWorkingDirectory.setValue(data.getWorkingDirPath()); + myGoalsEditor.setText(ParametersList.join(data.getGoals())); + myResolveToWorkspaceCheckBox.setSelected(data.isResolveToWorkspace()); + + ParametersList parametersList = new ParametersList(); + + for (Map.Entry entry : data.getProfilesMap().entrySet()) { + String profileName = entry.getKey(); + + if (!entry.getValue()) { + profileName = '-' + profileName; + } + + parametersList.add(profileName); + } + + myProfilesEditor.setText(parametersList.getParametersString()); + } } diff --git a/plugin/src/main/java/org/jetbrains/idea/maven/execution/MavenRunnerParametersSettingEditor.java b/plugin/src/main/java/org/jetbrains/idea/maven/execution/MavenRunnerParametersSettingEditor.java index e668c7ef..a21ada3c 100644 --- a/plugin/src/main/java/org/jetbrains/idea/maven/execution/MavenRunnerParametersSettingEditor.java +++ b/plugin/src/main/java/org/jetbrains/idea/maven/execution/MavenRunnerParametersSettingEditor.java @@ -13,46 +13,39 @@ /** * @author Sergey Evdokimov */ -public class MavenRunnerParametersSettingEditor extends SettingsEditor -{ - private final MavenRunnerParametersPanel myPanel; - private BorderLayoutPanel myVerticalPanel; - - @RequiredUIAccess - public MavenRunnerParametersSettingEditor(@Nonnull Project project) - { - myPanel = new MavenRunnerParametersPanel(project); - } - - @Override - protected void resetEditorFrom(MavenRunConfiguration runConfiguration) - { - myPanel.getData(runConfiguration.getRunnerParameters()); - } - - @Override - protected void applyEditorTo(MavenRunConfiguration runConfiguration) throws ConfigurationException - { - myPanel.setData(runConfiguration.getRunnerParameters()); - } - - @Nonnull - @Override - protected JComponent createEditor() - { - if(myVerticalPanel != null) - { - return myVerticalPanel; - } - myVerticalPanel = new BorderLayoutPanel(); - myVerticalPanel.setBorder(JBUI.Borders.empty(5, 0, 0, 0)); - myVerticalPanel.addToTop(myPanel.createComponent()); - return myVerticalPanel; - } - - @Override - protected void disposeEditor() - { - myPanel.disposeUIResources(); - } +public class MavenRunnerParametersSettingEditor extends SettingsEditor { + private final MavenRunnerParametersPanel myPanel; + private BorderLayoutPanel myVerticalPanel; + + @RequiredUIAccess + public MavenRunnerParametersSettingEditor(@Nonnull Project project) { + myPanel = new MavenRunnerParametersPanel(project); + } + + @Override + protected void resetEditorFrom(MavenRunConfiguration runConfiguration) { + myPanel.getData(runConfiguration.getRunnerParameters()); + } + + @Override + protected void applyEditorTo(MavenRunConfiguration runConfiguration) throws ConfigurationException { + myPanel.setData(runConfiguration.getRunnerParameters()); + } + + @Nonnull + @Override + protected JComponent createEditor() { + if (myVerticalPanel != null) { + return myVerticalPanel; + } + myVerticalPanel = new BorderLayoutPanel(); + myVerticalPanel.setBorder(JBUI.Borders.empty(5, 0, 0, 0)); + myVerticalPanel.addToTop(myPanel.createComponent()); + return myVerticalPanel; + } + + @Override + protected void disposeEditor() { + myPanel.disposeUIResources(); + } } diff --git a/plugin/src/main/java/org/jetbrains/idea/maven/execution/MavenRunnerSettings.java b/plugin/src/main/java/org/jetbrains/idea/maven/execution/MavenRunnerSettings.java index 443a2b51..52f10d56 100644 --- a/plugin/src/main/java/org/jetbrains/idea/maven/execution/MavenRunnerSettings.java +++ b/plugin/src/main/java/org/jetbrains/idea/maven/execution/MavenRunnerSettings.java @@ -24,212 +24,173 @@ import javax.annotation.Nullable; import java.util.*; -public class MavenRunnerSettings implements Cloneable -{ - private boolean runMavenInBackground = true; - @Nullable - private String jreName; - @Nonnull - private String vmOptions = ""; - private boolean skipTests = false; - private Map mavenProperties = new LinkedHashMap<>(); - - private Map environmentProperties = new HashMap<>(); - private boolean passParentEnv = true; - - private List myListeners = Lists.newLockFreeCopyOnWriteList(); - - public boolean isRunMavenInBackground() - { - return runMavenInBackground; - } - - public void setRunMavenInBackground(boolean runMavenInBackground) - { - this.runMavenInBackground = runMavenInBackground; - } - - @Nullable - public String getJreName() - { - return jreName; - } - - public void setJreName(@Nullable String jreName) - { - this.jreName = jreName; - } - - @Nonnull - public String getVmOptions() - { - return vmOptions; - } - - public void setVmOptions(@Nullable String vmOptions) - { - if(vmOptions != null) - { - this.vmOptions = vmOptions; - } - } - - public boolean isSkipTests() - { - return skipTests; - } - - public void setSkipTests(boolean skipTests) - { - if(skipTests != this.skipTests) - { - fireSkipTestsChanged(); - } - this.skipTests = skipTests; - } - - public Map getMavenProperties() - { - return this.mavenProperties; - } - - @SuppressWarnings({"UnusedDeclaration"}) - public void setMavenProperties(Map mavenProperties) - { - this.mavenProperties = mavenProperties; - } - - @Nonnull - public Map getEnvironmentProperties() - { - return environmentProperties; - } - - public void setEnvironmentProperties(@Nonnull Map envs) - { - if(envs == environmentProperties) - { - return; - } - - environmentProperties.clear(); - environmentProperties.putAll(envs); - } - - public boolean isPassParentEnv() - { - return passParentEnv; - } - - public void setPassParentEnv(boolean passParentEnv) - { - this.passParentEnv = passParentEnv; - } - - public void addListener(Listener l) - { - myListeners.add(l); - } - - public void removeListener(Listener l) - { - myListeners.remove(l); - } - - private void fireSkipTestsChanged() - { - for(Listener each : myListeners) - { - each.skipTestsChanged(); - } - } - - public interface Listener - { - void skipTestsChanged(); - } - - public boolean equals(final Object o) - { - if(this == o) - { - return true; - } - if(o == null || getClass() != o.getClass()) - { - return false; - } - - final MavenRunnerSettings that = (MavenRunnerSettings) o; - - if(runMavenInBackground != that.runMavenInBackground) - { - return false; - } - if(skipTests != that.skipTests) - { - return false; - } - if(!Objects.equals(jreName, that.jreName)) - { - return false; - } - if(mavenProperties != null ? !mavenProperties.equals(that.mavenProperties) : that.mavenProperties != null) - { - return false; - } - if(!vmOptions.equals(that.vmOptions)) - { - return false; - } - if(!environmentProperties.equals(that.environmentProperties)) - { - return false; - } - if(passParentEnv != that.passParentEnv) - { - return false; - } - - return true; - } - - public int hashCode() - { - int result; - result = (runMavenInBackground ? 1 : 0); - result = 31 * result + jreName.hashCode(); - result = 31 * result + vmOptions.hashCode(); - result = 31 * result + (skipTests ? 1 : 0); - result = 31 * result + environmentProperties.hashCode(); - result = 31 * result + (mavenProperties != null ? mavenProperties.hashCode() : 0); - return result; - } - - @Override - public MavenRunnerSettings clone() - { - try - { - final MavenRunnerSettings clone = (MavenRunnerSettings) super.clone(); - clone.mavenProperties = cloneMap(mavenProperties); - clone.myListeners = Lists.newLockFreeCopyOnWriteList(); - clone.environmentProperties = new HashMap<>(environmentProperties); - return clone; - } - catch(CloneNotSupportedException e) - { - throw new Error(e); - } - } - - private static Map cloneMap(final Map source) - { - final Map clone = new LinkedHashMap<>(); - for(Map.Entry entry : source.entrySet()) - { - clone.put(entry.getKey(), entry.getValue()); - } - return clone; - } +public class MavenRunnerSettings implements Cloneable { + private boolean runMavenInBackground = true; + @Nullable + private String jreName; + @Nonnull + private String vmOptions = ""; + private boolean skipTests = false; + private Map mavenProperties = new LinkedHashMap<>(); + + private Map environmentProperties = new HashMap<>(); + private boolean passParentEnv = true; + + private List myListeners = Lists.newLockFreeCopyOnWriteList(); + + public boolean isRunMavenInBackground() { + return runMavenInBackground; + } + + public void setRunMavenInBackground(boolean runMavenInBackground) { + this.runMavenInBackground = runMavenInBackground; + } + + @Nullable + public String getJreName() { + return jreName; + } + + public void setJreName(@Nullable String jreName) { + this.jreName = jreName; + } + + @Nonnull + public String getVmOptions() { + return vmOptions; + } + + public void setVmOptions(@Nullable String vmOptions) { + if (vmOptions != null) { + this.vmOptions = vmOptions; + } + } + + public boolean isSkipTests() { + return skipTests; + } + + public void setSkipTests(boolean skipTests) { + if (skipTests != this.skipTests) { + fireSkipTestsChanged(); + } + this.skipTests = skipTests; + } + + public Map getMavenProperties() { + return this.mavenProperties; + } + + @SuppressWarnings({"UnusedDeclaration"}) + public void setMavenProperties(Map mavenProperties) { + this.mavenProperties = mavenProperties; + } + + @Nonnull + public Map getEnvironmentProperties() { + return environmentProperties; + } + + public void setEnvironmentProperties(@Nonnull Map envs) { + if (envs == environmentProperties) { + return; + } + + environmentProperties.clear(); + environmentProperties.putAll(envs); + } + + public boolean isPassParentEnv() { + return passParentEnv; + } + + public void setPassParentEnv(boolean passParentEnv) { + this.passParentEnv = passParentEnv; + } + + public void addListener(Listener l) { + myListeners.add(l); + } + + public void removeListener(Listener l) { + myListeners.remove(l); + } + + private void fireSkipTestsChanged() { + for (Listener each : myListeners) { + each.skipTestsChanged(); + } + } + + public interface Listener { + void skipTestsChanged(); + } + + public boolean equals(final Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + + final MavenRunnerSettings that = (MavenRunnerSettings)o; + + if (runMavenInBackground != that.runMavenInBackground) { + return false; + } + if (skipTests != that.skipTests) { + return false; + } + if (!Objects.equals(jreName, that.jreName)) { + return false; + } + if (mavenProperties != null ? !mavenProperties.equals(that.mavenProperties) : that.mavenProperties != null) { + return false; + } + if (!vmOptions.equals(that.vmOptions)) { + return false; + } + if (!environmentProperties.equals(that.environmentProperties)) { + return false; + } + if (passParentEnv != that.passParentEnv) { + return false; + } + + return true; + } + + public int hashCode() { + int result; + result = (runMavenInBackground ? 1 : 0); + result = 31 * result + jreName.hashCode(); + result = 31 * result + vmOptions.hashCode(); + result = 31 * result + (skipTests ? 1 : 0); + result = 31 * result + environmentProperties.hashCode(); + result = 31 * result + (mavenProperties != null ? mavenProperties.hashCode() : 0); + return result; + } + + @Override + public MavenRunnerSettings clone() { + try { + final MavenRunnerSettings clone = (MavenRunnerSettings)super.clone(); + clone.mavenProperties = cloneMap(mavenProperties); + clone.myListeners = Lists.newLockFreeCopyOnWriteList(); + clone.environmentProperties = new HashMap<>(environmentProperties); + return clone; + } + catch (CloneNotSupportedException e) { + throw new Error(e); + } + } + + private static Map cloneMap(final Map source) { + final Map clone = new LinkedHashMap<>(); + for (Map.Entry entry : source.entrySet()) { + clone.put(entry.getKey(), entry.getValue()); + } + return clone; + } } diff --git a/plugin/src/main/java/org/jetbrains/idea/maven/execution/MavenRunnerSettingsEditor.java b/plugin/src/main/java/org/jetbrains/idea/maven/execution/MavenRunnerSettingsEditor.java index 7e317f32..5b6d9bfe 100644 --- a/plugin/src/main/java/org/jetbrains/idea/maven/execution/MavenRunnerSettingsEditor.java +++ b/plugin/src/main/java/org/jetbrains/idea/maven/execution/MavenRunnerSettingsEditor.java @@ -28,51 +28,51 @@ * @author Sergey Evdokimov */ public class MavenRunnerSettingsEditor extends SettingsEditor { + private final MavenRunnerPanel myPanel; - private final MavenRunnerPanel myPanel; + private JCheckBox myUseProjectSettings; - private JCheckBox myUseProjectSettings; - - public MavenRunnerSettingsEditor(@Nonnull Project project) { - myPanel = new MavenRunnerPanel(project, true); - } + public MavenRunnerSettingsEditor(@Nonnull Project project) { + myPanel = new MavenRunnerPanel(project, true); + } - @Override - protected void resetEditorFrom(MavenRunConfiguration runConfiguration) { - myUseProjectSettings.setSelected(runConfiguration.getRunnerSettings() == null); + @Override + protected void resetEditorFrom(MavenRunConfiguration runConfiguration) { + myUseProjectSettings.setSelected(runConfiguration.getRunnerSettings() == null); - if (runConfiguration.getRunnerSettings() == null) { - MavenRunnerSettings settings = MavenRunner.getInstance(myPanel.getProject()).getSettings(); - myPanel.reset(settings); - } - else { - myPanel.reset(runConfiguration.getRunnerSettings()); + if (runConfiguration.getRunnerSettings() == null) { + MavenRunnerSettings settings = MavenRunner.getInstance(myPanel.getProject()).getSettings(); + myPanel.reset(settings); + } + else { + myPanel.reset(runConfiguration.getRunnerSettings()); + } } - } - @Override - protected void applyEditorTo(MavenRunConfiguration runConfiguration) throws ConfigurationException { - if (myUseProjectSettings.isSelected()) { - runConfiguration.setRunnerSettings(null); + @Override + protected void applyEditorTo(MavenRunConfiguration runConfiguration) throws ConfigurationException { + if (myUseProjectSettings.isSelected()) { + runConfiguration.setRunnerSettings(null); + } + else { + if (runConfiguration.getRunnerSettings() != null) { + myPanel.apply(runConfiguration.getRunnerSettings()); + } + else { + MavenRunnerSettings settings = MavenRunner.getInstance(myPanel.getProject()).getSettings().clone(); + myPanel.apply(settings); + runConfiguration.setRunnerSettings(settings); + } + } } - else { - if (runConfiguration.getRunnerSettings() != null) { - myPanel.apply(runConfiguration.getRunnerSettings()); - } - else { - MavenRunnerSettings settings = MavenRunner.getInstance(myPanel.getProject()).getSettings().clone(); - myPanel.apply(settings); - runConfiguration.setRunnerSettings(settings); - } - } - } - @Nonnull - @Override - protected JComponent createEditor() { - Pair pair = MavenDisablePanelCheckbox.createPanel(myPanel.createComponent(this), "Use project settings"); + @Nonnull + @Override + protected JComponent createEditor() { + Pair pair = + MavenDisablePanelCheckbox.createPanel(myPanel.createComponent(this), "Use project settings"); - myUseProjectSettings = pair.second; - return pair.first; - } + myUseProjectSettings = pair.second; + return pair.first; + } } diff --git a/plugin/src/main/java/org/jetbrains/idea/maven/execution/MavenSelectProjectPopup.java b/plugin/src/main/java/org/jetbrains/idea/maven/execution/MavenSelectProjectPopup.java index 4b827c0a..16c8155b 100644 --- a/plugin/src/main/java/org/jetbrains/idea/maven/execution/MavenSelectProjectPopup.java +++ b/plugin/src/main/java/org/jetbrains/idea/maven/execution/MavenSelectProjectPopup.java @@ -45,175 +45,158 @@ /** * @author Sergey Evdokimov */ -public class MavenSelectProjectPopup -{ - public static void attachToWorkingDirectoryField(@Nonnull final MavenProjectsManager projectsManager, - final JTextField workingDirectoryField, - final JButton showModulesButton, - @Nullable final JComponent focusAfterSelection) - { - attachToButton(projectsManager, showModulesButton, project -> - { - workingDirectoryField.setText(project.getDirectory()); - - if(focusAfterSelection != null) - { - ApplicationManager.getApplication().invokeLater(() -> - { - if(workingDirectoryField.hasFocus()) - { - focusAfterSelection.requestFocus(); - } - }); - } - }); - - workingDirectoryField.addKeyListener(new KeyAdapter() - { - @Override - public void keyPressed(KeyEvent e) - { - if(e.getKeyCode() == KeyEvent.VK_DOWN) - { - e.consume(); - showModulesButton.doClick(); - } - } - }); - } - - public static void attachToButton(@Nonnull final MavenProjectsManager projectsManager, - @Nonnull final JButton button, - @Nonnull final Consumer callback) - { - button.addActionListener(e -> buildPopup(projectsManager, callback).showUnderneathOf(button)); - } - - @Nonnull - public static JBPopup buildPopup(MavenProjectsManager projectsManager, @Nonnull final Consumer callback) - { - List projectList = projectsManager.getProjects(); - if(projectList.isEmpty()) - { - return JBPopupFactory.getInstance().createMessage("Maven projects not found"); - } - - DefaultMutableTreeNode root = buildTree(projectsManager, projectList); - - final Map projectsNameMap = MavenProjectNamer.generateNameMap(projectList); - - final Tree projectTree = new Tree(root); - projectTree.setRootVisible(false); - projectTree.setCellRenderer(new NodeRenderer() - { - @RequiredUIAccess - @Override - public void customizeCellRenderer(@Nonnull JTree tree, - Object value, - boolean selected, - boolean expanded, - boolean leaf, - int row, - boolean hasFocus) - { - if(value instanceof DefaultMutableTreeNode) - { - MavenProject mavenProject = (MavenProject) ((DefaultMutableTreeNode) value).getUserObject(); - value = projectsNameMap.get(mavenProject); - setIcon(MavenIcons.MavenProject); - } - - super.customizeCellRenderer(tree, value, selected, expanded, leaf, row, hasFocus); - } - }); - - new TreeSpeedSearch(projectTree, o -> - { - Object lastPathComponent = o.getLastPathComponent(); - if(!(lastPathComponent instanceof DefaultMutableTreeNode)) - { - return null; - } - - Object userObject = ((DefaultMutableTreeNode) lastPathComponent).getUserObject(); - - //noinspection SuspiciousMethodCalls - return projectsNameMap.get(userObject); - }); - - final SimpleReference popupRef = SimpleReference.create(); - - Runnable clickCallBack = new Runnable() - { - @Override - public void run() - { - TreePath path = projectTree.getSelectionPath(); - if(path == null) - { - return; - } - - Object lastPathComponent = path.getLastPathComponent(); - if(!(lastPathComponent instanceof DefaultMutableTreeNode)) - { - return; - } - - Object object = ((DefaultMutableTreeNode) lastPathComponent).getUserObject(); - if(object == null) - { - return; // may be it's the root - } - - callback.accept((MavenProject) object); - - popupRef.get().closeOk(null); - } - }; - - JBPopup popup = new PopupChooserBuilder(projectTree) - .setTitle("Select maven project") - .setResizable(true) - .setItemChoosenCallback(clickCallBack).setAutoselectOnMouseMove(true) - .setCloseOnEnter(false) - .createPopup(); - - popupRef.set(popup); - - return popup; - } - - private static DefaultMutableTreeNode buildTree(MavenProjectsManager projectsManager, List projectList) - { - MavenProject[] projects = projectList.toArray(new MavenProject[projectList.size()]); - Arrays.sort(projects, new MavenProjectNamer.MavenProjectComparator()); - - Map projectsToNode = new HashMap<>(); - for(MavenProject mavenProject : projects) - { - projectsToNode.put(mavenProject, new DefaultMutableTreeNode(mavenProject)); - } - - DefaultMutableTreeNode root = new DefaultMutableTreeNode(); - - for(MavenProject mavenProject : projects) - { - DefaultMutableTreeNode parent; - - MavenProject aggregator = projectsManager.findAggregator(mavenProject); - if(aggregator != null) - { - parent = projectsToNode.get(aggregator); - } - else - { - parent = root; - } - - parent.add(projectsToNode.get(mavenProject)); - } - - return root; - } +public class MavenSelectProjectPopup { + public static void attachToWorkingDirectoryField( + @Nonnull final MavenProjectsManager projectsManager, + final JTextField workingDirectoryField, + final JButton showModulesButton, + @Nullable final JComponent focusAfterSelection + ) { + attachToButton( + projectsManager, + showModulesButton, + project -> { + workingDirectoryField.setText(project.getDirectory()); + + if (focusAfterSelection != null) { + ApplicationManager.getApplication().invokeLater(() -> { + if (workingDirectoryField.hasFocus()) { + focusAfterSelection.requestFocus(); + } + }); + } + } + ); + + workingDirectoryField.addKeyListener(new KeyAdapter() { + @Override + public void keyPressed(KeyEvent e) { + if (e.getKeyCode() == KeyEvent.VK_DOWN) { + e.consume(); + showModulesButton.doClick(); + } + } + }); + } + + public static void attachToButton( + @Nonnull final MavenProjectsManager projectsManager, + @Nonnull final JButton button, + @Nonnull final Consumer callback + ) { + button.addActionListener(e -> buildPopup(projectsManager, callback).showUnderneathOf(button)); + } + + @Nonnull + public static JBPopup buildPopup(MavenProjectsManager projectsManager, @Nonnull final Consumer callback) { + List projectList = projectsManager.getProjects(); + if (projectList.isEmpty()) { + return JBPopupFactory.getInstance().createMessage("Maven projects not found"); + } + + DefaultMutableTreeNode root = buildTree(projectsManager, projectList); + + final Map projectsNameMap = MavenProjectNamer.generateNameMap(projectList); + + final Tree projectTree = new Tree(root); + projectTree.setRootVisible(false); + projectTree.setCellRenderer(new NodeRenderer() { + @RequiredUIAccess + @Override + public void customizeCellRenderer( + @Nonnull JTree tree, + Object value, + boolean selected, + boolean expanded, + boolean leaf, + int row, + boolean hasFocus + ) { + if (value instanceof DefaultMutableTreeNode) { + MavenProject mavenProject = (MavenProject)((DefaultMutableTreeNode)value).getUserObject(); + value = projectsNameMap.get(mavenProject); + setIcon(MavenIcons.MavenProject); + } + + super.customizeCellRenderer(tree, value, selected, expanded, leaf, row, hasFocus); + } + }); + + new TreeSpeedSearch( + projectTree, + o -> { + Object lastPathComponent = o.getLastPathComponent(); + if (!(lastPathComponent instanceof DefaultMutableTreeNode)) { + return null; + } + + Object userObject = ((DefaultMutableTreeNode)lastPathComponent).getUserObject(); + + //noinspection SuspiciousMethodCalls + return projectsNameMap.get(userObject); + } + ); + + final SimpleReference popupRef = SimpleReference.create(); + + Runnable clickCallBack = () -> { + TreePath path = projectTree.getSelectionPath(); + if (path == null) { + return; + } + + Object lastPathComponent = path.getLastPathComponent(); + if (!(lastPathComponent instanceof DefaultMutableTreeNode)) { + return; + } + + Object object = ((DefaultMutableTreeNode)lastPathComponent).getUserObject(); + if (object == null) { + return; // may be it's the root + } + + callback.accept((MavenProject)object); + + popupRef.get().closeOk(null); + }; + + JBPopup popup = new PopupChooserBuilder(projectTree) + .setTitle("Select maven project") + .setResizable(true) + .setItemChoosenCallback(clickCallBack).setAutoselectOnMouseMove(true) + .setCloseOnEnter(false) + .createPopup(); + + popupRef.set(popup); + + return popup; + } + + private static DefaultMutableTreeNode buildTree(MavenProjectsManager projectsManager, List projectList) { + MavenProject[] projects = projectList.toArray(new MavenProject[projectList.size()]); + Arrays.sort(projects, new MavenProjectNamer.MavenProjectComparator()); + + Map projectsToNode = new HashMap<>(); + for (MavenProject mavenProject : projects) { + projectsToNode.put(mavenProject, new DefaultMutableTreeNode(mavenProject)); + } + + DefaultMutableTreeNode root = new DefaultMutableTreeNode(); + + for (MavenProject mavenProject : projects) { + DefaultMutableTreeNode parent; + + MavenProject aggregator = projectsManager.findAggregator(mavenProject); + if (aggregator != null) { + parent = projectsToNode.get(aggregator); + } + else { + parent = root; + } + + parent.add(projectsToNode.get(mavenProject)); + } + + return root; + } } diff --git a/plugin/src/main/java/org/jetbrains/idea/maven/execution/RunnerBundle.java b/plugin/src/main/java/org/jetbrains/idea/maven/execution/RunnerBundle.java index 31b8d8b5..9548a2c0 100644 --- a/plugin/src/main/java/org/jetbrains/idea/maven/execution/RunnerBundle.java +++ b/plugin/src/main/java/org/jetbrains/idea/maven/execution/RunnerBundle.java @@ -24,25 +24,27 @@ import java.util.ResourceBundle; public class RunnerBundle { - private static Reference ourBundle; + private static Reference ourBundle; - @NonNls - private static final String BUNDLE = "RunnerBundle"; + @NonNls + private static final String BUNDLE = "RunnerBundle"; - private RunnerBundle() { - } + private RunnerBundle() { + } - public static String message(@PropertyKey(resourceBundle = BUNDLE) String key, Object... params) { - return CommonBundle.message(getBundle(), key, params); - } + public static String message(@PropertyKey(resourceBundle = BUNDLE) String key, Object... params) { + return CommonBundle.message(getBundle(), key, params); + } - private static ResourceBundle getBundle() { - ResourceBundle bundle = null; - if (ourBundle != null) bundle = ourBundle.get(); - if (bundle == null) { - bundle = ResourceBundle.getBundle(BUNDLE); - ourBundle = new SoftReference(bundle); + private static ResourceBundle getBundle() { + ResourceBundle bundle = null; + if (ourBundle != null) { + bundle = ourBundle.get(); + } + if (bundle == null) { + bundle = ResourceBundle.getBundle(BUNDLE); + ourBundle = new SoftReference<>(bundle); + } + return bundle; } - return bundle; - } } diff --git a/plugin/src/main/java/org/jetbrains/idea/maven/execution/SoutMavenConsole.java b/plugin/src/main/java/org/jetbrains/idea/maven/execution/SoutMavenConsole.java index a43f9126..0d7b4a3d 100644 --- a/plugin/src/main/java/org/jetbrains/idea/maven/execution/SoutMavenConsole.java +++ b/plugin/src/main/java/org/jetbrains/idea/maven/execution/SoutMavenConsole.java @@ -21,59 +21,46 @@ import consulo.util.dataholder.Key; import org.jetbrains.idea.maven.project.MavenConsole; -import java.util.function.BiPredicate; +public class SoutMavenConsole extends MavenConsole { + public SoutMavenConsole() { + super(MavenExecutionOptions.LoggingLevel.DEBUG, true); + } -public class SoutMavenConsole extends MavenConsole -{ - public SoutMavenConsole() - { - super(MavenExecutionOptions.LoggingLevel.DEBUG, true); - } + @Override + public boolean canPause() { + return false; + } - @Override - public boolean canPause() - { - return false; - } + @Override + public boolean isOutputPaused() { + return false; + } - @Override - public boolean isOutputPaused() - { - return false; - } + @Override + public void setOutputPaused(boolean outputPaused) { + } - @Override - public void setOutputPaused(boolean outputPaused) - { - } + @Override + public void attachToProcess(ProcessHandler processHandler) { + processHandler.addProcessListener(new ProcessAdapter() { + @Override + public void onTextAvailable(ProcessEvent event, Key outputType) { + if (isSuppressed(event.getText())) { + return; + } - @Override - public void attachToProcess(ProcessHandler processHandler) - { - processHandler.addProcessListener(new ProcessAdapter() - { - @Override - public void onTextAvailable(ProcessEvent event, Key outputType) - { - if(isSuppressed(event.getText())) - { - return; - } + System.out.print(event.getText()); + } - System.out.print(event.getText()); - } + @Override + public void processTerminated(ProcessEvent event) { + System.out.println("PROCESS TERMINATED: " + event.getExitCode()); + } + }); + } - @Override - public void processTerminated(ProcessEvent event) - { - System.out.println("PROCESS TERMINATED: " + event.getExitCode()); - } - }); - } - - @Override - protected void doPrint(String text, OutputType type) - { - System.out.print(text); - } + @Override + protected void doPrint(String text, OutputType type) { + System.out.print(text); + } } diff --git a/plugin/src/main/java/org/jetbrains/idea/maven/execution/cmd/CommandLineCompletionProvider.java b/plugin/src/main/java/org/jetbrains/idea/maven/execution/cmd/CommandLineCompletionProvider.java index 0afabf46..ffa97763 100644 --- a/plugin/src/main/java/org/jetbrains/idea/maven/execution/cmd/CommandLineCompletionProvider.java +++ b/plugin/src/main/java/org/jetbrains/idea/maven/execution/cmd/CommandLineCompletionProvider.java @@ -16,102 +16,100 @@ * @author Sergey Evdokimov */ public abstract class CommandLineCompletionProvider extends TextFieldCompletionProvider { + private final Options myOptions; - private final Options myOptions; + public CommandLineCompletionProvider(Options options) { + super(true); - public CommandLineCompletionProvider(Options options) { - super(true); + myOptions = options; + } - myOptions = options; - } + @Nonnull + @Override + public String getPrefix(@Nonnull String currentTextPrefix) { + ParametersListLexer lexer = new ParametersListLexer(currentTextPrefix); + while (lexer.nextToken()) { + if (lexer.getTokenEnd() == currentTextPrefix.length()) { + return lexer.getCurrentToken(); + } + } - @Nonnull - @Override - public String getPrefix(@Nonnull String currentTextPrefix) { - ParametersListLexer lexer = new ParametersListLexer(currentTextPrefix); - while (lexer.nextToken()) { - if (lexer.getTokenEnd() == currentTextPrefix.length()) { - return lexer.getCurrentToken(); - } + return ""; } - return ""; - } + protected LookupElement createLookupElement(@Nonnull Option option, @Nonnull String text) { + LookupElementBuilder res = LookupElementBuilder.create(text); - protected LookupElement createLookupElement(@Nonnull Option option, @Nonnull String text) { - LookupElementBuilder res = LookupElementBuilder.create(text); + if (option.getDescription() != null) { + return TailTypeDecorator.withTail(res.withTypeText(option.getDescription(), true), TailType.INSERT_SPACE); + } - if (option.getDescription() != null) { - return TailTypeDecorator.withTail(res.withTypeText(option.getDescription(), true), TailType.INSERT_SPACE); + return res; } - return res; - } + protected abstract void addArgumentVariants(@Nonnull CompletionResultSet result); - protected abstract void addArgumentVariants(@Nonnull CompletionResultSet result); + @Override + public void addCompletionVariants(@Nonnull String text, int offset, @Nonnull String prefix, @Nonnull CompletionResultSet result) { + ParametersListLexer lexer = new ParametersListLexer(text); - @Override - public void addCompletionVariants(@Nonnull String text, int offset, @Nonnull String prefix, @Nonnull CompletionResultSet result) { - ParametersListLexer lexer = new ParametersListLexer(text); + int argCount = 0; - int argCount = 0; + while (lexer.nextToken()) { + if (offset < lexer.getTokenStart()) { + break; + } - while (lexer.nextToken()) { - if (offset < lexer.getTokenStart()) { - break; - } + if (offset <= lexer.getTokenEnd()) { + if (argCount == 0) { + if (prefix.startsWith("--")) { + for (Option option : myOptions.getOptions()) { + if (option.getLongOpt() != null) { + result.addElement(createLookupElement(option, "--" + option.getLongOpt())); + } + } + } + else if (prefix.startsWith("-")) { + for (Option option : myOptions.getOptions()) { + if (option.getOpt() != null) { + result.addElement(createLookupElement(option, "-" + option.getOpt())); + } + } + } + else { + addArgumentVariants(result); + } + } + + return; + } - if (offset <= lexer.getTokenEnd()) { - if (argCount == 0) { - if (prefix.startsWith("--")) { - for (Option option : (Collection