diff --git a/plugin/src/main/java/org/jetbrains/idea/maven/MavenIcons.java b/plugin/src/main/java/org/jetbrains/idea/maven/MavenIcons.java index 5ad40be0..238f5271 100644 --- a/plugin/src/main/java/org/jetbrains/idea/maven/MavenIcons.java +++ b/plugin/src/main/java/org/jetbrains/idea/maven/MavenIcons.java @@ -7,18 +7,17 @@ @Deprecated @DeprecationInfo("Use MavenIconGroup") -public class MavenIcons -{ - public static final Image ChildrenProjects = MavenIconGroup.childrenprojects(); - public static final Image MavenLogo = MavenIconGroup.mavenlogo(); - public static final Image MavenPlugin = MavenIconGroup.mavenplugin(); - // TODO [VISTALL] use file icon - public static final Image MavenProject = MavenLogo; // 16x16 - public static final Image ModulesClosed = MavenIconGroup.modulesclosed(); - public static final Image ParentProject = MavenIconGroup.parentproject(); - public static final Image PhasesClosed = AllIcons.Nodes.ConfigFolder; // 16x16 - public static final Image PluginGoal = MavenIconGroup.plugingoal(); - public static final Image ProfilesClosed = MavenIconGroup.profilesclosed(); - public static final Image ToolWindowMaven = MavenIconGroup.toolwindowmaven(); - public static final Image UpdateFolders = MavenIconGroup.updatefolders(); +public class MavenIcons { + public static final Image ChildrenProjects = MavenIconGroup.childrenprojects(); + public static final Image MavenLogo = MavenIconGroup.mavenlogo(); + public static final Image MavenPlugin = MavenIconGroup.mavenplugin(); + // TODO [VISTALL] use file icon + public static final Image MavenProject = MavenLogo; // 16x16 + public static final Image ModulesClosed = MavenIconGroup.modulesclosed(); + public static final Image ParentProject = MavenIconGroup.parentproject(); + public static final Image PhasesClosed = AllIcons.Nodes.ConfigFolder; // 16x16 + public static final Image PluginGoal = MavenIconGroup.plugingoal(); + public static final Image ProfilesClosed = MavenIconGroup.profilesclosed(); + public static final Image ToolWindowMaven = MavenIconGroup.toolwindowmaven(); + public static final Image UpdateFolders = MavenIconGroup.updatefolders(); } diff --git a/plugin/src/main/java/org/jetbrains/idea/maven/dom/annotator/MavenDomGutterAnnotatorFactory.java b/plugin/src/main/java/org/jetbrains/idea/maven/dom/annotator/MavenDomGutterAnnotatorFactory.java index b9931330..b5eb58fc 100644 --- a/plugin/src/main/java/org/jetbrains/idea/maven/dom/annotator/MavenDomGutterAnnotatorFactory.java +++ b/plugin/src/main/java/org/jetbrains/idea/maven/dom/annotator/MavenDomGutterAnnotatorFactory.java @@ -11,7 +11,7 @@ /** * @author VISTALL - * @since 21/01/2023 + * @since 2023-01-21 */ @ExtensionImpl public class MavenDomGutterAnnotatorFactory implements AnnotatorFactory { diff --git a/plugin/src/main/java/org/jetbrains/idea/maven/dom/refactorings/extract/SelectMavenProjectDialog.java b/plugin/src/main/java/org/jetbrains/idea/maven/dom/refactorings/extract/SelectMavenProjectDialog.java index 1f6952bc..754a03ad 100644 --- a/plugin/src/main/java/org/jetbrains/idea/maven/dom/refactorings/extract/SelectMavenProjectDialog.java +++ b/plugin/src/main/java/org/jetbrains/idea/maven/dom/refactorings/extract/SelectMavenProjectDialog.java @@ -15,22 +15,22 @@ */ package org.jetbrains.idea.maven.dom.refactorings.extract; -import consulo.language.editor.refactoring.RefactoringBundle; +import consulo.language.editor.refactoring.localize.RefactoringLocalize; import consulo.project.Project; +import consulo.ui.annotation.RequiredUIAccess; import consulo.ui.ex.awt.DialogWrapper; import consulo.util.lang.Pair; import consulo.util.lang.StringUtil; -import org.jetbrains.idea.maven.dom.MavenDomBundle; import org.jetbrains.idea.maven.dom.MavenDomUtil; import org.jetbrains.idea.maven.dom.model.MavenDomDependency; import org.jetbrains.idea.maven.dom.model.MavenDomProjectModel; +import org.jetbrains.idea.maven.localize.MavenDomLocalize; import org.jetbrains.idea.maven.project.MavenProject; import org.jetbrains.idea.maven.utils.ComboBoxUtil; import javax.annotation.Nonnull; import javax.annotation.Nullable; import javax.swing.*; -import java.awt.event.ItemEvent; import java.awt.event.ItemListener; import java.util.Set; import java.util.function.Function; @@ -58,7 +58,7 @@ public SelectMavenProjectDialog( myMavenDomProjectModels = mavenDomProjectModels; myHasExclusions = hasExclusions; - setTitle(MavenDomBundle.message("choose.project")); + setTitle(MavenDomLocalize.chooseProject()); myOccurrencesCountFunction = funOccurrences; for (MavenDomProjectModel model : myMavenDomProjectModels) { @@ -72,6 +72,7 @@ public SelectMavenProjectDialog( } @Nonnull + @Override protected Action[] createActions() { return new Action[]{ getOKAction(), @@ -79,6 +80,7 @@ protected Action[] createActions() { }; } + @Override protected void init() { super.init(); @@ -106,6 +108,7 @@ public boolean isExtractExclusions() { return myExtractExclusions.isSelected(); } + @Override protected JComponent createCenterPanel() { ComboBoxUtil.setModel(myMavenProjectsComboBox, new DefaultComboBoxModel(), myMavenDomProjectModels, model -> { @@ -121,11 +124,7 @@ protected JComponent createCenterPanel() { } ); - myReplaceAllListener = new ItemListener() { - public void itemStateChanged(ItemEvent e) { - updateControls(); - } - }; + myReplaceAllListener = e -> updateControls(); myMavenProjectsComboBox.addItemListener(myReplaceAllListener); myMavenProjectsComboBox.setSelectedItem(0); @@ -140,7 +139,7 @@ public void itemStateChanged(ItemEvent e) { private void updateControls() { MavenDomProjectModel project = getSelectedProject(); Integer count = myOccurrencesCountFunction.apply(project).size(); - myReplaceAllCheckBox.setText(RefactoringBundle.message("replace.all.occurences", count)); + myReplaceAllCheckBox.setText(RefactoringLocalize.replaceAllOccurences(count).get()); myReplaceAllCheckBox.setEnabled(count != 0); } @@ -149,6 +148,8 @@ private void updateOkStatus() { setOKActionEnabled(getSelectedProject() != null); } + @Override + @RequiredUIAccess public JComponent getPreferredFocusedComponent() { return myMavenProjectsComboBox; } 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 ed75bd1b..9fc203f6 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 @@ -15,8 +15,8 @@ */ /* - * User: anna - * Date: 13-May-2010 + * @author anna + * @since 2010-05-13 */ package org.jetbrains.idea.maven.execution; diff --git a/plugin/src/main/java/org/jetbrains/idea/maven/model/impl/MavenIdBean.java b/plugin/src/main/java/org/jetbrains/idea/maven/model/impl/MavenIdBean.java index c576bd10..d2000afe 100644 --- a/plugin/src/main/java/org/jetbrains/idea/maven/model/impl/MavenIdBean.java +++ b/plugin/src/main/java/org/jetbrains/idea/maven/model/impl/MavenIdBean.java @@ -19,46 +19,52 @@ /** * @author Eugene Zhuravlev - * Date: 10/27/12 + * @since 2012-10-27 */ public class MavenIdBean { - @Tag("groupId") - public String groupId; + @Tag("groupId") + public String groupId; - @Tag("artifactId") - public String artifactId; + @Tag("artifactId") + public String artifactId; - @Tag("version") - public String version; + @Tag("version") + public String version; - public MavenIdBean() { - } + public MavenIdBean() { + } - public MavenIdBean(String groupId, String artifactId, String version) { - this.groupId = groupId; - this.artifactId = artifactId; - this.version = version; - } + public MavenIdBean(String groupId, String artifactId, String version) { + this.groupId = groupId; + this.artifactId = artifactId; + this.version = version; + } - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } - MavenIdBean bean = (MavenIdBean)o; + MavenIdBean bean = (MavenIdBean)o; - if (artifactId != null ? !artifactId.equals(bean.artifactId) : bean.artifactId != null) return false; - if (groupId != null ? !groupId.equals(bean.groupId) : bean.groupId != null) return false; - if (version != null ? !version.equals(bean.version) : bean.version != null) return false; + if (artifactId != null ? !artifactId.equals(bean.artifactId) : bean.artifactId != null) { + return false; + } + if (groupId != null ? !groupId.equals(bean.groupId) : bean.groupId != null) { + return false; + } + return version != null ? version.equals(bean.version) : bean.version == null; + } - return true; - } - - @Override - public int hashCode() { - int result = groupId != null ? groupId.hashCode() : 0; - result = 31 * result + (artifactId != null ? artifactId.hashCode() : 0); - result = 31 * result + (version != null ? version.hashCode() : 0); - return result; - } + @Override + public int hashCode() { + int result = groupId != null ? groupId.hashCode() : 0; + result = 31 * result + (artifactId != null ? artifactId.hashCode() : 0); + result = 31 * result + (version != null ? version.hashCode() : 0); + return result; + } } diff --git a/plugin/src/main/java/org/jetbrains/idea/maven/model/impl/MavenModuleResourceConfiguration.java b/plugin/src/main/java/org/jetbrains/idea/maven/model/impl/MavenModuleResourceConfiguration.java index 4712f5bc..58361131 100644 --- a/plugin/src/main/java/org/jetbrains/idea/maven/model/impl/MavenModuleResourceConfiguration.java +++ b/plugin/src/main/java/org/jetbrains/idea/maven/model/impl/MavenModuleResourceConfiguration.java @@ -28,81 +28,79 @@ /** * @author Eugene Zhuravlev - * Date: 10/20/12 + * @since 2012-10-20 */ public class MavenModuleResourceConfiguration { - @Nonnull - @Tag("id") - public MavenIdBean id; - - @Nullable - @Tag("parentId") - public MavenIdBean parentId; - - @Nonnull - @Tag("directory") - public String directory; - - @Nonnull - @Tag("delimiters-pattern") - public String delimitersPattern; - - @Tag("model-map") - @MapAnnotation(surroundWithTag = false, surroundKeyWithTag = false, surroundValueWithTag = false) - public Map modelMap = new HashMap(); - - @Tag("properties") - @MapAnnotation(surroundWithTag = false, surroundKeyWithTag = false, surroundValueWithTag = false) - public Map properties = new HashMap(); - - @Tag("filtering-excluded-extensions") - @AbstractCollection(surroundWithTag = false, elementTag = "extension") - public Set filteringExclusions = Sets.newHashSet(FileUtil.PATH_HASHING_STRATEGY); - - @OptionTag - public String escapeString = MavenProjectConfiguration.DEFAULT_ESCAPE_STRING; - - @OptionTag - public boolean escapeWindowsPaths = true; - - @Tag("resources") - @AbstractCollection(surroundWithTag = false, elementTag = "resource") - public List resources = new ArrayList(); - - @Tag("test-resources") - @AbstractCollection(surroundWithTag = false, elementTag = "resource") - public List testResources = new ArrayList(); - - - public Set getFilteringExcludedExtensions() { - if (filteringExclusions.isEmpty()) { - return MavenProjectConfiguration.DEFAULT_FILTERING_EXCLUDED_EXTENSIONS; - } - final Set result = Sets.newHashSet(FileUtil.PATH_HASHING_STRATEGY); - result.addAll(MavenProjectConfiguration.DEFAULT_FILTERING_EXCLUDED_EXTENSIONS); - result.addAll(filteringExclusions); - return Collections.unmodifiableSet(result); - } - - public int computeConfigurationHash(boolean forTestResources) { - int result = id.hashCode(); - result = 31 * result + (parentId != null ? parentId.hashCode() : 0); - result = 31 * result + directory.hashCode(); - result = 31 * result + delimitersPattern.hashCode(); - result = 31 * result + modelMap.hashCode(); - result = 31 * result + properties.hashCode(); - result = 31 * result + filteringExclusions.hashCode(); - result = 31 * result + (escapeString != null ? escapeString.hashCode() : 0); - result = 31 * result + (escapeWindowsPaths ? 1 : 0); - - final List _resources = forTestResources? testResources : resources; - result = 31 * result; - for (ResourceRootConfiguration resource : _resources) { - result += resource.computeConfigurationHash(); + @Nonnull + @Tag("id") + public MavenIdBean id; + + @Nullable + @Tag("parentId") + public MavenIdBean parentId; + + @Nonnull + @Tag("directory") + public String directory; + + @Nonnull + @Tag("delimiters-pattern") + public String delimitersPattern; + + @Tag("model-map") + @MapAnnotation(surroundWithTag = false, surroundKeyWithTag = false, surroundValueWithTag = false) + public Map modelMap = new HashMap<>(); + + @Tag("properties") + @MapAnnotation(surroundWithTag = false, surroundKeyWithTag = false, surroundValueWithTag = false) + public Map properties = new HashMap<>(); + + @Tag("filtering-excluded-extensions") + @AbstractCollection(surroundWithTag = false, elementTag = "extension") + public Set filteringExclusions = Sets.newHashSet(FileUtil.PATH_HASHING_STRATEGY); + + @OptionTag + public String escapeString = MavenProjectConfiguration.DEFAULT_ESCAPE_STRING; + + @OptionTag + public boolean escapeWindowsPaths = true; + + @Tag("resources") + @AbstractCollection(surroundWithTag = false, elementTag = "resource") + public List resources = new ArrayList<>(); + + @Tag("test-resources") + @AbstractCollection(surroundWithTag = false, elementTag = "resource") + public List testResources = new ArrayList<>(); + + public Set getFilteringExcludedExtensions() { + if (filteringExclusions.isEmpty()) { + return MavenProjectConfiguration.DEFAULT_FILTERING_EXCLUDED_EXTENSIONS; + } + final Set result = Sets.newHashSet(FileUtil.PATH_HASHING_STRATEGY); + result.addAll(MavenProjectConfiguration.DEFAULT_FILTERING_EXCLUDED_EXTENSIONS); + result.addAll(filteringExclusions); + return Collections.unmodifiableSet(result); } - return result; - } + public int computeConfigurationHash(boolean forTestResources) { + int result = id.hashCode(); + result = 31 * result + (parentId != null ? parentId.hashCode() : 0); + result = 31 * result + directory.hashCode(); + result = 31 * result + delimitersPattern.hashCode(); + result = 31 * result + modelMap.hashCode(); + result = 31 * result + properties.hashCode(); + result = 31 * result + filteringExclusions.hashCode(); + result = 31 * result + (escapeString != null ? escapeString.hashCode() : 0); + result = 31 * result + (escapeWindowsPaths ? 1 : 0); + + final List _resources = forTestResources ? testResources : resources; + result = 31 * result; + for (ResourceRootConfiguration resource : _resources) { + result += resource.computeConfigurationHash(); + } + return result; + } } diff --git a/plugin/src/main/java/org/jetbrains/idea/maven/model/impl/MavenProjectConfiguration.java b/plugin/src/main/java/org/jetbrains/idea/maven/model/impl/MavenProjectConfiguration.java index 0c44f119..31695dce 100644 --- a/plugin/src/main/java/org/jetbrains/idea/maven/model/impl/MavenProjectConfiguration.java +++ b/plugin/src/main/java/org/jetbrains/idea/maven/model/impl/MavenProjectConfiguration.java @@ -31,167 +31,179 @@ /** * @author Eugene Zhuravlev - * Date: 10/24/12 + * @since 2012-10-24 */ public class MavenProjectConfiguration { - public static final String CONFIGURATION_FILE_RELATIVE_PATH = "maven/configuration.xml"; - public static final String DEFAULT_ESCAPE_STRING = "\\"; - private static final Pattern PROPERTY_PATTERN = Pattern.compile("-D(\\S+?)=(.+)"); - public static final Set DEFAULT_FILTERING_EXCLUDED_EXTENSIONS; - static { - final Set set = Sets.newHashSet(FileUtil.PATH_HASHING_STRATEGY); - set.addAll(Arrays.asList("jpg", "jpeg", "gif", "bmp", "png")); - DEFAULT_FILTERING_EXCLUDED_EXTENSIONS = Collections.unmodifiableSet(set); - } - - @Tag("resource-processing") - @MapAnnotation(surroundWithTag = false, surroundKeyWithTag = false, surroundValueWithTag = false, entryTagName = "maven-module", keyAttributeName = "name") - public Map moduleConfigurations = new HashMap(); - - @Nullable - public MavenModuleResourceConfiguration findProject(MavenIdBean id) { - return getModuleConfigurationMap().get(id); - } - - @Transient - private volatile Map myIdToModuleMap; - - @Nonnull - private Map getModuleConfigurationMap() { - Map map = myIdToModuleMap; - if (map == null) { - map = new HashMap(); - for (MavenModuleResourceConfiguration configuration : moduleConfigurations.values()) { - if (configuration != null) { - map.put(configuration.id, configuration); - } - } - myIdToModuleMap = map; + public static final String CONFIGURATION_FILE_RELATIVE_PATH = "maven/configuration.xml"; + public static final String DEFAULT_ESCAPE_STRING = "\\"; + private static final Pattern PROPERTY_PATTERN = Pattern.compile("-D(\\S+?)=(.+)"); + public static final Set DEFAULT_FILTERING_EXCLUDED_EXTENSIONS; + + static { + final Set set = Sets.newHashSet(FileUtil.PATH_HASHING_STRATEGY); + set.addAll(Arrays.asList("jpg", "jpeg", "gif", "bmp", "png")); + DEFAULT_FILTERING_EXCLUDED_EXTENSIONS = Collections.unmodifiableSet(set); } - return map; - } - - @Nullable - public String resolveProperty(final String propName, final MavenModuleResourceConfiguration moduleConfig, Map additionalProperties) { - boolean hasPrefix = false; - String unprefixed = propName; - if (propName.startsWith("pom.")) { - unprefixed = propName.substring("pom.".length()); - hasPrefix = true; + @Tag("resource-processing") + @MapAnnotation( + surroundWithTag = false, + surroundKeyWithTag = false, + surroundValueWithTag = false, + entryTagName = "maven-module", + keyAttributeName = "name" + ) + public Map moduleConfigurations = new HashMap<>(); + + @Nullable + public MavenModuleResourceConfiguration findProject(MavenIdBean id) { + return getModuleConfigurationMap().get(id); } - else if (propName.startsWith("project.")) { - unprefixed = propName.substring("project.".length()); - hasPrefix = true; + + @Transient + private volatile Map myIdToModuleMap; + + @Nonnull + private Map getModuleConfigurationMap() { + Map map = myIdToModuleMap; + if (map == null) { + map = new HashMap<>(); + for (MavenModuleResourceConfiguration configuration : moduleConfigurations.values()) { + if (configuration != null) { + map.put(configuration.id, configuration); + } + } + myIdToModuleMap = map; + } + return map; } - MavenModuleResourceConfiguration selectedConfig = moduleConfig; + @Nullable + public String resolveProperty( + final String propName, + final MavenModuleResourceConfiguration moduleConfig, + Map additionalProperties + ) { + boolean hasPrefix = false; + String unprefixed = propName; + + if (propName.startsWith("pom.")) { + unprefixed = propName.substring("pom.".length()); + hasPrefix = true; + } + else if (propName.startsWith("project.")) { + unprefixed = propName.substring("project.".length()); + hasPrefix = true; + } - while (unprefixed.startsWith("parent.")) { - MavenIdBean parentId = selectedConfig.parentId; - if (parentId == null) { - return null; - } + MavenModuleResourceConfiguration selectedConfig = moduleConfig; - unprefixed = unprefixed.substring("parent.".length()); + while (unprefixed.startsWith("parent.")) { + MavenIdBean parentId = selectedConfig.parentId; + if (parentId == null) { + return null; + } - if (unprefixed.equals("groupId")) { - return parentId.groupId; - } - if (unprefixed.equals("artifactId")) { - return parentId.artifactId; - } + unprefixed = unprefixed.substring("parent.".length()); - selectedConfig = findProject(parentId); - if (selectedConfig == null) { - return null; - } - } + if (unprefixed.equals("groupId")) { + return parentId.groupId; + } + if (unprefixed.equals("artifactId")) { + return parentId.artifactId; + } - if (unprefixed.equals("basedir") || (hasPrefix && moduleConfig == selectedConfig && unprefixed.equals("baseUri"))) { - return selectedConfig.directory; - } + selectedConfig = findProject(parentId); + if (selectedConfig == null) { + return null; + } + } - String result; + if (unprefixed.equals("basedir") || (hasPrefix && moduleConfig == selectedConfig && unprefixed.equals("baseUri"))) { + return selectedConfig.directory; + } - result = getMavenOptsProperties().get(propName); - if (result != null) { - return result; - } + String result; - result = getSystemProperties().getProperty(propName); - if (result != null) { - return result; - } + result = getMavenOptsProperties().get(propName); + if (result != null) { + return result; + } - result = selectedConfig.modelMap.get(unprefixed); - if (result != null) { - return result; - } + result = getSystemProperties().getProperty(propName); + if (result != null) { + return result; + } - result = additionalProperties.get(propName); - if (result != null) { - return result; - } + result = selectedConfig.modelMap.get(unprefixed); + if (result != null) { + return result; + } - return moduleConfig.properties.get(propName); - } - - - private static volatile Map ourPropertiesFromMvnOpts; - @Nonnull - private static Map getMavenOptsProperties() { - Map res = ourPropertiesFromMvnOpts; - if (res == null) { - String mavenOpts = System.getenv("MAVEN_OPTS"); - if (mavenOpts != null) { - res = new HashMap(); - final String[] split = ParametersListUtil.parseToArray(mavenOpts); - for (String parameter : split) { - final Matcher matcher = PROPERTY_PATTERN.matcher(parameter); - if (matcher.matches()) { - res.put(matcher.group(1), matcher.group(2)); - } + result = additionalProperties.get(propName); + if (result != null) { + return result; } - } - else { - res = Collections.emptyMap(); - } - ourPropertiesFromMvnOpts = res; + return moduleConfig.properties.get(propName); } - return res; - } - - private static volatile Properties ourSystemProperties; - public static Properties getSystemProperties() { - Properties res = ourSystemProperties; - if (res == null) { - res = new Properties(); - res.putAll(System.getProperties()); - - for (Iterator itr = res.keySet().iterator(); itr.hasNext(); ) { - final String propertyName = itr.next().toString(); - if (propertyName.startsWith("idea.")) { - itr.remove(); + private static volatile Map ourPropertiesFromMvnOpts; + + @Nonnull + private static Map getMavenOptsProperties() { + Map res = ourPropertiesFromMvnOpts; + if (res == null) { + String mavenOpts = System.getenv("MAVEN_OPTS"); + if (mavenOpts != null) { + res = new HashMap<>(); + final String[] split = ParametersListUtil.parseToArray(mavenOpts); + for (String parameter : split) { + final Matcher matcher = PROPERTY_PATTERN.matcher(parameter); + if (matcher.matches()) { + res.put(matcher.group(1), matcher.group(2)); + } + } + } + else { + res = Collections.emptyMap(); + } + + ourPropertiesFromMvnOpts = res; } - } - for (Map.Entry entry : System.getenv().entrySet()) { - String key = entry.getKey(); - if (key.startsWith("=")) { - continue; - } - if (SystemInfo.isWindows) { - key = key.toUpperCase(); - } - res.setProperty("env." + key, entry.getValue()); - } + return res; + } - ourSystemProperties = res; + private static volatile Properties ourSystemProperties; + + public static Properties getSystemProperties() { + Properties res = ourSystemProperties; + if (res == null) { + res = new Properties(); + res.putAll(System.getProperties()); + + for (Iterator itr = res.keySet().iterator(); itr.hasNext(); ) { + final String propertyName = itr.next().toString(); + if (propertyName.startsWith("idea.")) { + itr.remove(); + } + } + + for (Map.Entry entry : System.getenv().entrySet()) { + String key = entry.getKey(); + if (key.startsWith("=")) { + continue; + } + if (SystemInfo.isWindows) { + key = key.toUpperCase(); + } + res.setProperty("env." + key, entry.getValue()); + } + + ourSystemProperties = res; + } + return res; } - return res; - } } diff --git a/plugin/src/main/java/org/jetbrains/idea/maven/model/impl/ResourceRootConfiguration.java b/plugin/src/main/java/org/jetbrains/idea/maven/model/impl/ResourceRootConfiguration.java index ba257471..c6ef8b3c 100644 --- a/plugin/src/main/java/org/jetbrains/idea/maven/model/impl/ResourceRootConfiguration.java +++ b/plugin/src/main/java/org/jetbrains/idea/maven/model/impl/ResourceRootConfiguration.java @@ -26,36 +26,35 @@ /** * @author Eugene Zhuravlev - * Date: 10/20/12 + * @since 2012-10-20 */ @Tag("resource") public class ResourceRootConfiguration { - @Tag("directory") - @Nonnull - public String directory; - - @Tag("targetPath") - @Nullable - public String targetPath; - - @Attribute("filtered") - public boolean isFiltered; - - @Tag("includes") - @AbstractCollection(surroundWithTag = false, elementTag = "pattern") - public Set includes = new HashSet(); - - @Tag("excludes") - @AbstractCollection(surroundWithTag = false, elementTag = "pattern") - public Set excludes = new HashSet(); - - - public int computeConfigurationHash() { - int result = directory.hashCode(); - result = 31 * result + (targetPath != null ? targetPath.hashCode() : 0); - result = 31 * result + (isFiltered ? 1 : 0); - //result = 31 * result + includes.hashCode(); - //result = 31 * result + excludes.hashCode(); - return result; - } + @Tag("directory") + @Nonnull + public String directory; + + @Tag("targetPath") + @Nullable + public String targetPath; + + @Attribute("filtered") + public boolean isFiltered; + + @Tag("includes") + @AbstractCollection(surroundWithTag = false, elementTag = "pattern") + public Set includes = new HashSet<>(); + + @Tag("excludes") + @AbstractCollection(surroundWithTag = false, elementTag = "pattern") + public Set excludes = new HashSet<>(); + + public int computeConfigurationHash() { + int result = directory.hashCode(); + result = 31 * result + (targetPath != null ? targetPath.hashCode() : 0); + result = 31 * result + (isFiltered ? 1 : 0); + //result = 31 * result + includes.hashCode(); + //result = 31 * result + excludes.hashCode(); + return result; + } } diff --git a/plugin/src/main/java/org/jetbrains/idea/maven/plugins/api/MavenCompletionReferenceProvider.java b/plugin/src/main/java/org/jetbrains/idea/maven/plugins/api/MavenCompletionReferenceProvider.java index faa7f6eb..d3b45b1c 100644 --- a/plugin/src/main/java/org/jetbrains/idea/maven/plugins/api/MavenCompletionReferenceProvider.java +++ b/plugin/src/main/java/org/jetbrains/idea/maven/plugins/api/MavenCompletionReferenceProvider.java @@ -1,8 +1,10 @@ package org.jetbrains.idea.maven.plugins.api; +import consulo.annotation.access.RequiredReadAction; import consulo.language.psi.PsiElement; import consulo.language.psi.PsiReference; import consulo.language.util.ProcessingContext; + import javax.annotation.Nonnull; import consulo.language.psi.PsiReferenceBase; @@ -13,25 +15,29 @@ */ public abstract class MavenCompletionReferenceProvider implements MavenParamReferenceProvider { - protected abstract Object[] getVariants(@Nonnull PsiReferenceBase reference); + protected abstract Object[] getVariants(@Nonnull PsiReferenceBase reference); - @Override - public PsiReference[] getReferencesByElement(@Nonnull PsiElement element, - @Nonnull MavenDomConfiguration domCfg, - @Nonnull ProcessingContext context) { - return new PsiReference[] { - new PsiReferenceBase(element, true) { - @Override - public PsiElement resolve() { - return null; - } + @Override + public PsiReference[] getReferencesByElement( + @Nonnull PsiElement element, + @Nonnull MavenDomConfiguration domCfg, + @Nonnull ProcessingContext context + ) { + return new PsiReference[]{ + new PsiReferenceBase<>(element, true) { + @Override + @RequiredReadAction + public PsiElement resolve() { + return null; + } - @Nonnull - @Override - public Object[] getVariants() { - return MavenCompletionReferenceProvider.this.getVariants(this); - } - } - }; - } + @Nonnull + @Override + @RequiredReadAction + public Object[] getVariants() { + return MavenCompletionReferenceProvider.this.getVariants(this); + } + } + }; + } } diff --git a/plugin/src/main/java/org/jetbrains/idea/maven/plugins/api/MavenFixedValueReferenceProvider.java b/plugin/src/main/java/org/jetbrains/idea/maven/plugins/api/MavenFixedValueReferenceProvider.java index 03a2a14c..db7bcd3b 100644 --- a/plugin/src/main/java/org/jetbrains/idea/maven/plugins/api/MavenFixedValueReferenceProvider.java +++ b/plugin/src/main/java/org/jetbrains/idea/maven/plugins/api/MavenFixedValueReferenceProvider.java @@ -1,5 +1,6 @@ package org.jetbrains.idea.maven.plugins.api; +import consulo.annotation.access.RequiredReadAction; import consulo.document.util.TextRange; import consulo.language.psi.*; import consulo.language.util.ProcessingContext; @@ -14,65 +15,60 @@ /** * @author Sergey Evdokimov */ -public class MavenFixedValueReferenceProvider implements MavenParamReferenceProvider, MavenSoftAwareReferenceProvider -{ - private final String[] myValues; +public class MavenFixedValueReferenceProvider implements MavenParamReferenceProvider, MavenSoftAwareReferenceProvider { + private final String[] myValues; - private boolean mySoft = false; + private boolean mySoft = false; - public MavenFixedValueReferenceProvider(String[] values) - { - myValues = values; - } + public MavenFixedValueReferenceProvider(String[] values) { + myValues = values; + } - @Override - public PsiReference[] getReferencesByElement(@Nonnull PsiElement element, - @Nonnull MavenDomConfiguration domCfg, - @Nonnull ProcessingContext context) - { - ElementManipulator manipulator = ElementManipulators.getManipulator(element); - TextRange range = manipulator.getRangeInElement(element); + @Override + @RequiredReadAction + public PsiReference[] getReferencesByElement( + @Nonnull PsiElement element, + @Nonnull MavenDomConfiguration domCfg, + @Nonnull ProcessingContext context + ) { + ElementManipulator manipulator = ElementManipulators.getManipulator(element); + TextRange range = manipulator.getRangeInElement(element); - String text = range.substring(element.getText()); - Matcher matcher = MavenPropertyResolver.PATTERN.matcher(text); - if(matcher.find()) - { - return PsiReference.EMPTY_ARRAY; - } + String text = range.substring(element.getText()); + Matcher matcher = MavenPropertyResolver.PATTERN.matcher(text); + if (matcher.find()) { + return PsiReference.EMPTY_ARRAY; + } - return new PsiReference[]{ - new PsiReferenceBase<>(element, mySoft) - { - @Nullable - @Override - public PsiElement resolve() - { - if(mySoft) - { - return null; - } + return new PsiReference[]{ + new PsiReferenceBase<>(element, mySoft) { + @Nullable + @Override + @RequiredReadAction + public PsiElement resolve() { + if (mySoft) { + return null; + } - if(Arrays.asList(myValues).contains(getValue())) - { - return getElement(); - } + if (Arrays.asList(myValues).contains(getValue())) { + return getElement(); + } - return null; - } + return null; + } - @Nonnull - @Override - public Object[] getVariants() - { - return myValues; - } - } - }; - } + @Nonnull + @Override + @RequiredReadAction + public Object[] getVariants() { + return myValues; + } + } + }; + } - @Override - public void setSoft(boolean soft) - { - mySoft = soft; - } + @Override + public void setSoft(boolean soft) { + mySoft = soft; + } } diff --git a/plugin/src/main/java/org/jetbrains/idea/maven/plugins/api/MavenModelPropertiesPatcher.java b/plugin/src/main/java/org/jetbrains/idea/maven/plugins/api/MavenModelPropertiesPatcher.java index 7d192358..0d36aa87 100644 --- a/plugin/src/main/java/org/jetbrains/idea/maven/plugins/api/MavenModelPropertiesPatcher.java +++ b/plugin/src/main/java/org/jetbrains/idea/maven/plugins/api/MavenModelPropertiesPatcher.java @@ -13,36 +13,29 @@ /** * @author Sergey Evdokimov */ -public class MavenModelPropertiesPatcher -{ - /* - * Add properties those should be added by plugins. - */ - public static void patch(Properties modelProperties, @Nullable Collection plugins) - { - if(plugins == null) - { - return; - } +public class MavenModelPropertiesPatcher { + /* + * Add properties those should be added by plugins. + */ + public static void patch(Properties modelProperties, @Nullable Collection plugins) { + if (plugins == null) { + return; + } - Map descriptors = MavenPluginDescriptorCache.getDescriptors(); + Map descriptors = MavenPluginDescriptorCache.getDescriptors(); - for(MavenPlugin plugin : plugins) - { - MavenPluginDescriptor descriptor = descriptors.get(new MavenId(plugin.getGroupId(), plugin.getArtifactId())); + for (MavenPlugin plugin : plugins) { + MavenPluginDescriptor descriptor = descriptors.get(new MavenId(plugin.getGroupId(), plugin.getArtifactId())); - if(descriptor == null) - { - continue; - } + if (descriptor == null) { + continue; + } - for(String property : descriptor.getProperties()) - { - if(!modelProperties.containsKey(property)) - { - modelProperties.setProperty(property, ""); - } - } - } - } + for (String property : descriptor.getProperties()) { + if (!modelProperties.containsKey(property)) { + modelProperties.setProperty(property, ""); + } + } + } + } } diff --git a/plugin/src/main/java/org/jetbrains/idea/maven/plugins/api/MavenParamLanguageProvider.java b/plugin/src/main/java/org/jetbrains/idea/maven/plugins/api/MavenParamLanguageProvider.java index 666aaab8..721a87d0 100644 --- a/plugin/src/main/java/org/jetbrains/idea/maven/plugins/api/MavenParamLanguageProvider.java +++ b/plugin/src/main/java/org/jetbrains/idea/maven/plugins/api/MavenParamLanguageProvider.java @@ -26,8 +26,7 @@ * @author Sergey Evdokimov */ @FunctionalInterface -public interface MavenParamLanguageProvider -{ - @Nullable - Language getLanguage(@Nonnull XmlText xmlText, @Nonnull MavenDomConfiguration configuration); +public interface MavenParamLanguageProvider { + @Nullable + Language getLanguage(@Nonnull XmlText xmlText, @Nonnull MavenDomConfiguration configuration); } diff --git a/plugin/src/main/java/org/jetbrains/idea/maven/plugins/api/MavenParamReferenceProvider.java b/plugin/src/main/java/org/jetbrains/idea/maven/plugins/api/MavenParamReferenceProvider.java index 4cad2b0a..2685dfe9 100644 --- a/plugin/src/main/java/org/jetbrains/idea/maven/plugins/api/MavenParamReferenceProvider.java +++ b/plugin/src/main/java/org/jetbrains/idea/maven/plugins/api/MavenParamReferenceProvider.java @@ -26,7 +26,9 @@ * @author Sergey Evdokimov */ public interface MavenParamReferenceProvider { - - PsiReference[] getReferencesByElement(@Nonnull PsiElement element, @Nonnull MavenDomConfiguration domCfg, @Nonnull ProcessingContext context); - + PsiReference[] getReferencesByElement( + @Nonnull PsiElement element, + @Nonnull MavenDomConfiguration domCfg, + @Nonnull ProcessingContext context + ); } diff --git a/plugin/src/main/java/org/jetbrains/idea/maven/plugins/api/MavenPluginConfigurationLanguageInjector.java b/plugin/src/main/java/org/jetbrains/idea/maven/plugins/api/MavenPluginConfigurationLanguageInjector.java index b337d41b..23424d07 100644 --- a/plugin/src/main/java/org/jetbrains/idea/maven/plugins/api/MavenPluginConfigurationLanguageInjector.java +++ b/plugin/src/main/java/org/jetbrains/idea/maven/plugins/api/MavenPluginConfigurationLanguageInjector.java @@ -15,6 +15,7 @@ */ package org.jetbrains.idea.maven.plugins.api; +import consulo.annotation.access.RequiredReadAction; import consulo.annotation.component.ExtensionImpl; import consulo.document.util.TextRange; import consulo.language.Language; @@ -29,42 +30,46 @@ * @author Sergey Evdokimov */ @ExtensionImpl -public final class MavenPluginConfigurationLanguageInjector implements LanguageInjector -{ - @Override - public void injectLanguages(@Nonnull final PsiLanguageInjectionHost host, @Nonnull final InjectedLanguagePlaces injectionPlacesRegistrar) - { - if(!(host instanceof XmlText)) - { - return; - } +public final class MavenPluginConfigurationLanguageInjector implements LanguageInjector { + @Override + @RequiredReadAction + public void injectLanguages( + @Nonnull final PsiLanguageInjectionHost host, + @Nonnull final InjectedLanguagePlaces injectionPlacesRegistrar + ) { + if (!(host instanceof XmlText)) { + return; + } - final XmlText xmlText = (XmlText) host; + final XmlText xmlText = (XmlText)host; - if(!MavenPluginParamInfo.isSimpleText(xmlText)) - { - return; - } + if (!MavenPluginParamInfo.isSimpleText(xmlText)) { + return; + } - MavenPluginParamInfo.processParamInfo(xmlText, (info, configuration) -> - { - Language language = info.getLanguage(); + MavenPluginParamInfo.processParamInfo( + xmlText, + (info, configuration) -> { + Language language = info.getLanguage(); - if(language == null) - { - MavenParamLanguageProvider provider = info.getLanguageProvider(); - if(provider != null) - { - language = provider.getLanguage(xmlText, configuration); - } - } + if (language == null) { + MavenParamLanguageProvider provider = info.getLanguageProvider(); + if (provider != null) { + language = provider.getLanguage(xmlText, configuration); + } + } - if(language != null) - { - injectionPlacesRegistrar.addPlace(language, TextRange.from(0, host.getTextLength()), info.getLanguageInjectionPrefix(), info.getLanguageInjectionSuffix()); - return false; - } - return true; - }); - } + if (language != null) { + injectionPlacesRegistrar.addPlace( + language, + TextRange.from(0, host.getTextLength()), + info.getLanguageInjectionPrefix(), + info.getLanguageInjectionSuffix() + ); + return false; + } + return true; + } + ); + } } diff --git a/plugin/src/main/java/org/jetbrains/idea/maven/plugins/api/MavenPluginParamInfo.java b/plugin/src/main/java/org/jetbrains/idea/maven/plugins/api/MavenPluginParamInfo.java index f7c286cf..a3329203 100644 --- a/plugin/src/main/java/org/jetbrains/idea/maven/plugins/api/MavenPluginParamInfo.java +++ b/plugin/src/main/java/org/jetbrains/idea/maven/plugins/api/MavenPluginParamInfo.java @@ -21,113 +21,94 @@ /** * @author Sergey Evdokimov */ -public class MavenPluginParamInfo -{ - @RequiredReadAction - public static boolean isSimpleText(@Nonnull XmlText paramValue) - { - PsiElement prevSibling = paramValue.getPrevSibling(); - if(!(prevSibling instanceof LeafPsiElement) || ((LeafPsiElement) prevSibling).getElementType() != XmlTokenType.XML_TAG_END) - { - return false; - } - - PsiElement nextSibling = paramValue.getNextSibling(); - if(!(nextSibling instanceof LeafPsiElement) || ((LeafPsiElement) nextSibling).getElementType() != XmlTokenType.XML_END_TAG_START) - { - return false; - } - - return true; - } - - public static void processParamInfo(@Nonnull XmlText paramValue, @Nonnull BiPredicate processor) - { - XmlTag paramTag = paramValue.getParentTag(); - if(paramTag == null) - { - return; - } - - XmlTag configurationTag = paramTag; - DomElement domElement; - - while(true) - { - configurationTag = configurationTag.getParentTag(); - if(configurationTag == null) - { - return; - } - - String tagName = configurationTag.getName(); - if("configuration".equals(tagName)) - { - domElement = DomManager.getDomManager(configurationTag.getProject()).getDomElement(configurationTag); - if(domElement instanceof MavenDomConfiguration) - { - break; - } - - if(domElement != null) - { - return; - } - } - } - - MavenDomConfiguration domCfg = (MavenDomConfiguration) domElement; - - MavenDomPlugin domPlugin = domCfg.getParentOfType(MavenDomPlugin.class, true); - if(domPlugin == null) - { - return; - } - - Map descriptors = MavenPluginDescriptorCache.getDescriptors(); - - String pluginGroupId = domPlugin.getGroupId().getStringValue(); - String pluginArtifactId = domPlugin.getArtifactId().getStringValue(); - - MavenPluginDescriptor descriptor; - - if(pluginGroupId == null) - { - descriptor = descriptors.get(new MavenId("org.apache.maven.plugins", pluginArtifactId)); - if(descriptor == null) - { - descriptor = descriptors.get(new MavenId("org.codehaus.mojo", pluginArtifactId)); - } - } - else - { - descriptor = descriptors.get(new MavenId(pluginGroupId, pluginArtifactId)); - } - - if(descriptor == null) - { - return; - } - - DomElement parent = domCfg.getParent(); - if(parent instanceof MavenDomPluginExecution) - { - MavenDomGoals goals = ((MavenDomPluginExecution) parent).getGoals(); - for(MavenDomGoal goal : goals.getGoals()) - { - MavenPluginDescriptorParam info = descriptor.getParam(goal.getStringValue()); - if(info != null && !processor.test(info, domCfg)) - { - return; - } - } - - MavenPluginDescriptorParam param = descriptor.getParam(paramTag.getName()); - if(param != null && !processor.test(param, domCfg)) - { - return; - } - } +public class MavenPluginParamInfo { + @RequiredReadAction + public static boolean isSimpleText(@Nonnull XmlText paramValue) { + PsiElement prevSibling = paramValue.getPrevSibling(); + if (!(prevSibling instanceof LeafPsiElement prevLeafPsiElement + && prevLeafPsiElement.getElementType() == XmlTokenType.XML_TAG_END)) { + return false; + } + + PsiElement nextSibling = paramValue.getNextSibling(); + return nextSibling instanceof LeafPsiElement nextLeafPsiElement + && nextLeafPsiElement.getElementType() == XmlTokenType.XML_END_TAG_START; + } + + public static void processParamInfo( + @Nonnull XmlText paramValue, + @Nonnull BiPredicate processor + ) { + XmlTag paramTag = paramValue.getParentTag(); + if (paramTag == null) { + return; + } + + XmlTag configurationTag = paramTag; + DomElement domElement; + + while (true) { + configurationTag = configurationTag.getParentTag(); + if (configurationTag == null) { + return; + } + + String tagName = configurationTag.getName(); + if ("configuration".equals(tagName)) { + domElement = DomManager.getDomManager(configurationTag.getProject()).getDomElement(configurationTag); + if (domElement instanceof MavenDomConfiguration) { + break; + } + + if (domElement != null) { + return; + } + } + } + + MavenDomConfiguration domCfg = (MavenDomConfiguration)domElement; + + MavenDomPlugin domPlugin = domCfg.getParentOfType(MavenDomPlugin.class, true); + if (domPlugin == null) { + return; + } + + Map descriptors = MavenPluginDescriptorCache.getDescriptors(); + + String pluginGroupId = domPlugin.getGroupId().getStringValue(); + String pluginArtifactId = domPlugin.getArtifactId().getStringValue(); + + MavenPluginDescriptor descriptor; + + if (pluginGroupId == null) { + descriptor = descriptors.get(new MavenId("org.apache.maven.plugins", pluginArtifactId)); + if (descriptor == null) { + descriptor = descriptors.get(new MavenId("org.codehaus.mojo", pluginArtifactId)); + } + } + else { + descriptor = descriptors.get(new MavenId(pluginGroupId, pluginArtifactId)); + } + + if (descriptor == null) { + return; + } + + DomElement parent = domCfg.getParent(); + if (parent instanceof MavenDomPluginExecution) { + MavenDomGoals goals = ((MavenDomPluginExecution)parent).getGoals(); + for (MavenDomGoal goal : goals.getGoals()) { + MavenPluginDescriptorParam info = descriptor.getParam(goal.getStringValue()); + if (info != null && !processor.test(info, domCfg)) { + return; + } + } + + MavenPluginDescriptorParam param = descriptor.getParam(paramTag.getName()); + if (param != null && !processor.test(param, domCfg)) { + return; + } + } // ParamInfo defaultInfo = goalsMap.get(null); // if(defaultInfo != null) @@ -137,5 +118,5 @@ public static void processParamInfo(@Nonnull XmlText paramValue, @Nonnull BiPred // return; // } // } - } + } } diff --git a/plugin/src/main/java/org/jetbrains/idea/maven/plugins/api/MavenPluginParamReferenceContributor.java b/plugin/src/main/java/org/jetbrains/idea/maven/plugins/api/MavenPluginParamReferenceContributor.java index b1c3854b..5bc9f7c4 100644 --- a/plugin/src/main/java/org/jetbrains/idea/maven/plugins/api/MavenPluginParamReferenceContributor.java +++ b/plugin/src/main/java/org/jetbrains/idea/maven/plugins/api/MavenPluginParamReferenceContributor.java @@ -15,6 +15,7 @@ */ package org.jetbrains.idea.maven.plugins.api; +import consulo.annotation.access.RequiredReadAction; import consulo.annotation.component.ExtensionImpl; import consulo.language.Language; import consulo.language.pattern.PlatformPatterns; @@ -34,67 +35,58 @@ * @author Sergey Evdokimov */ @ExtensionImpl -public class MavenPluginParamReferenceContributor extends PsiReferenceContributor -{ - @Override - public void registerReferenceProviders(PsiReferenceRegistrar registrar) - { - registrar.registerReferenceProvider( - PlatformPatterns.psiElement(XmlTokenType.XML_DATA_CHARACTERS).withParent( - XmlPatterns.xmlText().inFile(XmlPatterns.xmlFile().withName("pom.xml")) - ), - new MavenPluginParamRefProvider()); - } +public class MavenPluginParamReferenceContributor extends PsiReferenceContributor { + @Override + public void registerReferenceProviders(PsiReferenceRegistrar registrar) { + registrar.registerReferenceProvider( + PlatformPatterns.psiElement(XmlTokenType.XML_DATA_CHARACTERS).withParent( + XmlPatterns.xmlText().inFile(XmlPatterns.xmlFile().withName("pom.xml")) + ), + new MavenPluginParamRefProvider() + ); + } - private static class MavenPluginParamRefProvider extends PsiReferenceProvider - { + private static class MavenPluginParamRefProvider extends PsiReferenceProvider { + @Nonnull + @Override + @RequiredReadAction + public PsiReference[] getReferencesByElement(@Nonnull final PsiElement element, @Nonnull final ProcessingContext context) { + final XmlText xmlText = (XmlText)element.getParent(); - @Nonnull - @Override - public PsiReference[] getReferencesByElement(@Nonnull final PsiElement element, @Nonnull final ProcessingContext context) - { - final XmlText xmlText = (XmlText) element.getParent(); + if (!MavenPluginParamInfo.isSimpleText(xmlText)) { + return PsiReference.EMPTY_ARRAY; + } - if(!MavenPluginParamInfo.isSimpleText(xmlText)) - { - return PsiReference.EMPTY_ARRAY; - } + class MyProcessor implements BiPredicate { + PsiReference[] result; - class MyProcessor implements BiPredicate - { - PsiReference[] result; + @Override + public boolean test(MavenPluginDescriptorParam info, MavenDomConfiguration domCfg) { + MavenParamReferenceProvider providerInstance = info.getRefProvider(); + if (providerInstance != null) { + result = providerInstance.getReferencesByElement(xmlText, domCfg, context); + return false; + } - @Override - public boolean test(MavenPluginDescriptorParam info, MavenDomConfiguration domCfg) - { - MavenParamReferenceProvider providerInstance = info.getRefProvider(); - if(providerInstance != null) - { - result = providerInstance.getReferencesByElement(xmlText, domCfg, context); - return false; - } + return true; + } + } - return true; - } - } + MyProcessor processor = new MyProcessor(); - MyProcessor processor = new MyProcessor(); + MavenPluginParamInfo.processParamInfo(xmlText, processor); - MavenPluginParamInfo.processParamInfo(xmlText, processor); + if (processor.result != null) { + return processor.result; + } - if(processor.result != null) - { - return processor.result; - } + return PsiReference.EMPTY_ARRAY; + } + } - return PsiReference.EMPTY_ARRAY; - } - } - - @Nonnull - @Override - public Language getLanguage() - { - return XMLLanguage.INSTANCE; - } + @Nonnull + @Override + public Language getLanguage() { + return XMLLanguage.INSTANCE; + } } diff --git a/plugin/src/main/java/org/jetbrains/idea/maven/plugins/api/MavenSoftAwareReferenceProvider.java b/plugin/src/main/java/org/jetbrains/idea/maven/plugins/api/MavenSoftAwareReferenceProvider.java index bd2f6315..6476d87c 100644 --- a/plugin/src/main/java/org/jetbrains/idea/maven/plugins/api/MavenSoftAwareReferenceProvider.java +++ b/plugin/src/main/java/org/jetbrains/idea/maven/plugins/api/MavenSoftAwareReferenceProvider.java @@ -4,7 +4,5 @@ * @author Sergey Evdokimov */ public interface MavenSoftAwareReferenceProvider { - - void setSoft(boolean soft); - + void setSoft(boolean soft); } diff --git a/plugin/src/main/java/org/jetbrains/idea/maven/plugins/api/common/MavenCommonParamReferenceProviders.java b/plugin/src/main/java/org/jetbrains/idea/maven/plugins/api/common/MavenCommonParamReferenceProviders.java index 1c2e2509..8f6978f7 100644 --- a/plugin/src/main/java/org/jetbrains/idea/maven/plugins/api/common/MavenCommonParamReferenceProviders.java +++ b/plugin/src/main/java/org/jetbrains/idea/maven/plugins/api/common/MavenCommonParamReferenceProviders.java @@ -15,6 +15,7 @@ */ package org.jetbrains.idea.maven.plugins.api.common; +import consulo.annotation.access.RequiredReadAction; import consulo.language.editor.completion.lookup.LookupElement; import consulo.language.editor.completion.lookup.LookupElementBuilder; import consulo.language.psi.PsiElement; @@ -39,61 +40,65 @@ * @author Sergey Evdokimov */ public class MavenCommonParamReferenceProviders { + private MavenCommonParamReferenceProviders() { + } - private MavenCommonParamReferenceProviders() { - } - - public static class FilePath implements MavenParamReferenceProvider { - @Override - public PsiReference[] getReferencesByElement(@Nonnull PsiElement element, - @Nonnull MavenDomConfiguration domCfg, - @Nonnull ProcessingContext context) { - return MavenPathReferenceConverter.createReferences(domCfg, element, Condition.TRUE); + public static class FilePath implements MavenParamReferenceProvider { + @Override + @RequiredReadAction + public PsiReference[] getReferencesByElement( + @Nonnull PsiElement element, + @Nonnull MavenDomConfiguration domCfg, + @Nonnull ProcessingContext context + ) { + return MavenPathReferenceConverter.createReferences(domCfg, element, Condition.TRUE); + } } - } - public static class DirPath implements MavenParamReferenceProvider { - @Override - public PsiReference[] getReferencesByElement(@Nonnull PsiElement element, - @Nonnull MavenDomConfiguration domCfg, - @Nonnull ProcessingContext context) { - return MavenPathReferenceConverter.createReferences(domCfg, element, FileReferenceSet.DIRECTORY_FILTER); + public static class DirPath implements MavenParamReferenceProvider { + @Override + @RequiredReadAction + public PsiReference[] getReferencesByElement( + @Nonnull PsiElement element, + @Nonnull MavenDomConfiguration domCfg, + @Nonnull ProcessingContext context + ) { + return MavenPathReferenceConverter.createReferences(domCfg, element, FileReferenceSet.DIRECTORY_FILTER); + } } - } - public static class DependencyWithoutVersion extends MavenDependencyReferenceProvider { - public DependencyWithoutVersion() { - setCanHasVersion(false); + public static class DependencyWithoutVersion extends MavenDependencyReferenceProvider { + public DependencyWithoutVersion() { + setCanHasVersion(false); + } } - } - public static class Encoding extends MavenCompletionReferenceProvider { + public static class Encoding extends MavenCompletionReferenceProvider { - @Override - protected Object[] getVariants(@Nonnull PsiReferenceBase reference) { - Charset[] charsets = CharsetToolkit.getAvailableCharsets(); + @Override + protected Object[] getVariants(@Nonnull PsiReferenceBase reference) { + Charset[] charsets = CharsetToolkit.getAvailableCharsets(); - LookupElement[] res = new LookupElement[charsets.length]; - for (int i = 0; i < charsets.length; i++) { - res[i] = LookupElementBuilder.create(charsets[i].name()).withCaseSensitivity(false); - } + LookupElement[] res = new LookupElement[charsets.length]; + for (int i = 0; i < charsets.length; i++) { + res[i] = LookupElementBuilder.create(charsets[i].name()).withCaseSensitivity(false); + } - return res; + return res; + } } - } - public static class Goal extends MavenCompletionReferenceProvider { - @Override - protected Object[] getVariants(@Nonnull PsiReferenceBase reference) { - return MavenUtil.getPhaseVariants(MavenProjectsManager.getInstance(reference.getElement().getProject())).toArray(); + public static class Goal extends MavenCompletionReferenceProvider { + @Override + protected Object[] getVariants(@Nonnull PsiReferenceBase reference) { + return MavenUtil.getPhaseVariants(MavenProjectsManager.getInstance(reference.getElement().getProject())).toArray(); + } } - } - public static class Profile extends MavenCompletionReferenceProvider { - @Override - protected Object[] getVariants(@Nonnull PsiReferenceBase reference) { - return MavenProjectsManager.getInstance(reference.getElement().getProject()).getAvailableProfiles().toArray(); + public static class Profile extends MavenCompletionReferenceProvider { + @Override + protected Object[] getVariants(@Nonnull PsiReferenceBase reference) { + return MavenProjectsManager.getInstance(reference.getElement().getProject()).getAvailableProfiles().toArray(); + } } - } - } diff --git a/plugin/src/main/java/org/jetbrains/idea/maven/project/MavenConsole.java b/plugin/src/main/java/org/jetbrains/idea/maven/project/MavenConsole.java index a8114b62..07ff496c 100644 --- a/plugin/src/main/java/org/jetbrains/idea/maven/project/MavenConsole.java +++ b/plugin/src/main/java/org/jetbrains/idea/maven/project/MavenConsole.java @@ -17,10 +17,10 @@ import com.google.common.collect.BiMap; import com.google.common.collect.ImmutableBiMap; +import consulo.maven.rt.server.common.server.MavenServerConsole; import consulo.process.ProcessHandler; import org.jetbrains.idea.maven.execution.MavenExecutionOptions; -import org.jetbrains.idea.maven.execution.RunnerBundle; -import consulo.maven.rt.server.common.server.MavenServerConsole; +import org.jetbrains.idea.maven.localize.MavenRunnerLocalize; import java.text.MessageFormat; @@ -73,7 +73,7 @@ public void finish() { public abstract void attachToProcess(ProcessHandler processHandler); public void printException(Throwable throwable) { - systemMessage(MavenServerConsole.LEVEL_ERROR, RunnerBundle.message("embedded.build.failed"), throwable); + systemMessage(MavenServerConsole.LEVEL_ERROR, MavenRunnerLocalize.embeddedBuildFailed().get(), throwable); } public void systemMessage(int level, String string, Throwable throwable) { diff --git a/plugin/src/main/java/org/jetbrains/idea/maven/project/MavenProjectsManagerState.java b/plugin/src/main/java/org/jetbrains/idea/maven/project/MavenProjectsManagerState.java index de29bb0a..577ba949 100644 --- a/plugin/src/main/java/org/jetbrains/idea/maven/project/MavenProjectsManagerState.java +++ b/plugin/src/main/java/org/jetbrains/idea/maven/project/MavenProjectsManagerState.java @@ -15,10 +15,8 @@ */ /* - * Created by IntelliJ IDEA. * User: Vladislav.Kaznacheev - * Date: Jun 29, 2007 - * Time: 1:02:29 PM + * @since 2007-06-29 */ package org.jetbrains.idea.maven.project; diff --git a/plugin/src/main/java/org/jetbrains/idea/maven/server/MavenEmbedderWrapper.java b/plugin/src/main/java/org/jetbrains/idea/maven/server/MavenEmbedderWrapper.java index 29323ac9..216dae69 100644 --- a/plugin/src/main/java/org/jetbrains/idea/maven/server/MavenEmbedderWrapper.java +++ b/plugin/src/main/java/org/jetbrains/idea/maven/server/MavenEmbedderWrapper.java @@ -34,353 +34,308 @@ import java.util.Collections; import java.util.List; -public abstract class MavenEmbedderWrapper extends RemoteObjectWrapper -{ - private Customization myCustomization; - - public MavenEmbedderWrapper(@Nullable RemoteObjectWrapper parent) - { - super(parent); - } - - @Override - protected synchronized void onWrappeeCreated() throws RemoteException - { - super.onWrappeeCreated(); - if(myCustomization != null) - { - doCustomize(); - } - } - - public void customizeForResolve(MavenConsole console, MavenProgressIndicator indicator) - { - setCustomization(console, indicator, null, false, false); - perform(new Retriable() - { - @Override - public Object execute() throws RemoteException - { - doCustomize(); - return null; - } - }); - } - - public void customizeForResolve(MavenWorkspaceMap workspaceMap, MavenConsole console, MavenProgressIndicator indicator, boolean alwaysUpdateSnapshot) - { - setCustomization(console, indicator, workspaceMap, false, alwaysUpdateSnapshot); - perform(new Retriable() - { - @Override - public Object execute() throws RemoteException - { - doCustomize(); - return null; - } - }); - } - - public void customizeForStrictResolve(MavenWorkspaceMap workspaceMap, MavenConsole console, MavenProgressIndicator indicator) - { - setCustomization(console, indicator, workspaceMap, true, false); - perform(new Retriable() - { - @Override - public Object execute() throws RemoteException - { - doCustomize(); - return null; - } - }); - } - - public void customizeForGetVersions() - { - perform(new Retriable() - { - @Override - public Object execute() throws RemoteException - { - doCustomizeComponents(); - return null; - } - }); - } - - private synchronized void doCustomizeComponents() throws RemoteException - { - getOrCreateWrappee().customizeComponents(); - } - - private synchronized void doCustomize() throws RemoteException - { - getOrCreateWrappee().customize(myCustomization.workspaceMap, myCustomization.failOnUnresolvedDependency, myCustomization.console, myCustomization.indicator, - myCustomization.alwaysUpdateSnapshot); - } - - @Nonnull - public MavenServerExecutionResult resolveProject(@Nonnull final VirtualFile file, - @Nonnull final Collection activeProfiles, - @Nonnull final Collection inactiveProfiles) throws MavenProcessCanceledException - { - return perform(new RetriableCancelable() - { - @Override - public MavenServerExecutionResult execute() throws RemoteException, MavenServerProcessCanceledException - { - return getOrCreateWrappee().resolveProject(new File(file.getPath()), activeProfiles, inactiveProfiles); - } - }); - } - - @Nullable - public String evaluateEffectivePom(@Nonnull final VirtualFile file, - @Nonnull final Collection activeProfiles, - @Nonnull final Collection inactiveProfiles) throws MavenProcessCanceledException - { - return perform(new RetriableCancelable() - { - @Override - public String execute() throws RemoteException, MavenServerProcessCanceledException - { - return getOrCreateWrappee().evaluateEffectivePom(new File(file.getPath()), new ArrayList(activeProfiles), new ArrayList(inactiveProfiles)); - } - }); - } - - @Nonnull - public MavenArtifact resolve(@Nonnull final MavenArtifactInfo info, @Nonnull final List remoteRepositories) throws MavenProcessCanceledException - { - return perform(new RetriableCancelable() - { - @Override - public MavenArtifact execute() throws RemoteException, MavenServerProcessCanceledException - { - return getOrCreateWrappee().resolve(info, remoteRepositories); - } - }); - } - - @Nonnull - public List resolveTransitively(@Nonnull final List artifacts, @Nonnull final List remoteRepositories) throws - MavenProcessCanceledException - { - - return perform(new RetriableCancelable>() - { - @Override - public List execute() throws RemoteException, MavenServerProcessCanceledException - { - return getOrCreateWrappee().resolveTransitively(artifacts, remoteRepositories); - } - }); - } - - @Nonnull - public List retrieveVersions(@Nonnull final String groupId, - @Nonnull final String artifactId, - @Nonnull final List remoteRepositories) throws MavenProcessCanceledException - { - - return perform(new RetriableCancelable>() - { - @Override - public List execute() throws RemoteException, MavenServerProcessCanceledException - { - return getOrCreateWrappee().retrieveAvailableVersions(groupId, artifactId, remoteRepositories); - } - }); - } - - public Collection resolvePlugin(@Nonnull final MavenPlugin plugin, - @Nonnull final List repositories, - @Nonnull final NativeMavenProjectHolder nativeMavenProject, - final boolean transitive) throws MavenProcessCanceledException - { - int id; - try - { - id = nativeMavenProject.getId(); - } - catch(RemoteException e) - { - // do not call handleRemoteError here since this error occurred because of previous remote error - return Collections.emptyList(); - } - - try - { - return getOrCreateWrappee().resolvePlugin(plugin, repositories, id, transitive); - } - catch(RemoteException e) - { - // do not try to reconnect here since we have lost NativeMavenProjectHolder anyway. - handleRemoteError(e); - return Collections.emptyList(); - } - catch(MavenServerProcessCanceledException e) - { - throw new MavenProcessCanceledException(); - } - } - - @Nonnull - public MavenServerExecutionResult execute(@Nonnull final VirtualFile file, - @Nonnull final Collection activeProfiles, - @Nonnull final Collection inactiveProfiles, - @Nonnull final List goals) throws MavenProcessCanceledException - { - return perform(new RetriableCancelable() - { - @Override - public MavenServerExecutionResult execute() throws RemoteException, MavenServerProcessCanceledException - { - return getOrCreateWrappee().execute(new File(file.getPath()), activeProfiles, inactiveProfiles, goals, Collections.emptyList(), false, false); - } - }); - } - - @Nonnull - public MavenServerExecutionResult execute(@Nonnull final VirtualFile file, - @Nonnull final Collection activeProfiles, - @Nonnull final Collection inactiveProfiles, - @Nonnull final List goals, - @Nonnull final List selectedProjects, - final boolean alsoMake, - final boolean alsoMakeDependents) throws MavenProcessCanceledException - { - return perform(new RetriableCancelable() - { - @Override - public MavenServerExecutionResult execute() throws RemoteException, MavenServerProcessCanceledException - { - return getOrCreateWrappee().execute(new File(file.getPath()), activeProfiles, inactiveProfiles, goals, selectedProjects, alsoMake, alsoMakeDependents); - } - }); - } - - public void reset() - { - MavenServerEmbedder w = getWrappee(); - if(w == null) - { - return; - } - try - { - w.reset(); - } - catch(RemoteException e) - { - handleRemoteError(e); - } - resetCustomization(); - } - - public void release() - { - MavenServerEmbedder w = getWrappee(); - if(w == null) - { - return; - } - try - { - w.release(); - } - catch(RemoteException e) - { - handleRemoteError(e); - } - resetCustomization(); - } - - - public void clearCaches() - { - MavenServerEmbedder w = getWrappee(); - if(w == null) - { - return; - } - try - { - w.clearCaches(); - } - catch(RemoteException e) - { - handleRemoteError(e); - } - } - - public void clearCachesFor(MavenId projectId) - { - MavenServerEmbedder w = getWrappee(); - if(w == null) - { - return; - } - try - { - w.clearCachesFor(projectId); - } - catch(RemoteException e) - { - handleRemoteError(e); - } - } - - private synchronized void setCustomization(MavenConsole console, MavenProgressIndicator indicator, MavenWorkspaceMap workspaceMap, boolean failOnUnresolvedDependency, - boolean alwaysUpdateSnapshot) - { - resetCustomization(); - myCustomization = new Customization(MavenServerManager.wrapAndExport(console), MavenServerManager.wrapAndExport(indicator), workspaceMap, failOnUnresolvedDependency, alwaysUpdateSnapshot); - } - - private synchronized void resetCustomization() - { - if(myCustomization == null) - { - return; - } - - try - { - UnicastRemoteObject.unexportObject(myCustomization.console, true); - } - catch(NoSuchObjectException e) - { - MavenLog.LOG.warn(e); - } - try - { - UnicastRemoteObject.unexportObject(myCustomization.indicator, true); - } - catch(NoSuchObjectException e) - { - MavenLog.LOG.warn(e); - } - - myCustomization = null; - } - - private static class Customization - { - private final MavenServerConsole console; - private final MavenServerProgressIndicator indicator; - - private final MavenWorkspaceMap workspaceMap; - private final boolean failOnUnresolvedDependency; - private final boolean alwaysUpdateSnapshot; - - private Customization(MavenServerConsole console, MavenServerProgressIndicator indicator, MavenWorkspaceMap workspaceMap, boolean failOnUnresolvedDependency, boolean alwaysUpdateSnapshot) - { - this.console = console; - this.indicator = indicator; - this.workspaceMap = workspaceMap; - this.failOnUnresolvedDependency = failOnUnresolvedDependency; - this.alwaysUpdateSnapshot = alwaysUpdateSnapshot; - } - } +public abstract class MavenEmbedderWrapper extends RemoteObjectWrapper { + private Customization myCustomization; + + public MavenEmbedderWrapper(@Nullable RemoteObjectWrapper parent) { + super(parent); + } + + @Override + protected synchronized void onWrappeeCreated() throws RemoteException { + super.onWrappeeCreated(); + if (myCustomization != null) { + doCustomize(); + } + } + + public void customizeForResolve(MavenConsole console, MavenProgressIndicator indicator) { + setCustomization(console, indicator, null, false, false); + perform((Retriable)() -> { + doCustomize(); + return null; + }); + } + + public void customizeForResolve( + MavenWorkspaceMap workspaceMap, + MavenConsole console, + MavenProgressIndicator indicator, + boolean alwaysUpdateSnapshot + ) { + setCustomization(console, indicator, workspaceMap, false, alwaysUpdateSnapshot); + perform((Retriable)() -> { + doCustomize(); + return null; + }); + } + + public void customizeForStrictResolve(MavenWorkspaceMap workspaceMap, MavenConsole console, MavenProgressIndicator indicator) { + setCustomization(console, indicator, workspaceMap, true, false); + perform((Retriable)() -> { + doCustomize(); + return null; + }); + } + + public void customizeForGetVersions() { + perform((Retriable)() -> { + doCustomizeComponents(); + return null; + }); + } + + private synchronized void doCustomizeComponents() throws RemoteException { + getOrCreateWrappee().customizeComponents(); + } + + private synchronized void doCustomize() throws RemoteException { + getOrCreateWrappee().customize( + myCustomization.workspaceMap, + myCustomization.failOnUnresolvedDependency, + myCustomization.console, + myCustomization.indicator, + myCustomization.alwaysUpdateSnapshot + ); + } + + @Nonnull + public MavenServerExecutionResult resolveProject( + @Nonnull final VirtualFile file, + @Nonnull final Collection activeProfiles, + @Nonnull final Collection inactiveProfiles + ) throws MavenProcessCanceledException { + return perform((RetriableCancelable)() -> getOrCreateWrappee().resolveProject( + new File(file.getPath()), + activeProfiles, + inactiveProfiles + )); + } + + @Nullable + public String evaluateEffectivePom( + @Nonnull final VirtualFile file, + @Nonnull final Collection activeProfiles, + @Nonnull final Collection inactiveProfiles + ) throws MavenProcessCanceledException { + return perform((RetriableCancelable)() -> getOrCreateWrappee().evaluateEffectivePom( + new File(file.getPath()), + new ArrayList<>(activeProfiles), + new ArrayList<>(inactiveProfiles) + )); + } + + @Nonnull + public MavenArtifact resolve( + @Nonnull final MavenArtifactInfo info, + @Nonnull final List remoteRepositories + ) throws MavenProcessCanceledException { + return perform((RetriableCancelable)() -> getOrCreateWrappee().resolve(info, remoteRepositories)); + } + + @Nonnull + public List resolveTransitively( + @Nonnull final List artifacts, + @Nonnull final List remoteRepositories + ) throws MavenProcessCanceledException { + return perform((RetriableCancelable>)() -> getOrCreateWrappee().resolveTransitively( + artifacts, + remoteRepositories + )); + } + + @Nonnull + public List retrieveVersions( + @Nonnull final String groupId, + @Nonnull final String artifactId, + @Nonnull final List remoteRepositories + ) throws MavenProcessCanceledException { + return perform((RetriableCancelable>)() -> getOrCreateWrappee().retrieveAvailableVersions( + groupId, + artifactId, + remoteRepositories + )); + } + + public Collection resolvePlugin( + @Nonnull final MavenPlugin plugin, + @Nonnull final List repositories, + @Nonnull final NativeMavenProjectHolder nativeMavenProject, + final boolean transitive + ) throws MavenProcessCanceledException { + int id; + try { + id = nativeMavenProject.getId(); + } + catch (RemoteException e) { + // do not call handleRemoteError here since this error occurred because of previous remote error + return Collections.emptyList(); + } + + try { + return getOrCreateWrappee().resolvePlugin(plugin, repositories, id, transitive); + } + catch (RemoteException e) { + // do not try to reconnect here since we have lost NativeMavenProjectHolder anyway. + handleRemoteError(e); + return Collections.emptyList(); + } + catch (MavenServerProcessCanceledException e) { + throw new MavenProcessCanceledException(); + } + } + + @Nonnull + public MavenServerExecutionResult execute( + @Nonnull final VirtualFile file, + @Nonnull final Collection activeProfiles, + @Nonnull final Collection inactiveProfiles, + @Nonnull final List goals + ) throws MavenProcessCanceledException { + return perform((RetriableCancelable)() -> getOrCreateWrappee().execute( + new File(file.getPath()), + activeProfiles, + inactiveProfiles, + goals, + Collections.emptyList(), + false, + false + )); + } + + @Nonnull + public MavenServerExecutionResult execute( + @Nonnull final VirtualFile file, + @Nonnull final Collection activeProfiles, + @Nonnull final Collection inactiveProfiles, + @Nonnull final List goals, + @Nonnull final List selectedProjects, + final boolean alsoMake, + final boolean alsoMakeDependents + ) throws MavenProcessCanceledException { + return perform((RetriableCancelable)() -> getOrCreateWrappee().execute( + new File(file.getPath()), + activeProfiles, + inactiveProfiles, + goals, + selectedProjects, + alsoMake, + alsoMakeDependents + )); + } + + public void reset() { + MavenServerEmbedder w = getWrappee(); + if (w == null) { + return; + } + try { + w.reset(); + } + catch (RemoteException e) { + handleRemoteError(e); + } + resetCustomization(); + } + + public void release() { + MavenServerEmbedder w = getWrappee(); + if (w == null) { + return; + } + try { + w.release(); + } + catch (RemoteException e) { + handleRemoteError(e); + } + resetCustomization(); + } + + + public void clearCaches() { + MavenServerEmbedder w = getWrappee(); + if (w == null) { + return; + } + try { + w.clearCaches(); + } + catch (RemoteException e) { + handleRemoteError(e); + } + } + + public void clearCachesFor(MavenId projectId) { + MavenServerEmbedder w = getWrappee(); + if (w == null) { + return; + } + try { + w.clearCachesFor(projectId); + } + catch (RemoteException e) { + handleRemoteError(e); + } + } + + private synchronized void setCustomization( + MavenConsole console, MavenProgressIndicator indicator, + MavenWorkspaceMap workspaceMap, + boolean failOnUnresolvedDependency, + boolean alwaysUpdateSnapshot + ) { + resetCustomization(); + myCustomization = new Customization( + MavenServerManager.wrapAndExport(console), + MavenServerManager.wrapAndExport(indicator), + workspaceMap, + failOnUnresolvedDependency, + alwaysUpdateSnapshot + ); + } + + private synchronized void resetCustomization() { + if (myCustomization == null) { + return; + } + + try { + UnicastRemoteObject.unexportObject(myCustomization.console, true); + } + catch (NoSuchObjectException e) { + MavenLog.LOG.warn(e); + } + try { + UnicastRemoteObject.unexportObject(myCustomization.indicator, true); + } + catch (NoSuchObjectException e) { + MavenLog.LOG.warn(e); + } + + myCustomization = null; + } + + private static class Customization { + private final MavenServerConsole console; + private final MavenServerProgressIndicator indicator; + + private final MavenWorkspaceMap workspaceMap; + private final boolean failOnUnresolvedDependency; + private final boolean alwaysUpdateSnapshot; + + private Customization( + MavenServerConsole console, + MavenServerProgressIndicator indicator, + MavenWorkspaceMap workspaceMap, + boolean failOnUnresolvedDependency, + boolean alwaysUpdateSnapshot + ) { + this.console = console; + this.indicator = indicator; + this.workspaceMap = workspaceMap; + this.failOnUnresolvedDependency = failOnUnresolvedDependency; + this.alwaysUpdateSnapshot = alwaysUpdateSnapshot; + } + } } diff --git a/plugin/src/main/java/org/jetbrains/idea/maven/server/MavenIndexerWrapper.java b/plugin/src/main/java/org/jetbrains/idea/maven/server/MavenIndexerWrapper.java index 6bb2dbef..deb4cc24 100644 --- a/plugin/src/main/java/org/jetbrains/idea/maven/server/MavenIndexerWrapper.java +++ b/plugin/src/main/java/org/jetbrains/idea/maven/server/MavenIndexerWrapper.java @@ -36,232 +36,174 @@ import java.util.Collection; import java.util.Set; -public abstract class MavenIndexerWrapper extends RemoteObjectWrapper -{ - private final IntObjectMap myDataMap = IntMaps.newIntObjectHashMap(); - - public MavenIndexerWrapper(@Nullable RemoteObjectWrapper parent) - { - super(parent); - } - - @Override - protected synchronized void onError() - { - super.onError(); - for(int each : myDataMap.keys()) - { - myDataMap.get(each).remoteId = -1; - } - } - - public synchronized int createIndex(@Nonnull final String indexId, - @Nonnull final String repositoryId, - @Nullable final File file, - @Nullable final String url, - @Nonnull final File indexDir) throws MavenServerIndexerException - { - IndexData data = new IndexData(indexId, repositoryId, file, url, indexDir); - final int localId = System.identityHashCode(data); - myDataMap.put(localId, data); - - perform((IndexRetriable) () -> getRemoteId(localId)); - - return localId; - } - - public synchronized void releaseIndex(int localId) throws MavenServerIndexerException - { - IndexData data = myDataMap.remove(localId); - if(data == null) - { - MavenLog.LOG.warn("index " + localId + " not found"); - return; - } - - // was invalidated on error - if(data.remoteId == -1) - { - return; - } - - MavenServerIndexer w = getWrappee(); - if(w == null) - { - return; - } - - try - { - w.releaseIndex(data.remoteId); - } - catch(RemoteException e) - { - handleRemoteError(e); - } - } - - public synchronized boolean indexExists(File dir) - { - try - { - return getOrCreateWrappee().indexExists(dir); - } - catch(RemoteException e) - { - handleRemoteError(e); - } - return false; - } - - public int getIndexCount() - { - return perform(new Retriable() - { - @Override - public Integer execute() throws RemoteException - { - return getOrCreateWrappee().getIndexCount(); - } - }); - } - - public void updateIndex(final int localId, final MavenGeneralSettings settings, final MavenProgressIndicator indicator) throws MavenProcessCanceledException, MavenServerIndexerException - { - perform(new IndexRetriableCancelable() - { - @Override - public Object execute() throws RemoteException, MavenServerIndexerException, MavenServerProcessCanceledException - { - MavenServerProgressIndicator indicatorWrapper = MavenServerManager.wrapAndExport(indicator); - try - { - getOrCreateWrappee().updateIndex(getRemoteId(localId), MavenServerManager.convertSettings(settings), indicatorWrapper); - } - finally - { - UnicastRemoteObject.unexportObject(indicatorWrapper, true); - } - return null; - } - }); - } - - public void processArtifacts(final int indexId, final MavenIndicesProcessor processor) throws MavenServerIndexerException - { - perform(new IndexRetriable() - { - @Override - public Object execute() throws RemoteException, MavenServerIndexerException - { - MavenServerIndicesProcessor processorWrapper = MavenServerManager.wrapAndExport(processor); - try - { - getOrCreateWrappee().processArtifacts(getRemoteId(indexId), processorWrapper); - } - finally - { - UnicastRemoteObject.unexportObject(processorWrapper, true); - } - return null; - } - }); - } - - public MavenId addArtifact(final int localId, final File artifactFile) throws MavenServerIndexerException - { - return perform(new IndexRetriable() - { - @Override - public MavenId execute() throws RemoteException, MavenServerIndexerException - { - return getOrCreateWrappee().addArtifact(getRemoteId(localId), artifactFile); - } - }); - } - - public Set search(final int localId, final Query query, final int maxResult) throws MavenServerIndexerException - { - return perform(new IndexRetriable>() - { - @Override - public Set execute() throws RemoteException, MavenServerIndexerException - { - return getOrCreateWrappee().search(getRemoteId(localId), query, maxResult); - } - }); - } - - private synchronized int getRemoteId(int localId) throws RemoteException, MavenServerIndexerException - { - IndexData result = myDataMap.get(localId); - MavenLog.LOG.assertTrue(result != null, "index " + localId + " not found"); - - if(result.remoteId == -1) - { - result.remoteId = getOrCreateWrappee().createIndex(result.indexId, result.repositoryId, result.file, result.url, result.indexDir); - } - return result.remoteId; - } - - public Collection getArchetypes() - { - return perform(new Retriable>() - { - @Override - public Collection execute() throws RemoteException - { - return getOrCreateWrappee().getArchetypes(); - } - }); - } - - @TestOnly - public void releaseInTests() - { - MavenServerIndexer w = getWrappee(); - if(w == null) - { - return; - } - try - { - w.release(); - } - catch(RemoteException e) - { - handleRemoteError(e); - } - } - - private static class IndexData - { - private int remoteId = -1; - - private final - @Nonnull - String indexId; - private final - @Nonnull - String repositoryId; - private final - @Nullable - File file; - private final - @Nullable - String url; - private final - @Nonnull - File indexDir; - - public IndexData(String indexId, String repositoryId, File file, String url, File indexDir) - { - this.indexId = indexId; - this.repositoryId = repositoryId; - this.file = file; - this.url = url; - this.indexDir = indexDir; - } - } +public abstract class MavenIndexerWrapper extends RemoteObjectWrapper { + private final IntObjectMap myDataMap = IntMaps.newIntObjectHashMap(); + + public MavenIndexerWrapper(@Nullable RemoteObjectWrapper parent) { + super(parent); + } + + @Override + protected synchronized void onError() { + super.onError(); + for (int each : myDataMap.keys()) { + myDataMap.get(each).remoteId = -1; + } + } + + public synchronized int createIndex( + @Nonnull final String indexId, + @Nonnull final String repositoryId, + @Nullable final File file, + @Nullable final String url, + @Nonnull final File indexDir + ) throws MavenServerIndexerException { + IndexData data = new IndexData(indexId, repositoryId, file, url, indexDir); + final int localId = System.identityHashCode(data); + myDataMap.put(localId, data); + + perform((IndexRetriable)() -> getRemoteId(localId)); + + return localId; + } + + public synchronized void releaseIndex(int localId) throws MavenServerIndexerException { + IndexData data = myDataMap.remove(localId); + if (data == null) { + MavenLog.LOG.warn("index " + localId + " not found"); + return; + } + + // was invalidated on error + if (data.remoteId == -1) { + return; + } + + MavenServerIndexer w = getWrappee(); + if (w == null) { + return; + } + + try { + w.releaseIndex(data.remoteId); + } + catch (RemoteException e) { + handleRemoteError(e); + } + } + + public synchronized boolean indexExists(File dir) { + try { + return getOrCreateWrappee().indexExists(dir); + } + catch (RemoteException e) { + handleRemoteError(e); + } + return false; + } + + public int getIndexCount() { + return perform((Retriable)() -> getOrCreateWrappee().getIndexCount()); + } + + public void updateIndex( + final int localId, + final MavenGeneralSettings settings, + final MavenProgressIndicator indicator + ) throws MavenProcessCanceledException, MavenServerIndexerException { + perform((IndexRetriableCancelable)() -> { + MavenServerProgressIndicator indicatorWrapper = MavenServerManager.wrapAndExport(indicator); + try { + getOrCreateWrappee().updateIndex(getRemoteId(localId), MavenServerManager.convertSettings(settings), indicatorWrapper); + } + finally { + UnicastRemoteObject.unexportObject(indicatorWrapper, true); + } + return null; + }); + } + + public void processArtifacts(final int indexId, final MavenIndicesProcessor processor) throws MavenServerIndexerException { + perform((IndexRetriable)() -> { + MavenServerIndicesProcessor processorWrapper = MavenServerManager.wrapAndExport(processor); + try { + getOrCreateWrappee().processArtifacts(getRemoteId(indexId), processorWrapper); + } + finally { + UnicastRemoteObject.unexportObject(processorWrapper, true); + } + return null; + }); + } + + public MavenId addArtifact(final int localId, final File artifactFile) throws MavenServerIndexerException { + return perform((IndexRetriable)() -> getOrCreateWrappee().addArtifact(getRemoteId(localId), artifactFile)); + } + + public Set search(final int localId, final Query query, final int maxResult) throws MavenServerIndexerException { + return perform((IndexRetriable>)() -> getOrCreateWrappee().search(getRemoteId(localId), query, maxResult)); + } + + private synchronized int getRemoteId(int localId) throws RemoteException, MavenServerIndexerException { + IndexData result = myDataMap.get(localId); + MavenLog.LOG.assertTrue(result != null, "index " + localId + " not found"); + + if (result.remoteId == -1) { + result.remoteId = + getOrCreateWrappee().createIndex(result.indexId, result.repositoryId, result.file, result.url, result.indexDir); + } + return result.remoteId; + } + + public Collection getArchetypes() { + return perform((Retriable>)() -> getOrCreateWrappee().getArchetypes()); + } + + @TestOnly + public void releaseInTests() { + MavenServerIndexer w = getWrappee(); + if (w == null) { + return; + } + try { + w.release(); + } + catch (RemoteException e) { + handleRemoteError(e); + } + } + + private static class IndexData { + private int remoteId = -1; + + private final + @Nonnull + String indexId; + private final + @Nonnull + String repositoryId; + private final + @Nullable + File file; + private final + @Nullable + String url; + private final + @Nonnull + File indexDir; + + public IndexData( + @Nonnull String indexId, + @Nonnull String repositoryId, + @Nullable File file, + @Nullable String url, + @Nonnull File indexDir + ) { + this.indexId = indexId; + this.repositoryId = repositoryId; + this.file = file; + this.url = url; + this.indexDir = indexDir; + } + } } - diff --git a/plugin/src/main/java/org/jetbrains/idea/maven/server/MavenIndicesProcessor.java b/plugin/src/main/java/org/jetbrains/idea/maven/server/MavenIndicesProcessor.java index 1c41d9f6..e9ea13ee 100644 --- a/plugin/src/main/java/org/jetbrains/idea/maven/server/MavenIndicesProcessor.java +++ b/plugin/src/main/java/org/jetbrains/idea/maven/server/MavenIndicesProcessor.java @@ -20,7 +20,6 @@ import java.util.Collection; @FunctionalInterface -public interface MavenIndicesProcessor -{ - void processArtifacts(Collection artifacts); +public interface MavenIndicesProcessor { + void processArtifacts(Collection artifacts); } diff --git a/plugin/src/main/java/org/jetbrains/idea/maven/server/MavenServerManager.java b/plugin/src/main/java/org/jetbrains/idea/maven/server/MavenServerManager.java index 142ee6bb..95191dbc 100644 --- a/plugin/src/main/java/org/jetbrains/idea/maven/server/MavenServerManager.java +++ b/plugin/src/main/java/org/jetbrains/idea/maven/server/MavenServerManager.java @@ -122,7 +122,7 @@ public static MavenServerManager getInstance() { public MavenServerManager() { super(null); - mySupport = new RemoteProcessSupport(MavenServer.class) { + mySupport = new RemoteProcessSupport<>(MavenServer.class) { @Override protected void fireModificationCountChanged() { } @@ -223,8 +223,8 @@ private OwnSimpleJavaParameters createJavaParameters() throws ExecutionException for (Map.Entry each : System.getProperties().entrySet()) { Object key = each.getKey(); Object value = each.getValue(); - if (key instanceof String && value instanceof String && ((String) key).startsWith("javax.net.ssl")) { - defs.put((String) key, (String) value); + if (key instanceof String && value instanceof String && ((String)key).startsWith("javax.net.ssl")) { + defs.put((String)key, (String)value); } } @@ -287,7 +287,8 @@ private OwnSimpleJavaParameters createJavaParameters() throws ExecutionException String mavenEmbedderDebugPort = System.getProperty("idea.maven.embedder.debug.port"); if (mavenEmbedderDebugPort != null) { - params.getVMParametersList().addParametersString("-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=" + mavenEmbedderDebugPort); + params.getVMParametersList() + .addParametersString("-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=" + mavenEmbedderDebugPort); } String mavenEmbedderParameters = System.getProperty("idea.maven.embedder.parameters"); @@ -297,7 +298,8 @@ private OwnSimpleJavaParameters createJavaParameters() throws ExecutionException String mavenEmbedderCliOptions = System.getProperty(MavenServerEmbedder.MAVEN_EMBEDDER_CLI_ADDITIONAL_ARGS); if (mavenEmbedderCliOptions != null) { - params.getVMParametersList().addProperty(MavenServerEmbedder.MAVEN_EMBEDDER_CLI_ADDITIONAL_ARGS, mavenEmbedderCliOptions); + params.getVMParametersList() + .addProperty(MavenServerEmbedder.MAVEN_EMBEDDER_CLI_ADDITIONAL_ARGS, mavenEmbedderCliOptions); } return params; @@ -438,15 +440,25 @@ protected MavenServerIndexer create() throws RemoteException { } public MavenModel interpolateAndAlignModel(final MavenModel model, final File basedir) { - return perform((Retriable) () -> getOrCreateWrappee().interpolateAndAlignModel(model, basedir)); + return perform((Retriable)() -> getOrCreateWrappee().interpolateAndAlignModel(model, basedir)); } public MavenModel assembleInheritance(final MavenModel model, final MavenModel parentModel) { - return perform((Retriable) () -> getOrCreateWrappee().assembleInheritance(model, parentModel)); + return perform((Retriable)() -> getOrCreateWrappee().assembleInheritance(model, parentModel)); } - public ProfileApplicationResult applyProfiles(final MavenModel model, final File basedir, final MavenExplicitProfiles explicitProfiles, final Collection alwaysOnProfiles) { - return perform((Retriable) () -> getOrCreateWrappee().applyProfiles(model, basedir, explicitProfiles, alwaysOnProfiles)); + public ProfileApplicationResult applyProfiles( + final MavenModel model, + final File basedir, + final MavenExplicitProfiles explicitProfiles, + final Collection alwaysOnProfiles + ) { + return perform((Retriable)() -> getOrCreateWrappee().applyProfiles( + model, + basedir, + explicitProfiles, + alwaysOnProfiles + )); } public void addDownloadListener(MavenServerDownloadListener listener) { @@ -466,7 +478,11 @@ public static MavenServerSettings convertSettings(MavenGeneralSettings settings) result.setGlobalSettingsFile(settings.getEffectiveGlobalSettingsIoFile()); result.setLocalRepository(settings.getEffectiveLocalRepository()); result.setPluginUpdatePolicy(settings.getPluginUpdatePolicy().getServerPolicy()); - result.setSnapshotUpdatePolicy(settings.isAlwaysUpdateSnapshots() ? MavenServerSettings.UpdatePolicy.ALWAYS_UPDATE : MavenServerSettings.UpdatePolicy.DO_NOT_UPDATE); + result.setSnapshotUpdatePolicy( + settings.isAlwaysUpdateSnapshots() + ? MavenServerSettings.UpdatePolicy.ALWAYS_UPDATE + : MavenServerSettings.UpdatePolicy.DO_NOT_UPDATE + ); return result; } diff --git a/plugin/src/main/java/org/jetbrains/idea/maven/server/RemoteObjectWrapper.java b/plugin/src/main/java/org/jetbrains/idea/maven/server/RemoteObjectWrapper.java index 750abd0c..71bde2d4 100644 --- a/plugin/src/main/java/org/jetbrains/idea/maven/server/RemoteObjectWrapper.java +++ b/plugin/src/main/java/org/jetbrains/idea/maven/server/RemoteObjectWrapper.java @@ -26,125 +26,129 @@ import java.rmi.RemoteException; public abstract class RemoteObjectWrapper { - @Nullable - private final RemoteObjectWrapper myParent; - @Nullable private T myWrappee; - - protected RemoteObjectWrapper(@Nullable RemoteObjectWrapper parent) { - myParent = parent; - } - - @Nullable - protected synchronized T getWrappee() { - return myWrappee == null ? null : myWrappee; - } - - @Nonnull - protected synchronized T getOrCreateWrappee() throws RemoteException { - if (myWrappee == null) { - myWrappee = create(); - onWrappeeCreated(); - } - onWrappeeAccessed(); - return myWrappee; - } - - @Nonnull - protected abstract T create() throws RemoteException; - - protected void onWrappeeCreated() throws RemoteException { - } - - protected void onWrappeeAccessed() { - if (myParent != null) myParent.onWrappeeAccessed(); - } - - protected synchronized void handleRemoteError(RemoteException e) { - MavenLog.LOG.debug("Connection failed. Will be reconnected on the next request.", e); - onError(); - } - - protected synchronized void onError() { - cleanup(); - if (myParent != null) myParent.onError(); - } - - protected synchronized void cleanup() { - myWrappee = null; - } - - protected T perform(Retriable r) { - RemoteException last = null; - for (int i = 0; i < 2; i++) { - try { - return r.execute(); - } - catch (RemoteException e) { - handleRemoteError(last = e); - } - } - throw new RuntimeException("Cannot reconnect.", last); - } - - protected T perform(RetriableCancelable r) throws MavenProcessCanceledException { - RemoteException last = null; - for (int i = 0; i < 2; i++) { - try { - return r.execute(); - } - catch (RemoteException e) { - handleRemoteError(last = e); - } - catch (MavenServerProcessCanceledException e) { - throw new MavenProcessCanceledException(); - } - } - throw new RuntimeException("Cannot reconnect.", last); - } - - protected T perform(IndexRetriable r) throws MavenServerIndexerException - { - RemoteException last = null; - for (int i = 0; i < 2; i++) { - try { - return r.execute(); - } - catch (RemoteException e) { - handleRemoteError(last = e); - } - } - throw new RuntimeException("Cannot reconnect.", last); - } - - protected T perform(IndexRetriableCancelable r) throws MavenServerIndexerException, MavenProcessCanceledException { - RemoteException last = null; - for (int i = 0; i < 2; i++) { - try { - return r.execute(); - } - catch (RemoteException e) { - handleRemoteError(last = e); - } - catch (MavenServerProcessCanceledException e) { - throw new MavenProcessCanceledException(); - } - } - throw new RuntimeException("Cannot reconnect.", last); - } - - protected interface Retriable { - T execute() throws RemoteException; - } - - protected interface IndexRetriable { - T execute() throws RemoteException, MavenServerIndexerException; - } - - protected interface IndexRetriableCancelable { - T execute() throws RemoteException, MavenServerIndexerException, MavenServerProcessCanceledException; - } - - protected interface RetriableCancelable { - T execute() throws RemoteException, MavenServerProcessCanceledException; - } + @Nullable + private final RemoteObjectWrapper myParent; + @Nullable + private T myWrappee; + + protected RemoteObjectWrapper(@Nullable RemoteObjectWrapper parent) { + myParent = parent; + } + + @Nullable + protected synchronized T getWrappee() { + return myWrappee == null ? null : myWrappee; + } + + @Nonnull + protected synchronized T getOrCreateWrappee() throws RemoteException { + if (myWrappee == null) { + myWrappee = create(); + onWrappeeCreated(); + } + onWrappeeAccessed(); + return myWrappee; + } + + @Nonnull + protected abstract T create() throws RemoteException; + + protected void onWrappeeCreated() throws RemoteException { + } + + protected void onWrappeeAccessed() { + if (myParent != null) { + myParent.onWrappeeAccessed(); + } + } + + protected synchronized void handleRemoteError(RemoteException e) { + MavenLog.LOG.debug("Connection failed. Will be reconnected on the next request.", e); + onError(); + } + + protected synchronized void onError() { + cleanup(); + if (myParent != null) { + myParent.onError(); + } + } + + protected synchronized void cleanup() { + myWrappee = null; + } + + protected T perform(Retriable r) { + RemoteException last = null; + for (int i = 0; i < 2; i++) { + try { + return r.execute(); + } + catch (RemoteException e) { + handleRemoteError(last = e); + } + } + throw new RuntimeException("Cannot reconnect.", last); + } + + protected T perform(RetriableCancelable r) throws MavenProcessCanceledException { + RemoteException last = null; + for (int i = 0; i < 2; i++) { + try { + return r.execute(); + } + catch (RemoteException e) { + handleRemoteError(last = e); + } + catch (MavenServerProcessCanceledException e) { + throw new MavenProcessCanceledException(); + } + } + throw new RuntimeException("Cannot reconnect.", last); + } + + protected T perform(IndexRetriable r) throws MavenServerIndexerException { + RemoteException last = null; + for (int i = 0; i < 2; i++) { + try { + return r.execute(); + } + catch (RemoteException e) { + handleRemoteError(last = e); + } + } + throw new RuntimeException("Cannot reconnect.", last); + } + + protected T perform(IndexRetriableCancelable r) throws MavenServerIndexerException, MavenProcessCanceledException { + RemoteException last = null; + for (int i = 0; i < 2; i++) { + try { + return r.execute(); + } + catch (RemoteException e) { + handleRemoteError(last = e); + } + catch (MavenServerProcessCanceledException e) { + throw new MavenProcessCanceledException(); + } + } + throw new RuntimeException("Cannot reconnect.", last); + } + + protected interface Retriable { + T execute() throws RemoteException; + } + + protected interface IndexRetriable { + T execute() throws RemoteException, MavenServerIndexerException; + } + + protected interface IndexRetriableCancelable { + T execute() throws RemoteException, MavenServerIndexerException, MavenServerProcessCanceledException; + } + + protected interface RetriableCancelable { + T execute() throws RemoteException, MavenServerProcessCanceledException; + } } diff --git a/plugin/src/main/java/org/jetbrains/idea/maven/services/MavenRepositoryService.java b/plugin/src/main/java/org/jetbrains/idea/maven/services/MavenRepositoryService.java index 21cce2a0..a8c0eb00 100644 --- a/plugin/src/main/java/org/jetbrains/idea/maven/services/MavenRepositoryService.java +++ b/plugin/src/main/java/org/jetbrains/idea/maven/services/MavenRepositoryService.java @@ -16,6 +16,7 @@ package org.jetbrains.idea.maven.services; import javax.annotation.Nonnull; + import consulo.maven.rt.server.common.model.MavenArtifactInfo; import consulo.maven.rt.server.common.model.MavenRepositoryInfo; @@ -26,17 +27,16 @@ * @author Gregory.Shrago */ public abstract class MavenRepositoryService { - @Nonnull - public abstract String getDisplayName(); - - @Nonnull - public abstract List getRepositories(@Nonnull String url) throws IOException; + @Nonnull + public abstract String getDisplayName(); - @Nonnull - public abstract List findArtifacts(@Nonnull String url, @Nonnull MavenArtifactInfo template) throws IOException; + @Nonnull + public abstract List getRepositories(@Nonnull String url) throws IOException; + @Nonnull + public abstract List findArtifacts(@Nonnull String url, @Nonnull MavenArtifactInfo template) throws IOException; - public final String toString() { - return getDisplayName(); - } + public final String toString() { + return getDisplayName(); + } } diff --git a/plugin/src/main/java/org/jetbrains/idea/maven/services/MavenRepositoryServicesManager.java b/plugin/src/main/java/org/jetbrains/idea/maven/services/MavenRepositoryServicesManager.java index 764f4d7a..6f92119c 100644 --- a/plugin/src/main/java/org/jetbrains/idea/maven/services/MavenRepositoryServicesManager.java +++ b/plugin/src/main/java/org/jetbrains/idea/maven/services/MavenRepositoryServicesManager.java @@ -43,115 +43,93 @@ * @author Gregory.Shrago */ @State( - name = "MavenServices", - storages = { - @Storage( - file = StoragePathMacros.APP_CONFIG + "/mavenServices.xml") - }) + name = "MavenServices", + storages = {@Storage(file = StoragePathMacros.APP_CONFIG + "/mavenServices.xml")} +) @ServiceAPI(ComponentScope.APPLICATION) @ServiceImpl @Singleton -public class MavenRepositoryServicesManager implements PersistentStateComponent -{ - private final List myUrls = new ArrayList(); +public class MavenRepositoryServicesManager implements PersistentStateComponent { + private final List myUrls = new ArrayList<>(); - @Nonnull - public static MavenRepositoryServicesManager getInstance() - { - return ServiceManager.getService(MavenRepositoryServicesManager.class); - } + @Nonnull + public static MavenRepositoryServicesManager getInstance() { + return ServiceManager.getService(MavenRepositoryServicesManager.class); + } - @Nonnull - public static MavenRepositoryService[] getServices() - { - return new MavenRepositoryService[]{ - new NexusRepositoryService(), - new ArtifactoryRepositoryService() - }; - } + @Nonnull + public static MavenRepositoryService[] getServices() { + return new MavenRepositoryService[]{ + new NexusRepositoryService(), + new ArtifactoryRepositoryService() + }; + } - public static String[] getServiceUrls() - { - final List configured = getInstance().getUrls(); - if(!configured.isEmpty()) - { - return ArrayUtil.toStringArray(configured); - } - return new String[]{ - "http://oss.sonatype.org/service/local/", - "http://repo.jfrog.org/artifactory/api/", - "https://repository.jboss.org/nexus/service/local/" - }; - } + public static String[] getServiceUrls() { + final List configured = getInstance().getUrls(); + if (!configured.isEmpty()) { + return ArrayUtil.toStringArray(configured); + } + return new String[]{ + "http://oss.sonatype.org/service/local/", + "http://repo.jfrog.org/artifactory/api/", + "https://repository.jboss.org/nexus/service/local/" + }; + } - public List getUrls() - { - return myUrls; - } + public List getUrls() { + return myUrls; + } - public void setUrls(List urls) - { - myUrls.clear(); - myUrls.addAll(urls); - } + public void setUrls(List urls) { + myUrls.clear(); + myUrls.addAll(urls); + } + @Override + public Element getState() { + final Element element = new Element("maven-services"); + for (String url : myUrls) { + final Element child = new Element("service-url"); + child.setText(StringUtil.escapeXml(url)); + element.addContent(child); + } + return element; + } - @Override - public Element getState() - { - final Element element = new Element("maven-services"); - for(String url : myUrls) - { - final Element child = new Element("service-url"); - child.setText(StringUtil.escapeXml(url)); - element.addContent(child); - } - return element; - } + @Override + public void loadState(Element state) { + myUrls.clear(); + for (Element element : (List)state.getChildren("service-url")) { + myUrls.add(StringUtil.unescapeXml(element.getTextTrim())); + } + } - @Override - public void loadState(Element state) - { - myUrls.clear(); - for(Element element : (List) state.getChildren("service-url")) - { - myUrls.add(StringUtil.unescapeXml(element.getTextTrim())); - } - } + @Nonnull + public static List getRepositories(String url) { + List result = new SmartList<>(); + for (MavenRepositoryService service : getServices()) { + try { + result.addAll(service.getRepositories(url)); + } + catch (IOException e) { + MavenLog.LOG.info(e); + } + } + return result; + } - @Nonnull - public static List getRepositories(String url) - { - List result = new SmartList(); - for(MavenRepositoryService service : getServices()) - { - try - { - result.addAll(service.getRepositories(url)); - } - catch(IOException e) - { - MavenLog.LOG.info(e); - } - } - return result; - } - - @Nonnull - public static List findArtifacts(@Nonnull MavenArtifactInfo template, @Nonnull String url) - { - List result = new SmartList(); - for(MavenRepositoryService service : getServices()) - { - try - { - result.addAll(service.findArtifacts(url, template)); - } - catch(IOException e) - { - MavenLog.LOG.info(e); - } - } - return result; - } + @Nonnull + public static List findArtifacts(@Nonnull MavenArtifactInfo template, @Nonnull String url) { + List result = new SmartList<>(); + for (MavenRepositoryService service : getServices()) { + try { + result.addAll(service.findArtifacts(url, template)); + } + catch (IOException e) { + MavenLog.LOG.info(e); + } + } + return result; + } } diff --git a/plugin/src/main/java/org/jetbrains/idea/maven/services/artifactory/ArtifactoryModel.java b/plugin/src/main/java/org/jetbrains/idea/maven/services/artifactory/ArtifactoryModel.java index 6409be82..15511449 100644 --- a/plugin/src/main/java/org/jetbrains/idea/maven/services/artifactory/ArtifactoryModel.java +++ b/plugin/src/main/java/org/jetbrains/idea/maven/services/artifactory/ArtifactoryModel.java @@ -19,52 +19,52 @@ * @author Gregory.Shrago */ public class ArtifactoryModel { - public static class RepositoryType { - public String key; - public String type; - public String description; - public String url; - public String configuration; - } + public static class RepositoryType { + public String key; + public String type; + public String description; + public String url; + public String configuration; + } - public static class GavcResults { - public GavcResult[] results; - } + public static class GavcResults { + public GavcResult[] results; + } - public static class GavcResult { - public String uri; - } + public static class GavcResult { + public String uri; + } - public static class ArchiveResults { - public ArchiveResult[] results; - } + public static class ArchiveResults { + public ArchiveResult[] results; + } - public static class ArchiveResult { - public String entry; - public String[] archiveUris; - } + public static class ArchiveResult { + public String entry; + public String[] archiveUris; + } - public static class FileInfo { - public String uri; - public String downloadUri; - public String metadataUri; - public String repo; - public String path; - public String remoteUrl; - public String created; - public String createdBy; - public String lastModified; - public String modifiedBy; - public String lastUpdated; - public String size; - public String mimeType; - public Checksums checksums; - public Checksums originalChecksums; - } + public static class FileInfo { + public String uri; + public String downloadUri; + public String metadataUri; + public String repo; + public String path; + public String remoteUrl; + public String created; + public String createdBy; + public String lastModified; + public String modifiedBy; + public String lastUpdated; + public String size; + public String mimeType; + public Checksums checksums; + public Checksums originalChecksums; + } - public static class Checksums { - public String md5; - public String sha1; - } + public static class Checksums { + public String md5; + public String sha1; + } } diff --git a/plugin/src/main/java/org/jetbrains/idea/maven/services/artifactory/ArtifactoryRepositoryService.java b/plugin/src/main/java/org/jetbrains/idea/maven/services/artifactory/ArtifactoryRepositoryService.java index 4b146455..3a50de67 100644 --- a/plugin/src/main/java/org/jetbrains/idea/maven/services/artifactory/ArtifactoryRepositoryService.java +++ b/plugin/src/main/java/org/jetbrains/idea/maven/services/artifactory/ArtifactoryRepositoryService.java @@ -19,6 +19,7 @@ import com.google.gson.JsonSyntaxException; import javax.annotation.Nonnull; + import consulo.maven.rt.server.common.model.MavenArtifactInfo; import consulo.maven.rt.server.common.model.MavenRepositoryInfo; import consulo.util.lang.StringUtil; @@ -36,97 +37,104 @@ * @author Gregory.Shrago */ public class ArtifactoryRepositoryService extends MavenRepositoryService { - @Nonnull - @Override - public String getDisplayName() { - return "Artifactory"; - } - - @Nonnull - @Override - public List getRepositories(@Nonnull String url) throws IOException { - try { - final Gson gson = new Gson(); - final InputStreamReader stream = - new InputStreamReader(new Endpoint.Repositories(url).getRepositoryDetailsListJson(null).getInputStream()); - final ArtifactoryModel.RepositoryType[] repos = gson.fromJson(stream, ArtifactoryModel.RepositoryType[].class); - final List result = new ArrayList(repos.length); - for (ArtifactoryModel.RepositoryType repo : repos) { - result.add(convert(repo)); - } - return result; + @Nonnull + @Override + public String getDisplayName() { + return "Artifactory"; } - catch (JsonSyntaxException e) { - return Collections.emptyList(); - } - catch (Exception e) { - throw new IOException(e); + + @Nonnull + @Override + public List getRepositories(@Nonnull String url) throws IOException { + try { + final Gson gson = new Gson(); + final InputStreamReader stream = + new InputStreamReader(new Endpoint.Repositories(url).getRepositoryDetailsListJson(null).getInputStream()); + final ArtifactoryModel.RepositoryType[] repos = gson.fromJson(stream, ArtifactoryModel.RepositoryType[].class); + final List result = new ArrayList<>(repos.length); + for (ArtifactoryModel.RepositoryType repo : repos) { + result.add(convert(repo)); + } + return result; + } + catch (JsonSyntaxException e) { + return Collections.emptyList(); + } + catch (Exception e) { + throw new IOException(e); + } } - } - private static MavenRepositoryInfo convert(ArtifactoryModel.RepositoryType repo) { - return new MavenRepositoryInfo(repo.key, repo.description, repo.url); - } + private static MavenRepositoryInfo convert(ArtifactoryModel.RepositoryType repo) { + return new MavenRepositoryInfo(repo.key, repo.description, repo.url); + } - @Nonnull - @Override - public List findArtifacts(@Nonnull String url, @Nonnull MavenArtifactInfo template) throws IOException { - try { - final String packaging = StringUtil.notNullize(template.getPackaging()); - final ArrayList artifacts = new ArrayList(); - final Gson gson = new Gson(); - final String className = template.getClassNames(); - if (className == null || className.length() == 0) { - final String name = StringUtil.join(Arrays.asList(template.getGroupId(), template.getArtifactId(), template.getVersion()), ":"); - final InputStream stream = new Endpoint.Search.Artifact(url).getArtifactSearchResultJson(name, null).getInputStream(); + @Nonnull + @Override + public List findArtifacts(@Nonnull String url, @Nonnull MavenArtifactInfo template) throws IOException { + try { + final String packaging = StringUtil.notNullize(template.getPackaging()); + final ArrayList artifacts = new ArrayList<>(); + final Gson gson = new Gson(); + final String className = template.getClassNames(); + if (className == null || className.length() == 0) { + final String name = + StringUtil.join(Arrays.asList(template.getGroupId(), template.getArtifactId(), template.getVersion()), ":"); + final InputStream stream = new Endpoint.Search.Artifact(url).getArtifactSearchResultJson(name, null).getInputStream(); - final ArtifactoryModel.GavcResults results = stream == null? null : gson.fromJson(new InputStreamReader(stream), ArtifactoryModel.GavcResults.class); - if (results != null && results.results != null) { - for (ArtifactoryModel.GavcResult result : results.results) { - if (!result.uri.endsWith(packaging)) continue; - artifacts.add(convertArtifactInfo(result.uri, url, null)); - } - } - } - else { - // IDEA-58225 - final String searchString = className.endsWith("*") || className.endsWith("?") ? className : className + ".class"; - final InputStream stream = new Endpoint.Search.Archive(url).getArchiveSearchResultJson(searchString, null).getInputStream(); + final ArtifactoryModel.GavcResults results = + stream == null ? null : gson.fromJson(new InputStreamReader(stream), ArtifactoryModel.GavcResults.class); + if (results != null && results.results != null) { + for (ArtifactoryModel.GavcResult result : results.results) { + if (!result.uri.endsWith(packaging)) { + continue; + } + artifacts.add(convertArtifactInfo(result.uri, url, null)); + } + } + } + else { + // IDEA-58225 + final String searchString = className.endsWith("*") || className.endsWith("?") ? className : className + ".class"; + final InputStream stream = new Endpoint.Search.Archive(url).getArchiveSearchResultJson(searchString, null).getInputStream(); - final ArtifactoryModel.ArchiveResults results = stream == null? null : gson.fromJson(new InputStreamReader(stream), ArtifactoryModel.ArchiveResults.class); - if (results != null && results.results != null) { - for (ArtifactoryModel.ArchiveResult result : results.results) { - for (String uri : result.archiveUris) { - if (!uri.endsWith(packaging)) continue; - artifacts.add(convertArtifactInfo(uri, url, result.entry)); + final ArtifactoryModel.ArchiveResults results = + stream == null ? null : gson.fromJson(new InputStreamReader(stream), ArtifactoryModel.ArchiveResults.class); + if (results != null && results.results != null) { + for (ArtifactoryModel.ArchiveResult result : results.results) { + for (String uri : result.archiveUris) { + if (!uri.endsWith(packaging)) { + continue; + } + artifacts.add(convertArtifactInfo(uri, url, result.entry)); + } + } + } } - } + return artifacts; + } + catch (JsonSyntaxException e) { + return Collections.emptyList(); + } + catch (Exception e) { + throw new IOException(e); } - } - return artifacts; - } - catch (JsonSyntaxException e) { - return Collections.emptyList(); - } - catch (Exception e) { - throw new IOException(e); } - } - private static MavenArtifactInfo convertArtifactInfo(String uri, String baseUri, String className) throws IOException { - final String repoPathFile = uri.substring((baseUri + "storage/").length()); - final int repoIndex = repoPathFile.indexOf('/'); - final String repoString = repoPathFile.substring(0, repoIndex); - final String repo = repoString.endsWith("-cache") ? repoString.substring(0, repoString.lastIndexOf('-')) : repoString; - final String filePath = repoPathFile.substring(repoIndex + 1, repoPathFile.lastIndexOf('/')); - final int artIdIndex = filePath.lastIndexOf('/'); - final String version = filePath.substring(artIdIndex + 1); - final String groupArtifact = filePath.substring(0, artIdIndex); - final int groupIndex = groupArtifact.lastIndexOf('/'); - final String artifact = groupArtifact.substring(groupIndex + 1); - final String group = groupArtifact.substring(0, groupIndex).replace('/', '.'); - final String packaging = uri.substring(uri.lastIndexOf('.') + 1); + private static MavenArtifactInfo convertArtifactInfo(String uri, String baseUri, String className) throws IOException { + final String repoPathFile = uri.substring((baseUri + "storage/").length()); + final int repoIndex = repoPathFile.indexOf('/'); + final String repoString = repoPathFile.substring(0, repoIndex); + final String repo = repoString.endsWith("-cache") ? repoString.substring(0, repoString.lastIndexOf('-')) : repoString; + final String filePath = repoPathFile.substring(repoIndex + 1, repoPathFile.lastIndexOf('/')); + final int artIdIndex = filePath.lastIndexOf('/'); + final String version = filePath.substring(artIdIndex + 1); + final String groupArtifact = filePath.substring(0, artIdIndex); + final int groupIndex = groupArtifact.lastIndexOf('/'); + final String artifact = groupArtifact.substring(groupIndex + 1); + final String group = groupArtifact.substring(0, groupIndex).replace('/', '.'); + final String packaging = uri.substring(uri.lastIndexOf('.') + 1); - return new MavenArtifactInfo(group, artifact, version, packaging, null, className, repo); - } + return new MavenArtifactInfo(group, artifact, version, packaging, null, className, repo); + } } diff --git a/plugin/src/main/java/org/jetbrains/idea/maven/services/artifactory/Endpoint.java b/plugin/src/main/java/org/jetbrains/idea/maven/services/artifactory/Endpoint.java index 8109ceb9..3f62116f 100644 --- a/plugin/src/main/java/org/jetbrains/idea/maven/services/artifactory/Endpoint.java +++ b/plugin/src/main/java/org/jetbrains/idea/maven/services/artifactory/Endpoint.java @@ -23,30 +23,32 @@ import consulo.maven.internal.org.jvnet.ws.wadl.util.UriBuilder; import jakarta.activation.DataSource; + import java.io.IOException; import java.net.MalformedURLException; import java.util.Collections; import java.util.HashMap; import java.util.List; - /** - * + * */ public class Endpoint { + public static DataSource getArtifactInfoByUri(String uri) + throws IOException, MalformedURLException { + DSDispatcher _dsDispatcher = new DSDispatcher(); + UriBuilder _uriBuilder = new UriBuilder(); + _uriBuilder.addPathSegment(uri); + String _url = _uriBuilder.buildUri(Collections.emptyMap(), Collections.emptyMap()); + DataSource _retVal = _dsDispatcher.doGET( + _url, + Collections.emptyMap(), + "application/vnd.org.jfrog.artifactory.search.ArtifactSearchResult+json" + ); + return _retVal; + } - public static DataSource getArtifactInfoByUri(String uri) - throws IOException, MalformedURLException { - DSDispatcher _dsDispatcher = new DSDispatcher(); - UriBuilder _uriBuilder = new UriBuilder(); - _uriBuilder.addPathSegment(uri); - String _url = _uriBuilder.buildUri(Collections.emptyMap(), Collections.emptyMap()); - DataSource _retVal = - _dsDispatcher.doGET(_url, Collections.emptyMap(), "application/vnd.org.jfrog.artifactory.search.ArtifactSearchResult+json"); - return _retVal; - } - - public static class Search { + public static class Search { public static class Artifact { @@ -61,33 +63,34 @@ public static class Artifact { * @param url */ public Artifact(final String url) - throws JAXBException - { + throws JAXBException { _dsDispatcher = new DSDispatcher(); _uriBuilder = new UriBuilder(); List _matrixParamSet; _matrixParamSet = _uriBuilder.addPathSegment(url); _matrixParamSet = _uriBuilder.addPathSegment("search"); _matrixParamSet = _uriBuilder.addPathSegment("artifact"); - _templateAndMatrixParameterValues = new HashMap(); + _templateAndMatrixParameterValues = new HashMap<>(); } public DataSource getArtifactSearchResultJson(String name, String repos) - throws IOException, MalformedURLException - { - HashMap _queryParameterValues = new HashMap(); - HashMap _headerParameterValues = new HashMap(); + throws IOException, MalformedURLException { + HashMap _queryParameterValues = new HashMap<>(); + HashMap _headerParameterValues = new HashMap<>(); _queryParameterValues.put("name", name); _queryParameterValues.put("repos", repos); String _url = _uriBuilder.buildUri(_templateAndMatrixParameterValues, _queryParameterValues); - DataSource _retVal = _dsDispatcher.doGET(_url, _headerParameterValues, "application/vnd.org.jfrog.artifactory.search.ArtifactSearchResult+json"); + DataSource _retVal = _dsDispatcher.doGET( + _url, + _headerParameterValues, + "application/vnd.org.jfrog.artifactory.search.ArtifactSearchResult+json" + ); return _retVal; } } public static class Gavc { - private JAXBDispatcher _jaxbDispatcher; private DSDispatcher _dsDispatcher; private UriBuilder _uriBuilder; @@ -100,35 +103,34 @@ public static class Gavc { * @param url */ public Gavc(final String url) - throws JAXBException - { + throws JAXBException { _dsDispatcher = new DSDispatcher(); _uriBuilder = new UriBuilder(); List _matrixParamSet; _matrixParamSet = _uriBuilder.addPathSegment(url); _matrixParamSet = _uriBuilder.addPathSegment("search"); _matrixParamSet = _uriBuilder.addPathSegment("gavc"); - _templateAndMatrixParameterValues = new HashMap(); + _templateAndMatrixParameterValues = new HashMap<>(); } public DataSource getGavcSearchResultJson(String g, String a, String v, String c, String repos) - throws IOException, MalformedURLException - { - HashMap _queryParameterValues = new HashMap(); - HashMap _headerParameterValues = new HashMap(); + throws IOException, MalformedURLException { + HashMap _queryParameterValues = new HashMap<>(); + HashMap _headerParameterValues = new HashMap<>(); _queryParameterValues.put("g", g); _queryParameterValues.put("a", a); _queryParameterValues.put("v", v); _queryParameterValues.put("c", c); _queryParameterValues.put("repos", repos); String _url = _uriBuilder.buildUri(_templateAndMatrixParameterValues, _queryParameterValues); - DataSource _retVal = _dsDispatcher.doGET(_url, _headerParameterValues, "application/vnd.org.jfrog.artifactory.search.GavcSearchResult+json"); + DataSource _retVal = + _dsDispatcher.doGET(_url, _headerParameterValues, "application/vnd.org.jfrog.artifactory.search.GavcSearchResult+json"); return _retVal; } } - public static class Archive { + public static class Archive { private JAXBDispatcher _jaxbDispatcher; private DSDispatcher _dsDispatcher; private UriBuilder _uriBuilder; @@ -141,26 +143,28 @@ public static class Archive { * @param url */ public Archive(final String url) - throws JAXBException - { + throws JAXBException { _dsDispatcher = new DSDispatcher(); _uriBuilder = new UriBuilder(); List _matrixParamSet; _matrixParamSet = _uriBuilder.addPathSegment(url); _matrixParamSet = _uriBuilder.addPathSegment("search"); _matrixParamSet = _uriBuilder.addPathSegment("archive"); - _templateAndMatrixParameterValues = new HashMap(); + _templateAndMatrixParameterValues = new HashMap<>(); } public DataSource getArchiveSearchResultJson(String className, String repos) - throws IOException, MalformedURLException - { - HashMap _queryParameterValues = new HashMap(); - HashMap _headerParameterValues = new HashMap(); + throws IOException, MalformedURLException { + HashMap _queryParameterValues = new HashMap<>(); + HashMap _headerParameterValues = new HashMap<>(); _queryParameterValues.put("name", className); _queryParameterValues.put("repos", repos); String _url = _uriBuilder.buildUri(_templateAndMatrixParameterValues, _queryParameterValues); - DataSource _retVal = _dsDispatcher.doGET(_url, _headerParameterValues, "application/vnd.org.jfrog.artifactory.search.ArchiveEntrySearchResult+json"); + DataSource _retVal = _dsDispatcher.doGET( + _url, + _headerParameterValues, + "application/vnd.org.jfrog.artifactory.search.ArchiveEntrySearchResult+json" + ); return _retVal; } @@ -169,7 +173,6 @@ public DataSource getArchiveSearchResultJson(String className, String repos) } public static class System { - private JAXBDispatcher _jaxbDispatcher; private DSDispatcher _dsDispatcher; private UriBuilder _uriBuilder; @@ -182,28 +185,25 @@ public static class System { * @param url */ public System(final String url) - throws JAXBException - { + throws JAXBException { _dsDispatcher = new DSDispatcher(); _uriBuilder = new UriBuilder(); List _matrixParamSet; _matrixParamSet = _uriBuilder.addPathSegment(url); _matrixParamSet = _uriBuilder.addPathSegment("system"); - _templateAndMatrixParameterValues = new HashMap(); + _templateAndMatrixParameterValues = new HashMap<>(); } public DataSource getAsApplicationXml() - throws IOException, MalformedURLException - { - HashMap _queryParameterValues = new HashMap(); - HashMap _headerParameterValues = new HashMap(); + throws IOException, MalformedURLException { + HashMap _queryParameterValues = new HashMap<>(); + HashMap _headerParameterValues = new HashMap<>(); String _url = _uriBuilder.buildUri(_templateAndMatrixParameterValues, _queryParameterValues); DataSource _retVal = _dsDispatcher.doGET(_url, _headerParameterValues, "application/xml"); return _retVal; } public static class Configuration { - private JAXBDispatcher _jaxbDispatcher; private DSDispatcher _dsDispatcher; private UriBuilder _uriBuilder; @@ -216,39 +216,34 @@ public static class Configuration { * @param url */ public Configuration(final String url) - throws JAXBException - { + throws JAXBException { _dsDispatcher = new DSDispatcher(); _uriBuilder = new UriBuilder(); List _matrixParamSet; _matrixParamSet = _uriBuilder.addPathSegment(url); _matrixParamSet = _uriBuilder.addPathSegment("system"); _matrixParamSet = _uriBuilder.addPathSegment("configuration"); - _templateAndMatrixParameterValues = new HashMap(); + _templateAndMatrixParameterValues = new HashMap<>(); } - public DataSource postAsTextPlain(DataSource input) - throws IOException, MalformedURLException - { - HashMap _queryParameterValues = new HashMap(); - HashMap _headerParameterValues = new HashMap(); + public DataSource postAsTextPlain(DataSource input) throws IOException, MalformedURLException { + HashMap _queryParameterValues = new HashMap<>(); + HashMap _headerParameterValues = new HashMap<>(); String _url = _uriBuilder.buildUri(_templateAndMatrixParameterValues, _queryParameterValues); - DataSource _retVal = _dsDispatcher.doPOST(input, "application/xml", _url, _headerParameterValues, "text/plain"); + DataSource _retVal = + _dsDispatcher.doPOST(input, "application/xml", _url, _headerParameterValues, "text/plain"); return _retVal; } - public DataSource getAsApplicationXml() - throws IOException, MalformedURLException - { - HashMap _queryParameterValues = new HashMap(); - HashMap _headerParameterValues = new HashMap(); + public DataSource getAsApplicationXml() throws IOException, MalformedURLException { + HashMap _queryParameterValues = new HashMap<>(); + HashMap _headerParameterValues = new HashMap<>(); String _url = _uriBuilder.buildUri(_templateAndMatrixParameterValues, _queryParameterValues); DataSource _retVal = _dsDispatcher.doGET(_url, _headerParameterValues, "application/xml"); return _retVal; } public static class RemoteRepositories { - private JAXBDispatcher _jaxbDispatcher; private DSDispatcher _dsDispatcher; private UriBuilder _uriBuilder; @@ -261,8 +256,7 @@ public static class RemoteRepositories { * @param url */ public RemoteRepositories(final String url) - throws JAXBException - { + throws JAXBException { _dsDispatcher = new DSDispatcher(); _uriBuilder = new UriBuilder(); List _matrixParamSet; @@ -270,27 +264,23 @@ public RemoteRepositories(final String url) _matrixParamSet = _uriBuilder.addPathSegment("system"); _matrixParamSet = _uriBuilder.addPathSegment("configuration"); _matrixParamSet = _uriBuilder.addPathSegment("remoteRepositories"); - _templateAndMatrixParameterValues = new HashMap(); + _templateAndMatrixParameterValues = new HashMap<>(); } public void put(DataSource input) - throws IOException, MalformedURLException - { - HashMap _queryParameterValues = new HashMap(); - HashMap _headerParameterValues = new HashMap(); + throws IOException, MalformedURLException { + HashMap _queryParameterValues = new HashMap<>(); + HashMap _headerParameterValues = new HashMap<>(); String _url = _uriBuilder.buildUri(_templateAndMatrixParameterValues, _queryParameterValues); - DataSource _retVal = _dsDispatcher.doPUT(input, "application/xml", _url, _headerParameterValues, null); - return ; + DataSource _retVal = + _dsDispatcher.doPUT(input, "application/xml", _url, _headerParameterValues, null); + return; } - } - } - } public static class SystemVersion { - private JAXBDispatcher _jaxbDispatcher; private DSDispatcher _dsDispatcher; private UriBuilder _uriBuilder; @@ -303,118 +293,112 @@ public static class SystemVersion { * @param url */ public SystemVersion(final String url) - throws JAXBException - { + throws JAXBException { _dsDispatcher = new DSDispatcher(); _uriBuilder = new UriBuilder(); List _matrixParamSet; _matrixParamSet = _uriBuilder.addPathSegment(url); _matrixParamSet = _uriBuilder.addPathSegment("system/version"); - _templateAndMatrixParameterValues = new HashMap(); + _templateAndMatrixParameterValues = new HashMap<>(); } - public DataSource getSystemVersionJson() - throws IOException, MalformedURLException - { - HashMap _queryParameterValues = new HashMap(); - HashMap _headerParameterValues = new HashMap(); + public DataSource getSystemVersionJson() throws IOException, MalformedURLException { + HashMap _queryParameterValues = new HashMap<>(); + HashMap _headerParameterValues = new HashMap<>(); String _url = _uriBuilder.buildUri(_templateAndMatrixParameterValues, _queryParameterValues); - DataSource _retVal = _dsDispatcher.doGET(_url, _headerParameterValues, "application/vnd.org.jfrog.artifactory.system.Version+json"); + DataSource _retVal = + _dsDispatcher.doGET(_url, _headerParameterValues, "application/vnd.org.jfrog.artifactory.system.Version+json"); return _retVal; } } - /** - * @author Gregory.Shrago - */ - public static class Repositories { - - private JAXBDispatcher _jaxbDispatcher; - private DSDispatcher _dsDispatcher; - private UriBuilder _uriBuilder; - private JAXBContext _jc; - private HashMap _templateAndMatrixParameterValues; - - /** - * Create new instance - * - * @param url - */ - public Repositories(String url) - throws JAXBException - { - _dsDispatcher = new DSDispatcher(); - _uriBuilder = new UriBuilder(); - List _matrixParamSet; - _matrixParamSet = _uriBuilder.addPathSegment(url); - _matrixParamSet = _uriBuilder.addPathSegment("repositories"); - _templateAndMatrixParameterValues = new HashMap(); - } - - public DataSource getRepositoryDetailsListJson(String type) - throws IOException, MalformedURLException - { - HashMap _queryParameterValues = new HashMap(); - HashMap _headerParameterValues = new HashMap(); - _queryParameterValues.put("type", type); - String _url = _uriBuilder.buildUri(_templateAndMatrixParameterValues, _queryParameterValues); - DataSource _retVal = _dsDispatcher.doGET(_url, _headerParameterValues, "application/vnd.org.jfrog.artifactory.repositories.RepositoryDetailsList+json"); - return _retVal; - } - - public static class RepoKeyConfiguration { - - private JAXBDispatcher _jaxbDispatcher; - private DSDispatcher _dsDispatcher; - private UriBuilder _uriBuilder; - private JAXBContext _jc; - private HashMap _templateAndMatrixParameterValues; - - /** - * Create new instance - * - */ - public RepoKeyConfiguration(final String url, String repokey) - throws JAXBException - { - _dsDispatcher = new DSDispatcher(); - _uriBuilder = new UriBuilder(); - List _matrixParamSet; - _matrixParamSet = _uriBuilder.addPathSegment(url); - _matrixParamSet = _uriBuilder.addPathSegment("repositories"); - _matrixParamSet = _uriBuilder.addPathSegment("{repoKey}/configuration"); - _templateAndMatrixParameterValues = new HashMap(); - _templateAndMatrixParameterValues.put("repoKey", repokey); - } - - /** - * Get repoKey - * - */ - public String getRepoKey() { - return ((String) _templateAndMatrixParameterValues.get("repoKey")); - } - - /** - * Set repoKey - * - */ - public void setRepoKey(String repokey) { - _templateAndMatrixParameterValues.put("repoKey", repokey); - } - - public DataSource getAsApplicationVndOrgJfrogArtifactoryRepositoriesRepositoryConfigurationJson() - throws IOException, MalformedURLException - { - HashMap _queryParameterValues = new HashMap(); - HashMap _headerParameterValues = new HashMap(); - String _url = _uriBuilder.buildUri(_templateAndMatrixParameterValues, _queryParameterValues); - DataSource _retVal = _dsDispatcher.doGET(_url, _headerParameterValues, "application/vnd.org.jfrog.artifactory.repositories.RepositoryConfiguration+json"); - return _retVal; - } - - } - - } + /** + * @author Gregory.Shrago + */ + public static class Repositories { + private JAXBDispatcher _jaxbDispatcher; + private DSDispatcher _dsDispatcher; + private UriBuilder _uriBuilder; + private JAXBContext _jc; + private HashMap _templateAndMatrixParameterValues; + + /** + * Create new instance + * + * @param url + */ + public Repositories(String url) + throws JAXBException { + _dsDispatcher = new DSDispatcher(); + _uriBuilder = new UriBuilder(); + List _matrixParamSet; + _matrixParamSet = _uriBuilder.addPathSegment(url); + _matrixParamSet = _uriBuilder.addPathSegment("repositories"); + _templateAndMatrixParameterValues = new HashMap<>(); + } + + public DataSource getRepositoryDetailsListJson(String type) throws IOException, MalformedURLException { + HashMap _queryParameterValues = new HashMap<>(); + HashMap _headerParameterValues = new HashMap<>(); + _queryParameterValues.put("type", type); + String _url = _uriBuilder.buildUri(_templateAndMatrixParameterValues, _queryParameterValues); + DataSource _retVal = _dsDispatcher.doGET( + _url, + _headerParameterValues, + "application/vnd.org.jfrog.artifactory.repositories.RepositoryDetailsList+json" + ); + return _retVal; + } + + public static class RepoKeyConfiguration { + private JAXBDispatcher _jaxbDispatcher; + private DSDispatcher _dsDispatcher; + private UriBuilder _uriBuilder; + private JAXBContext _jc; + private HashMap _templateAndMatrixParameterValues; + + /** + * Create new instance + */ + public RepoKeyConfiguration(final String url, String repokey) + throws JAXBException { + _dsDispatcher = new DSDispatcher(); + _uriBuilder = new UriBuilder(); + List _matrixParamSet; + _matrixParamSet = _uriBuilder.addPathSegment(url); + _matrixParamSet = _uriBuilder.addPathSegment("repositories"); + _matrixParamSet = _uriBuilder.addPathSegment("{repoKey}/configuration"); + _templateAndMatrixParameterValues = new HashMap<>(); + _templateAndMatrixParameterValues.put("repoKey", repokey); + } + + /** + * Get repoKey + */ + public String getRepoKey() { + return ((String)_templateAndMatrixParameterValues.get("repoKey")); + } + + /** + * Set repoKey + */ + public void setRepoKey(String repokey) { + _templateAndMatrixParameterValues.put("repoKey", repokey); + } + + public DataSource getAsApplicationVndOrgJfrogArtifactoryRepositoriesRepositoryConfigurationJson() + throws IOException, MalformedURLException { + HashMap _queryParameterValues = new HashMap<>(); + HashMap _headerParameterValues = new HashMap<>(); + String _url = _uriBuilder.buildUri(_templateAndMatrixParameterValues, _queryParameterValues); + DataSource _retVal = _dsDispatcher.doGET( + _url, + _headerParameterValues, + "application/vnd.org.jfrog.artifactory.repositories.RepositoryConfiguration+json" + ); + return _retVal; + } + } + } } diff --git a/plugin/src/main/java/org/jetbrains/idea/maven/services/nexus/ArtifactType.java b/plugin/src/main/java/org/jetbrains/idea/maven/services/nexus/ArtifactType.java index 99f88366..292d0847 100644 --- a/plugin/src/main/java/org/jetbrains/idea/maven/services/nexus/ArtifactType.java +++ b/plugin/src/main/java/org/jetbrains/idea/maven/services/nexus/ArtifactType.java @@ -19,6 +19,7 @@ import jakarta.xml.bind.annotation.XmlAccessorType; import jakarta.xml.bind.annotation.XmlElement; import jakarta.xml.bind.annotation.XmlType; + import java.io.Serializable; @@ -51,275 +52,274 @@ */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "artifactType", propOrder = { - "resourceUri", - "groupId", - "artifactId", - "version", - "classifier", - "packaging", - "extension", - "repoId", - "contextId", - "pomLink", - "artifactLink" + "resourceUri", + "groupId", + "artifactId", + "version", + "classifier", + "packaging", + "extension", + "repoId", + "contextId", + "pomLink", + "artifactLink" }) public class ArtifactType implements Serializable { + @XmlElement(required = true) + protected String resourceUri; + @XmlElement(required = true) + protected String groupId; + @XmlElement(required = true) + protected String artifactId; + @XmlElement(required = true) + protected String version; + @XmlElement(required = true) + protected String classifier; + @XmlElement(required = true) + protected String packaging; + @XmlElement(required = true) + protected String extension; + @XmlElement(required = true) + protected String repoId; + @XmlElement(required = true) + protected String contextId; + @XmlElement(required = true) + protected String pomLink; + @XmlElement(required = true) + protected String artifactLink; - @XmlElement(required = true) - protected String resourceUri; - @XmlElement(required = true) - protected String groupId; - @XmlElement(required = true) - protected String artifactId; - @XmlElement(required = true) - protected String version; - @XmlElement(required = true) - protected String classifier; - @XmlElement(required = true) - protected String packaging; - @XmlElement(required = true) - protected String extension; - @XmlElement(required = true) - protected String repoId; - @XmlElement(required = true) - protected String contextId; - @XmlElement(required = true) - protected String pomLink; - @XmlElement(required = true) - protected String artifactLink; - - public ArtifactType() { + public ArtifactType() { - } + } - public ArtifactType(String groupId, String artifactId, String version) { - this.groupId = groupId; - this.artifactId = artifactId; - this.version = version; - } + public ArtifactType(String groupId, String artifactId, String version) { + this.groupId = groupId; + this.artifactId = artifactId; + this.version = version; + } - /** - * Gets the value of the resourceUri property. - * - * @return possible object is - * {@link String } - */ - public String getResourceUri() { - return resourceUri; - } + /** + * Gets the value of the resourceUri property. + * + * @return possible object is + * {@link String } + */ + public String getResourceUri() { + return resourceUri; + } - /** - * Sets the value of the resourceUri property. - * - * @param value allowed object is - * {@link String } - */ - public void setResourceUri(String value) { - this.resourceUri = value; - } + /** + * Sets the value of the resourceUri property. + * + * @param value allowed object is + * {@link String } + */ + public void setResourceUri(String value) { + this.resourceUri = value; + } - /** - * Gets the value of the groupId property. - * - * @return possible object is - * {@link String } - */ - public String getGroupId() { - return groupId; - } + /** + * Gets the value of the groupId property. + * + * @return possible object is + * {@link String } + */ + public String getGroupId() { + return groupId; + } - /** - * Sets the value of the groupId property. - * - * @param value allowed object is - * {@link String } - */ - public void setGroupId(String value) { - this.groupId = value; - } + /** + * Sets the value of the groupId property. + * + * @param value allowed object is + * {@link String } + */ + public void setGroupId(String value) { + this.groupId = value; + } - /** - * Gets the value of the artifactId property. - * - * @return possible object is - * {@link String } - */ - public String getArtifactId() { - return artifactId; - } + /** + * Gets the value of the artifactId property. + * + * @return possible object is + * {@link String } + */ + public String getArtifactId() { + return artifactId; + } - /** - * Sets the value of the artifactId property. - * - * @param value allowed object is - * {@link String } - */ - public void setArtifactId(String value) { - this.artifactId = value; - } + /** + * Sets the value of the artifactId property. + * + * @param value allowed object is + * {@link String } + */ + public void setArtifactId(String value) { + this.artifactId = value; + } - /** - * Gets the value of the version property. - * - * @return possible object is - * {@link String } - */ - public String getVersion() { - return version; - } + /** + * Gets the value of the version property. + * + * @return possible object is + * {@link String } + */ + public String getVersion() { + return version; + } - /** - * Sets the value of the version property. - * - * @param value allowed object is - * {@link String } - */ - public void setVersion(String value) { - this.version = value; - } + /** + * Sets the value of the version property. + * + * @param value allowed object is + * {@link String } + */ + public void setVersion(String value) { + this.version = value; + } - /** - * Gets the value of the classifier property. - * - * @return possible object is - * {@link String } - */ - public String getClassifier() { - return classifier; - } + /** + * Gets the value of the classifier property. + * + * @return possible object is + * {@link String } + */ + public String getClassifier() { + return classifier; + } - /** - * Sets the value of the classifier property. - * - * @param value allowed object is - * {@link String } - */ - public void setClassifier(String value) { - this.classifier = value; - } + /** + * Sets the value of the classifier property. + * + * @param value allowed object is + * {@link String } + */ + public void setClassifier(String value) { + this.classifier = value; + } - /** - * Gets the value of the packaging property. - * - * @return possible object is - * {@link String } - */ - public String getPackaging() { - return packaging; - } + /** + * Gets the value of the packaging property. + * + * @return possible object is + * {@link String } + */ + public String getPackaging() { + return packaging; + } - /** - * Sets the value of the packaging property. - * - * @param value allowed object is - * {@link String } - */ - public void setPackaging(String value) { - this.packaging = value; - } + /** + * Sets the value of the packaging property. + * + * @param value allowed object is + * {@link String } + */ + public void setPackaging(String value) { + this.packaging = value; + } - /** - * Gets the value of the extension property. - * - * @return possible object is - * {@link String } - */ - public String getExtension() { - return extension; - } + /** + * Gets the value of the extension property. + * + * @return possible object is + * {@link String } + */ + public String getExtension() { + return extension; + } - /** - * Sets the value of the extension property. - * - * @param value allowed object is - * {@link String } - */ - public void setExtension(String value) { - this.extension = value; - } + /** + * Sets the value of the extension property. + * + * @param value allowed object is + * {@link String } + */ + public void setExtension(String value) { + this.extension = value; + } - /** - * Gets the value of the repoId property. - * - * @return possible object is - * {@link String } - */ - public String getRepoId() { - return repoId; - } + /** + * Gets the value of the repoId property. + * + * @return possible object is + * {@link String } + */ + public String getRepoId() { + return repoId; + } - /** - * Sets the value of the repoId property. - * - * @param value allowed object is - * {@link String } - */ - public void setRepoId(String value) { - this.repoId = value; - } + /** + * Sets the value of the repoId property. + * + * @param value allowed object is + * {@link String } + */ + public void setRepoId(String value) { + this.repoId = value; + } - /** - * Gets the value of the contextId property. - * - * @return possible object is - * {@link String } - */ - public String getContextId() { - return contextId; - } + /** + * Gets the value of the contextId property. + * + * @return possible object is + * {@link String } + */ + public String getContextId() { + return contextId; + } - /** - * Sets the value of the contextId property. - * - * @param value allowed object is - * {@link String } - */ - public void setContextId(String value) { - this.contextId = value; - } + /** + * Sets the value of the contextId property. + * + * @param value allowed object is + * {@link String } + */ + public void setContextId(String value) { + this.contextId = value; + } - /** - * Gets the value of the pomLink property. - * - * @return possible object is - * {@link String } - */ - public String getPomLink() { - return pomLink; - } + /** + * Gets the value of the pomLink property. + * + * @return possible object is + * {@link String } + */ + public String getPomLink() { + return pomLink; + } - /** - * Sets the value of the pomLink property. - * - * @param value allowed object is - * {@link String } - */ - public void setPomLink(String value) { - this.pomLink = value; - } + /** + * Sets the value of the pomLink property. + * + * @param value allowed object is + * {@link String } + */ + public void setPomLink(String value) { + this.pomLink = value; + } - /** - * Gets the value of the artifactLink property. - * - * @return possible object is - * {@link String } - */ - public String getArtifactLink() { - return artifactLink; - } + /** + * Gets the value of the artifactLink property. + * + * @return possible object is + * {@link String } + */ + public String getArtifactLink() { + return artifactLink; + } - /** - * Sets the value of the artifactLink property. - * - * @param value allowed object is - * {@link String } - */ - public void setArtifactLink(String value) { - this.artifactLink = value; - } + /** + * Sets the value of the artifactLink property. + * + * @param value allowed object is + * {@link String } + */ + public void setArtifactLink(String value) { + this.artifactLink = value; + } - @Override - public String toString() { - return groupId + ":" + artifactId + ":" + version; - } + @Override + public String toString() { + return groupId + ":" + artifactId + ":" + version; + } } diff --git a/plugin/src/main/java/org/jetbrains/idea/maven/services/nexus/Endpoint.java b/plugin/src/main/java/org/jetbrains/idea/maven/services/nexus/Endpoint.java index 080a010f..647bbcab 100644 --- a/plugin/src/main/java/org/jetbrains/idea/maven/services/nexus/Endpoint.java +++ b/plugin/src/main/java/org/jetbrains/idea/maven/services/nexus/Endpoint.java @@ -24,16 +24,14 @@ import consulo.maven.internal.org.jvnet.ws.wadl.util.UriBuilder; import jakarta.activation.DataSource; + import java.io.IOException; import java.net.MalformedURLException; import java.util.HashMap; import java.util.List; public class Endpoint { - - public static class DataIndex { - private JAXBDispatcher _jaxbDispatcher; private DSDispatcher _dsDispatcher; private UriBuilder _uriBuilder; @@ -45,9 +43,7 @@ public static class DataIndex { * * @param nexusRoot */ - public DataIndex(final String nexusRoot) - throws JAXBException - { + public DataIndex(final String nexusRoot) throws JAXBException { _jc = JAXBContext.newInstance("org.jetbrains.idea.maven.services.nexus", getClass().getClassLoader()); _jaxbDispatcher = new JAXBDispatcher(_jc); _dsDispatcher = new DSDispatcher(); @@ -55,41 +51,36 @@ public DataIndex(final String nexusRoot) List _matrixParamSet; _matrixParamSet = _uriBuilder.addPathSegment(nexusRoot); _matrixParamSet = _uriBuilder.addPathSegment("data_index"); - _templateAndMatrixParameterValues = new HashMap(); + _templateAndMatrixParameterValues = new HashMap<>(); } - public DataSource getArtifactlistAsApplicationXml() - throws IOException, MalformedURLException - { - HashMap _queryParameterValues = new HashMap(); - HashMap _headerParameterValues = new HashMap(); + public DataSource getArtifactlistAsApplicationXml() throws IOException, MalformedURLException { + HashMap _queryParameterValues = new HashMap<>(); + HashMap _headerParameterValues = new HashMap<>(); String _url = _uriBuilder.buildUri(_templateAndMatrixParameterValues, _queryParameterValues); DataSource _retVal = _dsDispatcher.doGET(_url, _headerParameterValues, "application/xml"); return _retVal; } - public SearchResults getArtifactlistAsSearchResults() - throws IOException, MalformedURLException, JAXBException - { - HashMap _queryParameterValues = new HashMap(); - HashMap _headerParameterValues = new HashMap(); + public SearchResults getArtifactlistAsSearchResults() throws IOException, MalformedURLException, JAXBException { + HashMap _queryParameterValues = new HashMap<>(); + HashMap _headerParameterValues = new HashMap<>(); String _url = _uriBuilder.buildUri(_templateAndMatrixParameterValues, _queryParameterValues); Object _retVal = _jaxbDispatcher.doGET(_url, _headerParameterValues, "application/xml"); if (_retVal == null) { return null; } if (JAXBElement.class.isInstance(_retVal)) { - JAXBElement jaxbElement = ((JAXBElement) _retVal); + JAXBElement jaxbElement = ((JAXBElement)_retVal); _retVal = jaxbElement.getValue(); } - return ((SearchResults) _retVal); + return ((SearchResults)_retVal); } public DataSource getArtifactlistAsApplicationXml(String q, String g, String a, String v, String c) - throws IOException, MalformedURLException - { - HashMap _queryParameterValues = new HashMap(); - HashMap _headerParameterValues = new HashMap(); + throws IOException, MalformedURLException { + HashMap _queryParameterValues = new HashMap<>(); + HashMap _headerParameterValues = new HashMap<>(); _queryParameterValues.put("q", q); _queryParameterValues.put("g", g); _queryParameterValues.put("a", a); @@ -101,10 +92,9 @@ public DataSource getArtifactlistAsApplicationXml(String q, String g, String a, } public SearchResults getArtifactlistAsSearchResults(String q, String g, String a, String v, String c, String cn) - throws IOException, MalformedURLException, JAXBException - { - HashMap _queryParameterValues = new HashMap(); - HashMap _headerParameterValues = new HashMap(); + throws IOException, MalformedURLException, JAXBException { + HashMap _queryParameterValues = new HashMap<>(); + HashMap _headerParameterValues = new HashMap<>(); _queryParameterValues.put("q", q); _queryParameterValues.put("g", g); _queryParameterValues.put("a", a); @@ -117,16 +107,15 @@ public SearchResults getArtifactlistAsSearchResults(String q, String g, String a return null; } if (JAXBElement.class.isInstance(_retVal)) { - JAXBElement jaxbElement = ((JAXBElement) _retVal); + JAXBElement jaxbElement = ((JAXBElement)_retVal); _retVal = jaxbElement.getValue(); } - return ((SearchResults) _retVal); + return ((SearchResults)_retVal); } } public static class DataIndexRepository { - private JAXBDispatcher _jaxbDispatcher; private DSDispatcher _dsDispatcher; private UriBuilder _uriBuilder; @@ -135,11 +124,8 @@ public static class DataIndexRepository { /** * Create new instance - * */ - public DataIndexRepository(String repository) - throws JAXBException - { + public DataIndexRepository(String repository) throws JAXBException { _jc = JAXBContext.newInstance("org.jetbrains.idea.maven.services.nexus", getClass().getClassLoader()); _jaxbDispatcher = new JAXBDispatcher(_jc); _dsDispatcher = new DSDispatcher(); @@ -153,52 +139,45 @@ public DataIndexRepository(String repository) /** * Get repository - * */ public String getRepository() { - return ((String) _templateAndMatrixParameterValues.get("repository")); + return ((String)_templateAndMatrixParameterValues.get("repository")); } /** * Set repository - * */ public void setRepository(String repository) { _templateAndMatrixParameterValues.put("repository", repository); } - public DataSource getArtifactlistAsApplicationXml() - throws IOException, MalformedURLException - { - HashMap _queryParameterValues = new HashMap(); - HashMap _headerParameterValues = new HashMap(); + public DataSource getArtifactlistAsApplicationXml() throws IOException, MalformedURLException { + HashMap _queryParameterValues = new HashMap<>(); + HashMap _headerParameterValues = new HashMap<>(); String _url = _uriBuilder.buildUri(_templateAndMatrixParameterValues, _queryParameterValues); DataSource _retVal = _dsDispatcher.doGET(_url, _headerParameterValues, "application/xml"); return _retVal; } - public SearchResults getArtifactlistAsSearchResults() - throws IOException, MalformedURLException, JAXBException - { - HashMap _queryParameterValues = new HashMap(); - HashMap _headerParameterValues = new HashMap(); + public SearchResults getArtifactlistAsSearchResults() throws IOException, MalformedURLException, JAXBException { + HashMap _queryParameterValues = new HashMap<>(); + HashMap _headerParameterValues = new HashMap<>(); String _url = _uriBuilder.buildUri(_templateAndMatrixParameterValues, _queryParameterValues); Object _retVal = _jaxbDispatcher.doGET(_url, _headerParameterValues, "application/xml"); if (_retVal == null) { return null; } if (JAXBElement.class.isInstance(_retVal)) { - JAXBElement jaxbElement = ((JAXBElement) _retVal); + JAXBElement jaxbElement = ((JAXBElement)_retVal); _retVal = jaxbElement.getValue(); } - return ((SearchResults) _retVal); + return ((SearchResults)_retVal); } public DataSource getArtifactlistAsApplicationXml(String q, String g, String a, String v, String c) - throws IOException, MalformedURLException - { - HashMap _queryParameterValues = new HashMap(); - HashMap _headerParameterValues = new HashMap(); + throws IOException, MalformedURLException { + HashMap _queryParameterValues = new HashMap<>(); + HashMap _headerParameterValues = new HashMap<>(); _queryParameterValues.put("q", q); _queryParameterValues.put("g", g); _queryParameterValues.put("a", a); @@ -210,10 +189,9 @@ public DataSource getArtifactlistAsApplicationXml(String q, String g, String a, } public SearchResults getArtifactlistAsSearchResults(String q, String g, String a, String v, String c) - throws IOException, MalformedURLException, JAXBException - { - HashMap _queryParameterValues = new HashMap(); - HashMap _headerParameterValues = new HashMap(); + throws IOException, MalformedURLException, JAXBException { + HashMap _queryParameterValues = new HashMap<>(); + HashMap _headerParameterValues = new HashMap<>(); _queryParameterValues.put("q", q); _queryParameterValues.put("g", g); _queryParameterValues.put("a", a); @@ -225,10 +203,10 @@ public SearchResults getArtifactlistAsSearchResults(String q, String g, String a return null; } if (JAXBElement.class.isInstance(_retVal)) { - JAXBElement jaxbElement = ((JAXBElement) _retVal); + JAXBElement jaxbElement = ((JAXBElement)_retVal); _retVal = jaxbElement.getValue(); } - return ((SearchResults) _retVal); + return ((SearchResults)_retVal); } } @@ -247,8 +225,7 @@ public static class Repositories { * @param url */ public Repositories(String url) - throws JAXBException - { + throws JAXBException { _jc = JAXBContext.newInstance("org.jetbrains.idea.maven.services.nexus", getClass().getClassLoader()); _jaxbDispatcher = new JAXBDispatcher(_jc); _dsDispatcher = new DSDispatcher(); @@ -256,34 +233,31 @@ public Repositories(String url) List _matrixParamSet; _matrixParamSet = _uriBuilder.addPathSegment(url); _matrixParamSet = _uriBuilder.addPathSegment("repositories"); - _templateAndMatrixParameterValues = new HashMap(); + _templateAndMatrixParameterValues = new HashMap<>(); } - public DataSource getRepolistAsApplicationXml() - throws IOException, MalformedURLException - { - HashMap _queryParameterValues = new HashMap(); - HashMap _headerParameterValues = new HashMap(); + public DataSource getRepolistAsApplicationXml() throws IOException, MalformedURLException { + HashMap _queryParameterValues = new HashMap<>(); + HashMap _headerParameterValues = new HashMap<>(); String _url = _uriBuilder.buildUri(_templateAndMatrixParameterValues, _queryParameterValues); DataSource _retVal = _dsDispatcher.doGET(_url, _headerParameterValues, "application/xml"); return _retVal; } public org.jetbrains.idea.maven.services.nexus.Repositories getRepolistAsRepositories() - throws IOException, MalformedURLException, JAXBException - { - HashMap _queryParameterValues = new HashMap(); - HashMap _headerParameterValues = new HashMap(); + throws IOException, MalformedURLException, JAXBException { + HashMap _queryParameterValues = new HashMap<>(); + HashMap _headerParameterValues = new HashMap<>(); String _url = _uriBuilder.buildUri(_templateAndMatrixParameterValues, _queryParameterValues); Object _retVal = _jaxbDispatcher.doGET(_url, _headerParameterValues, "application/xml"); if (_retVal == null) { return null; } if (JAXBElement.class.isInstance(_retVal)) { - JAXBElement jaxbElement = ((JAXBElement) _retVal); + JAXBElement jaxbElement = ((JAXBElement)_retVal); _retVal = jaxbElement.getValue(); } - return ((org.jetbrains.idea.maven.services.nexus.Repositories) _retVal); + return ((org.jetbrains.idea.maven.services.nexus.Repositories)_retVal); } } diff --git a/plugin/src/main/java/org/jetbrains/idea/maven/services/nexus/NexusRepositoryService.java b/plugin/src/main/java/org/jetbrains/idea/maven/services/nexus/NexusRepositoryService.java index 4c25dc28..237e9202 100644 --- a/plugin/src/main/java/org/jetbrains/idea/maven/services/nexus/NexusRepositoryService.java +++ b/plugin/src/main/java/org/jetbrains/idea/maven/services/nexus/NexusRepositoryService.java @@ -34,71 +34,85 @@ * @author Gregory.Shrago */ public class NexusRepositoryService extends MavenRepositoryService { - public static MavenRepositoryInfo convertRepositoryInfo(RepositoryType repo) { - return new MavenRepositoryInfo(repo.getId(), repo.getName(), repo.getContentResourceURI()); - } - - public static MavenArtifactInfo convertArtifactInfo(ArtifactType t) { - return new MavenArtifactInfo(t.getGroupId(), - t.getArtifactId(), - t.getVersion(), - t.getPackaging(), - t.getClassifier(), - null, - t.getRepoId()); - } - - @Nonnull - @Override - public String getDisplayName() { - return "Nexus"; - } - - @Nonnull - @Override - public List getRepositories(@Nonnull String url) throws IOException { - try { - List repos = new Endpoint.Repositories(url).getRepolistAsRepositories().getData().getRepositoriesItem(); - List result = new ArrayList(repos.size()); - for (RepositoryType repo : repos) { - if (!"maven2".equals(repo.getProvider())) continue; - result.add(convertRepositoryInfo(repo)); - } - return result; + public static MavenRepositoryInfo convertRepositoryInfo(RepositoryType repo) { + return new MavenRepositoryInfo(repo.getId(), repo.getName(), repo.getContentResourceURI()); } - catch (UnmarshalException e) { - return Collections.emptyList(); + + public static MavenArtifactInfo convertArtifactInfo(ArtifactType t) { + return new MavenArtifactInfo( + t.getGroupId(), + t.getArtifactId(), + t.getVersion(), + t.getPackaging(), + t.getClassifier(), + null, + t.getRepoId() + ); } - catch (JAXBException e) { - throw new IOException(e); + + @Nonnull + @Override + public String getDisplayName() { + return "Nexus"; } - } - @Nonnull - @Override - public List findArtifacts(@Nonnull String url, @Nonnull MavenArtifactInfo template) throws IOException { - try { - final String packaging = StringUtil.notNullize(template.getPackaging()); - final String name = StringUtil.join(Arrays.asList(template.getGroupId(), template.getArtifactId(), template.getVersion()), ":"); - final SearchResults results = new Endpoint.DataIndex(url).getArtifactlistAsSearchResults( - name, template.getGroupId(), template.getArtifactId(), template.getVersion(), null, template.getClassNames()); - boolean tooManyResults = results.isTooManyResults(); - final SearchResults.Data data = results.getData(); - final ArrayList result = new ArrayList(); - if (data != null) { - for (ArtifactType each : data.getArtifact()) { - if (!Comparing.equal(each.packaging, packaging)) continue; - result.add(convertArtifactInfo(each)); + @Nonnull + @Override + public List getRepositories(@Nonnull String url) throws IOException { + try { + List repos = new Endpoint.Repositories(url).getRepolistAsRepositories().getData().getRepositoriesItem(); + List result = new ArrayList<>(repos.size()); + for (RepositoryType repo : repos) { + if (!"maven2".equals(repo.getProvider())) { + continue; + } + result.add(convertRepositoryInfo(repo)); + } + return result; + } + catch (UnmarshalException e) { + return Collections.emptyList(); + } + catch (JAXBException e) { + throw new IOException(e); } - } - if (tooManyResults) result.add(null); - return result; - } - catch (UnmarshalException e) { - return Collections.emptyList(); } - catch (JAXBException e) { - throw new IOException(e); + + @Nonnull + @Override + public List findArtifacts(@Nonnull String url, @Nonnull MavenArtifactInfo template) throws IOException { + try { + final String packaging = StringUtil.notNullize(template.getPackaging()); + final String name = StringUtil.join(Arrays.asList(template.getGroupId(), template.getArtifactId(), template.getVersion()), ":"); + final SearchResults results = new Endpoint.DataIndex(url).getArtifactlistAsSearchResults( + name, + template.getGroupId(), + template.getArtifactId(), + template.getVersion(), + null, + template.getClassNames() + ); + boolean tooManyResults = results.isTooManyResults(); + final SearchResults.Data data = results.getData(); + final ArrayList result = new ArrayList<>(); + if (data != null) { + for (ArtifactType each : data.getArtifact()) { + if (!Comparing.equal(each.packaging, packaging)) { + continue; + } + result.add(convertArtifactInfo(each)); + } + } + if (tooManyResults) { + result.add(null); + } + return result; + } + catch (UnmarshalException e) { + return Collections.emptyList(); + } + catch (JAXBException e) { + throw new IOException(e); + } } - } } diff --git a/plugin/src/main/java/org/jetbrains/idea/maven/services/nexus/ObjectFactory.java b/plugin/src/main/java/org/jetbrains/idea/maven/services/nexus/ObjectFactory.java index 32a83eb4..c522867d 100644 --- a/plugin/src/main/java/org/jetbrains/idea/maven/services/nexus/ObjectFactory.java +++ b/plugin/src/main/java/org/jetbrains/idea/maven/services/nexus/ObjectFactory.java @@ -1,18 +1,18 @@ /* -* Copyright 2000-2010 JetBrains s.r.o. -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ + * Copyright 2000-2010 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.jetbrains.idea.maven.services.nexus; import consulo.maven.rt.server.common.model.MavenArtifactInfo; @@ -20,7 +20,6 @@ import jakarta.xml.bind.annotation.XmlRegistry; - /** * This object contains factory methods for each * Java content interface and Java element interface @@ -36,60 +35,58 @@ */ @XmlRegistry public class ObjectFactory { + /** + * Create a new ObjectFactory that can be used to create new instances of schema derived classes for package: nexus + */ + public ObjectFactory() { + } + /** + * Create an instance of {@link Repositories } + */ + public Repositories createRepositories() { + return new Repositories(); + } - /** - * Create a new ObjectFactory that can be used to create new instances of schema derived classes for package: nexus - */ - public ObjectFactory() { - } - - /** - * Create an instance of {@link Repositories } - */ - public Repositories createRepositories() { - return new Repositories(); - } - - /** - * Create an instance of {@link RepositoryMetaData } - */ - public RepositoryMetaData createRepositoryMetaData() { - return new RepositoryMetaData(); - } + /** + * Create an instance of {@link RepositoryMetaData } + */ + public RepositoryMetaData createRepositoryMetaData() { + return new RepositoryMetaData(); + } - /** - * Create an instance of {@link SearchResults } - */ - public SearchResults createSearchResults() { - return new SearchResults(); - } + /** + * Create an instance of {@link SearchResults } + */ + public SearchResults createSearchResults() { + return new SearchResults(); + } - /** - * Create an instance of {@link MavenRepositoryInfo } - */ - public RepositoryType createRepositoryType() { - return new RepositoryType(); - } + /** + * Create an instance of {@link MavenRepositoryInfo } + */ + public RepositoryType createRepositoryType() { + return new RepositoryType(); + } - /** - * Create an instance of {@link MavenArtifactInfo } - */ - public ArtifactType createArtifactType() { - return new ArtifactType(); - } + /** + * Create an instance of {@link MavenArtifactInfo } + */ + public ArtifactType createArtifactType() { + return new ArtifactType(); + } - /** - * Create an instance of {@link Repositories.Data } - */ - public Repositories.Data createRepositoriesData() { - return new Repositories.Data(); - } + /** + * Create an instance of {@link Repositories.Data } + */ + public Repositories.Data createRepositoriesData() { + return new Repositories.Data(); + } - /** - * Create an instance of {@link SearchResults.Data } - */ - public SearchResults.Data createSearchResultsData() { - return new SearchResults.Data(); - } + /** + * Create an instance of {@link SearchResults.Data } + */ + public SearchResults.Data createSearchResultsData() { + return new SearchResults.Data(); + } } diff --git a/plugin/src/main/java/org/jetbrains/idea/maven/services/nexus/Repositories.java b/plugin/src/main/java/org/jetbrains/idea/maven/services/nexus/Repositories.java index 393d834a..5b1efe12 100644 --- a/plugin/src/main/java/org/jetbrains/idea/maven/services/nexus/Repositories.java +++ b/plugin/src/main/java/org/jetbrains/idea/maven/services/nexus/Repositories.java @@ -19,15 +19,15 @@ import consulo.maven.rt.server.common.model.MavenRepositoryInfo; import jakarta.xml.bind.annotation.*; + import java.util.ArrayList; import java.util.List; - /** *

Java class for anonymous complex type. - * + * *

The following schema fragment specifies the expected content contained within this class. - * + * *

  * <complexType>
  *   <complexContent>
@@ -49,26 +49,18 @@
  *   </complexContent>
  * </complexType>
  * 
- * - * */ @XmlAccessorType(XmlAccessType.FIELD) -@XmlType(name = "", propOrder = { - "data" -}) +@XmlType(name = "", propOrder = {"data"}) @XmlRootElement(name = "repositories") public class Repositories { - @XmlElement(required = true) protected Repositories.Data data; /** * Gets the value of the data property. - * - * @return - * possible object is - * {@link Repositories.Data } - * + * + * @return possible object is {@link Repositories.Data } */ public Repositories.Data getData() { return data; @@ -76,22 +68,18 @@ public Repositories.Data getData() { /** * Sets the value of the data property. - * - * @param value - * allowed object is - * {@link Repositories.Data } - * + * + * @param value allowed object is {@link Repositories.Data } */ public void setData(Repositories.Data value) { this.data = value; } - /** *

Java class for anonymous complex type. - * + * *

The following schema fragment specifies the expected content contained within this class. - * + * *

      * <complexType>
      *   <complexContent>
@@ -103,47 +91,38 @@ public void setData(Repositories.Data value) {
      *   </complexContent>
      * </complexType>
      * 
- * - * */ @XmlAccessorType(XmlAccessType.FIELD) - @XmlType(name = "", propOrder = { - "repositoriesItem" - }) + @XmlType(name = "", propOrder = {"repositoriesItem"}) public static class Data { - @XmlElement(name = "repositories-item") protected List repositoriesItem; /** * Gets the value of the repositoriesItem property. - * + * *

* This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a set method for the repositoriesItem property. - * + * *

* For example, to add a new item, do as follows: *

          *    getRepositoriesItem().add(newItem);
          * 
- * - * + * + * *

* Objects of the following type(s) are allowed in the list * {@link MavenRepositoryInfo } - * - * */ public List getRepositoriesItem() { if (repositoriesItem == null) { - repositoriesItem = new ArrayList(); + repositoriesItem = new ArrayList<>(); } return this.repositoriesItem; } - } - } diff --git a/plugin/src/main/java/org/jetbrains/idea/maven/services/nexus/RepositoryMetaData.java b/plugin/src/main/java/org/jetbrains/idea/maven/services/nexus/RepositoryMetaData.java index 5a78f604..4f2b1586 100644 --- a/plugin/src/main/java/org/jetbrains/idea/maven/services/nexus/RepositoryMetaData.java +++ b/plugin/src/main/java/org/jetbrains/idea/maven/services/nexus/RepositoryMetaData.java @@ -17,14 +17,14 @@ package org.jetbrains.idea.maven.services.nexus; import jakarta.xml.bind.annotation.*; -import java.math.BigInteger; +import java.math.BigInteger; /** *

Java class for anonymous complex type. - * + * *

The following schema fragment specifies the expected content contained within this class. - * + * *

  * <complexType>
  *   <complexContent>
@@ -41,8 +41,6 @@
  *   </complexContent>
  * </complexType>
  * 
- * - * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { @@ -55,7 +53,6 @@ }) @XmlRootElement(name = "repositoryMetaData") public class RepositoryMetaData { - @XmlElement(required = true) protected String id; @XmlElement(required = true) @@ -71,11 +68,8 @@ public class RepositoryMetaData { /** * Gets the value of the id property. - * - * @return - * possible object is - * {@link String } - * + * + * @return possible object is {@link String} */ public String getId() { return id; @@ -83,11 +77,8 @@ public String getId() { /** * Sets the value of the id property. - * - * @param value - * allowed object is - * {@link String } - * + * + * @param value allowed object is {@link String} */ public void setId(String value) { this.id = value; @@ -95,11 +86,8 @@ public void setId(String value) { /** * Gets the value of the repoType property. - * - * @return - * possible object is - * {@link String } - * + * + * @return possible object is {@link String} */ public String getRepoType() { return repoType; @@ -107,11 +95,8 @@ public String getRepoType() { /** * Sets the value of the repoType property. - * - * @param value - * allowed object is - * {@link String } - * + * + * @param value allowed object is {@link String} */ public void setRepoType(String value) { this.repoType = value; @@ -119,11 +104,8 @@ public void setRepoType(String value) { /** * Gets the value of the effectiveLocalStorageUrl property. - * - * @return - * possible object is - * {@link String } - * + * + * @return possible object is {@link String} */ public String getEffectiveLocalStorageUrl() { return effectiveLocalStorageUrl; @@ -131,11 +113,8 @@ public String getEffectiveLocalStorageUrl() { /** * Sets the value of the effectiveLocalStorageUrl property. - * - * @param value - * allowed object is - * {@link String } - * + * + * @param value allowed object is {@link String} */ public void setEffectiveLocalStorageUrl(String value) { this.effectiveLocalStorageUrl = value; @@ -143,11 +122,8 @@ public void setEffectiveLocalStorageUrl(String value) { /** * Gets the value of the proxyUrl property. - * - * @return - * possible object is - * {@link String } - * + * + * @return possible object is {@link String} */ public String getProxyUrl() { return proxyUrl; @@ -155,11 +131,8 @@ public String getProxyUrl() { /** * Sets the value of the proxyUrl property. - * - * @param value - * allowed object is - * {@link String } - * + * + * @param value allowed object is {@link String} */ public void setProxyUrl(String value) { this.proxyUrl = value; @@ -167,11 +140,8 @@ public void setProxyUrl(String value) { /** * Gets the value of the sizeOnDisk property. - * - * @return - * possible object is - * {@link BigInteger } - * + * + * @return possible object is {@link BigInteger} */ public BigInteger getSizeOnDisk() { return sizeOnDisk; @@ -179,11 +149,8 @@ public BigInteger getSizeOnDisk() { /** * Sets the value of the sizeOnDisk property. - * - * @param value - * allowed object is - * {@link BigInteger } - * + * + * @param value allowed object is {@link BigInteger} */ public void setSizeOnDisk(BigInteger value) { this.sizeOnDisk = value; @@ -191,11 +158,8 @@ public void setSizeOnDisk(BigInteger value) { /** * Gets the value of the numArtifacts property. - * - * @return - * possible object is - * {@link BigInteger } - * + * + * @return possible object is {@link BigInteger} */ public BigInteger getNumArtifacts() { return numArtifacts; @@ -203,14 +167,10 @@ public BigInteger getNumArtifacts() { /** * Sets the value of the numArtifacts property. - * - * @param value - * allowed object is - * {@link BigInteger } - * + * + * @param value allowed object is {@link BigInteger} */ public void setNumArtifacts(BigInteger value) { this.numArtifacts = value; } - } diff --git a/plugin/src/main/java/org/jetbrains/idea/maven/services/nexus/RepositoryType.java b/plugin/src/main/java/org/jetbrains/idea/maven/services/nexus/RepositoryType.java index c3819722..e96d2643 100644 --- a/plugin/src/main/java/org/jetbrains/idea/maven/services/nexus/RepositoryType.java +++ b/plugin/src/main/java/org/jetbrains/idea/maven/services/nexus/RepositoryType.java @@ -20,14 +20,14 @@ import jakarta.xml.bind.annotation.XmlAccessorType; import jakarta.xml.bind.annotation.XmlElement; import jakarta.xml.bind.annotation.XmlType; -import java.io.Serializable; +import java.io.Serializable; /** *

Java class for repositoryType complex type. - * + * *

The following schema fragment specifies the expected content contained within this class. - * + * *

  * <complexType name="repositoryType">
  *   <complexContent>
@@ -50,8 +50,6 @@
  *   </complexContent>
  * </complexType>
  * 
- * - * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "repositoryType", propOrder = { @@ -69,7 +67,6 @@ "effectiveLocalStorageUrl" }) public class RepositoryType implements Serializable { - @XmlElement(required = true) protected String resourceURI; @XmlElement(required = true) @@ -97,11 +94,9 @@ public class RepositoryType implements Serializable { /** * Gets the value of the resourceURI property. - * - * @return - * possible object is - * {@link String } - * + * + * @return possible object is + * {@link String } */ public String getResourceURI() { return resourceURI; @@ -109,11 +104,8 @@ public String getResourceURI() { /** * Sets the value of the resourceURI property. - * - * @param value - * allowed object is - * {@link String } - * + * + * @param value allowed object is {@link String} */ public void setResourceURI(String value) { this.resourceURI = value; @@ -121,11 +113,8 @@ public void setResourceURI(String value) { /** * Gets the value of the contentResourceURI property. - * - * @return - * possible object is - * {@link String } - * + * + * @return possible object is {@link String} */ public String getContentResourceURI() { return contentResourceURI; @@ -133,11 +122,8 @@ public String getContentResourceURI() { /** * Sets the value of the contentResourceURI property. - * - * @param value - * allowed object is - * {@link String } - * + * + * @param value allowed object is {@link String} */ public void setContentResourceURI(String value) { this.contentResourceURI = value; @@ -145,11 +131,8 @@ public void setContentResourceURI(String value) { /** * Gets the value of the id property. - * - * @return - * possible object is - * {@link String } - * + * + * @return possible object is {@link String} */ public String getId() { return id; @@ -157,11 +140,8 @@ public String getId() { /** * Sets the value of the id property. - * - * @param value - * allowed object is - * {@link String } - * + * + * @param value allowed object is {@link String} */ public void setId(String value) { this.id = value; @@ -169,11 +149,8 @@ public void setId(String value) { /** * Gets the value of the name property. - * - * @return - * possible object is - * {@link String } - * + * + * @return possible object is {@link String} */ public String getName() { return name; @@ -181,11 +158,8 @@ public String getName() { /** * Sets the value of the name property. - * - * @param value - * allowed object is - * {@link String } - * + * + * @param value allowed object is {@link String} */ public void setName(String value) { this.name = value; @@ -193,11 +167,8 @@ public void setName(String value) { /** * Gets the value of the repoType property. - * - * @return - * possible object is - * {@link String } - * + * + * @return possible object is {@link String} */ public String getRepoType() { return repoType; @@ -205,11 +176,8 @@ public String getRepoType() { /** * Sets the value of the repoType property. - * - * @param value - * allowed object is - * {@link String } - * + * + * @param value allowed object is {@link String} */ public void setRepoType(String value) { this.repoType = value; @@ -217,11 +185,8 @@ public void setRepoType(String value) { /** * Gets the value of the repoPolicy property. - * - * @return - * possible object is - * {@link String } - * + * + * @return possible object is {@link String} */ public String getRepoPolicy() { return repoPolicy; @@ -229,11 +194,8 @@ public String getRepoPolicy() { /** * Sets the value of the repoPolicy property. - * - * @param value - * allowed object is - * {@link String } - * + * + * @param value allowed object is {@link String} */ public void setRepoPolicy(String value) { this.repoPolicy = value; @@ -241,11 +203,8 @@ public void setRepoPolicy(String value) { /** * Gets the value of the provider property. - * - * @return - * possible object is - * {@link String } - * + * + * @return possible object is {@link String} */ public String getProvider() { return provider; @@ -253,11 +212,9 @@ public String getProvider() { /** * Sets the value of the provider property. - * - * @param value - * allowed object is - * {@link String } - * + * + * @param value allowed object is + * {@link String } */ public void setProvider(String value) { this.provider = value; @@ -265,11 +222,8 @@ public void setProvider(String value) { /** * Gets the value of the providerRole property. - * - * @return - * possible object is - * {@link String } - * + * + * @return possible object is {@link String} */ public String getProviderRole() { return providerRole; @@ -277,11 +231,8 @@ public String getProviderRole() { /** * Sets the value of the providerRole property. - * - * @param value - * allowed object is - * {@link String } - * + * + * @param value allowed object is {@link String} */ public void setProviderRole(String value) { this.providerRole = value; @@ -289,11 +240,8 @@ public void setProviderRole(String value) { /** * Gets the value of the format property. - * - * @return - * possible object is - * {@link String } - * + * + * @return possible object is {@link String} */ public String getFormat() { return format; @@ -301,11 +249,8 @@ public String getFormat() { /** * Sets the value of the format property. - * - * @param value - * allowed object is - * {@link String } - * + * + * @param value allowed object is {@link String} */ public void setFormat(String value) { this.format = value; @@ -313,11 +258,8 @@ public void setFormat(String value) { /** * Gets the value of the userManaged property. - * - * @return - * possible object is - * {@link String } - * + * + * @return possible object is {@link String} */ public String getUserManaged() { return userManaged; @@ -325,11 +267,8 @@ public String getUserManaged() { /** * Sets the value of the userManaged property. - * - * @param value - * allowed object is - * {@link String } - * + * + * @param value allowed object is {@link String} */ public void setUserManaged(String value) { this.userManaged = value; @@ -337,11 +276,8 @@ public void setUserManaged(String value) { /** * Gets the value of the exposed property. - * - * @return - * possible object is - * {@link String } - * + * + * @return possible object is {@link String} */ public String getExposed() { return exposed; @@ -349,11 +285,8 @@ public String getExposed() { /** * Sets the value of the exposed property. - * - * @param value - * allowed object is - * {@link String } - * + * + * @param value allowed object is {@link String} */ public void setExposed(String value) { this.exposed = value; @@ -361,11 +294,8 @@ public void setExposed(String value) { /** * Gets the value of the effectiveLocalStorageUrl property. - * - * @return - * possible object is - * {@link String } - * + * + * @return possible object is {@link String} */ public String getEffectiveLocalStorageUrl() { return effectiveLocalStorageUrl; @@ -373,14 +303,10 @@ public String getEffectiveLocalStorageUrl() { /** * Sets the value of the effectiveLocalStorageUrl property. - * - * @param value - * allowed object is - * {@link String } - * + * + * @param value allowed object is {@link String} */ public void setEffectiveLocalStorageUrl(String value) { this.effectiveLocalStorageUrl = value; } - } diff --git a/plugin/src/main/java/org/jetbrains/idea/maven/services/nexus/SearchResult.java b/plugin/src/main/java/org/jetbrains/idea/maven/services/nexus/SearchResult.java index 1b44dc02..b3be4a89 100644 --- a/plugin/src/main/java/org/jetbrains/idea/maven/services/nexus/SearchResult.java +++ b/plugin/src/main/java/org/jetbrains/idea/maven/services/nexus/SearchResult.java @@ -18,16 +18,16 @@ import consulo.maven.rt.server.common.model.MavenArtifactInfo; import jakarta.xml.bind.annotation.*; + import java.math.BigInteger; import java.util.ArrayList; import java.util.List; - /** *

Java class for anonymous complex type. - * + * *

The following schema fragment specifies the expected content contained within this class. - * + * *

  * <complexType>
  *   <complexContent>
@@ -53,8 +53,6 @@
  *   </complexContent>
  * </complexType>
  * 
- * - * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { @@ -66,7 +64,6 @@ }) @XmlRootElement(name = "search-result") public class SearchResult { - @XmlElement(required = true) protected BigInteger totalCount; @XmlElement(required = true) @@ -79,11 +76,8 @@ public class SearchResult { /** * Gets the value of the totalCount property. - * - * @return - * possible object is - * {@link BigInteger } - * + * + * @return possible object is {@link BigInteger} */ public BigInteger getTotalCount() { return totalCount; @@ -91,11 +85,8 @@ public BigInteger getTotalCount() { /** * Sets the value of the totalCount property. - * - * @param value - * allowed object is - * {@link BigInteger } - * + * + * @param value allowed object is {@link BigInteger} */ public void setTotalCount(BigInteger value) { this.totalCount = value; @@ -103,11 +94,8 @@ public void setTotalCount(BigInteger value) { /** * Gets the value of the from property. - * - * @return - * possible object is - * {@link BigInteger } - * + * + * @return possible object is {@link BigInteger} */ public BigInteger getFrom() { return from; @@ -115,11 +103,8 @@ public BigInteger getFrom() { /** * Sets the value of the from property. - * - * @param value - * allowed object is - * {@link BigInteger } - * + * + * @param value allowed object is {@link BigInteger} */ public void setFrom(BigInteger value) { this.from = value; @@ -127,11 +112,8 @@ public void setFrom(BigInteger value) { /** * Gets the value of the count property. - * - * @return - * possible object is - * {@link BigInteger } - * + * + * @return possible object is {@link BigInteger} */ public BigInteger getCount() { return count; @@ -139,11 +121,8 @@ public BigInteger getCount() { /** * Sets the value of the count property. - * - * @param value - * allowed object is - * {@link BigInteger } - * + * + * @param value allowed object is {@link BigInteger} */ public void setCount(BigInteger value) { this.count = value; @@ -151,7 +130,6 @@ public void setCount(BigInteger value) { /** * Gets the value of the tooManyResults property. - * */ public boolean isTooManyResults() { return tooManyResults; @@ -159,7 +137,6 @@ public boolean isTooManyResults() { /** * Sets the value of the tooManyResults property. - * */ public void setTooManyResults(boolean value) { this.tooManyResults = value; @@ -167,11 +144,8 @@ public void setTooManyResults(boolean value) { /** * Gets the value of the data property. - * - * @return - * possible object is - * {@link SearchResult.Data } - * + * + * @return possible object is {@link SearchResult.Data} */ public SearchResult.Data getData() { return data; @@ -179,22 +153,18 @@ public SearchResult.Data getData() { /** * Sets the value of the data property. - * - * @param value - * allowed object is - * {@link SearchResult.Data } - * + * + * @param value allowed object is {@link SearchResult.Data} */ public void setData(SearchResult.Data value) { this.data = value; } - /** *

Java class for anonymous complex type. - * + * *

The following schema fragment specifies the expected content contained within this class. - * + * *

      * <complexType>
      *   <complexContent>
@@ -206,46 +176,35 @@ public void setData(SearchResult.Data value) {
      *   </complexContent>
      * </complexType>
      * 
- * - * */ @XmlAccessorType(XmlAccessType.FIELD) - @XmlType(name = "", propOrder = { - "artifact" - }) + @XmlType(name = "", propOrder = {"artifact"}) public static class Data { - protected List artifact; /** * Gets the value of the artifact property. - * + * *

* This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a set method for the artifact property. - * + * *

* For example, to add a new item, do as follows: *

          *    getArtifact().add(newItem);
          * 
- * - * + * *

- * Objects of the following type(s) are allowed in the list - * {@link MavenArtifactInfo } - * - * + * Objects of the following type(s) are allowed in the list {@link MavenArtifactInfo} */ public List getArtifact() { if (artifact == null) { - artifact = new ArrayList(); + artifact = new ArrayList<>(); } return this.artifact; } - } - } diff --git a/plugin/src/main/java/org/jetbrains/idea/maven/services/nexus/SearchResults.java b/plugin/src/main/java/org/jetbrains/idea/maven/services/nexus/SearchResults.java index d5004790..dfbcd233 100644 --- a/plugin/src/main/java/org/jetbrains/idea/maven/services/nexus/SearchResults.java +++ b/plugin/src/main/java/org/jetbrains/idea/maven/services/nexus/SearchResults.java @@ -18,16 +18,16 @@ import consulo.maven.rt.server.common.model.MavenArtifactInfo; import jakarta.xml.bind.annotation.*; + import java.math.BigInteger; import java.util.ArrayList; import java.util.List; - /** *

Java class for anonymous complex type. - * + * *

The following schema fragment specifies the expected content contained within this class. - * + * *

  * <complexType>
  *   <complexContent>
@@ -53,8 +53,6 @@
  *   </complexContent>
  * </complexType>
  * 
- * - * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { @@ -66,7 +64,6 @@ }) @XmlRootElement(name = "search-results") public class SearchResults { - @XmlElement(required = true) protected BigInteger totalCount; @XmlElement(required = true) @@ -78,11 +75,8 @@ public class SearchResults { /** * Gets the value of the totalCount property. - * - * @return - * possible object is - * {@link BigInteger } - * + * + * @return possible object is {@link BigInteger} */ public BigInteger getTotalCount() { return totalCount; @@ -90,11 +84,8 @@ public BigInteger getTotalCount() { /** * Sets the value of the totalCount property. - * - * @param value - * allowed object is - * {@link BigInteger } - * + * + * @param value allowed object is {@link BigInteger} */ public void setTotalCount(BigInteger value) { this.totalCount = value; @@ -102,11 +93,8 @@ public void setTotalCount(BigInteger value) { /** * Gets the value of the from property. - * - * @return - * possible object is - * {@link BigInteger } - * + * + * @return possible object is {@link BigInteger} */ public BigInteger getFrom() { return from; @@ -114,11 +102,8 @@ public BigInteger getFrom() { /** * Sets the value of the from property. - * - * @param value - * allowed object is - * {@link BigInteger } - * + * + * @param value allowed object is {@link BigInteger} */ public void setFrom(BigInteger value) { this.from = value; @@ -126,11 +111,8 @@ public void setFrom(BigInteger value) { /** * Gets the value of the count property. - * - * @return - * possible object is - * {@link BigInteger } - * + * + * @return possible object is {@link BigInteger} */ public BigInteger getCount() { return count; @@ -138,11 +120,8 @@ public BigInteger getCount() { /** * Sets the value of the count property. - * - * @param value - * allowed object is - * {@link BigInteger } - * + * + * @param value allowed object is {@link BigInteger} */ public void setCount(BigInteger value) { this.count = value; @@ -150,7 +129,6 @@ public void setCount(BigInteger value) { /** * Gets the value of the tooManyResults property. - * */ public boolean isTooManyResults() { return tooManyResults; @@ -158,7 +136,6 @@ public boolean isTooManyResults() { /** * Sets the value of the tooManyResults property. - * */ public void setTooManyResults(boolean value) { this.tooManyResults = value; @@ -166,11 +143,8 @@ public void setTooManyResults(boolean value) { /** * Gets the value of the data property. - * - * @return - * possible object is - * {@link SearchResults.Data } - * + * + * @return possible object is {@link SearchResults.Data} */ public SearchResults.Data getData() { return data; @@ -178,22 +152,18 @@ public SearchResults.Data getData() { /** * Sets the value of the data property. - * - * @param value - * allowed object is - * {@link SearchResults.Data } - * + * + * @param value allowed object is {@link SearchResults.Data} */ public void setData(SearchResults.Data value) { this.data = value; } - /** *

Java class for anonymous complex type. - * + * *

The following schema fragment specifies the expected content contained within this class. - * + * *

      * <complexType>
      *   <complexContent>
@@ -205,46 +175,35 @@ public void setData(SearchResults.Data value) {
      *   </complexContent>
      * </complexType>
      * 
- * - * */ @XmlAccessorType(XmlAccessType.FIELD) - @XmlType(name = "", propOrder = { - "artifact" - }) + @XmlType(name = "", propOrder = {"artifact"}) public static class Data { - protected ArrayList artifact; /** * Gets the value of the artifact property. - * + * *

* This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a set method for the artifact property. - * + * *

* For example, to add a new item, do as follows: *

          *    getArtifact().add(newItem);
          * 
- * - * + * *

- * Objects of the following type(s) are allowed in the list - * {@link MavenArtifactInfo } - * - * + * Objects of the following type(s) are allowed in the list {@link MavenArtifactInfo} */ public List getArtifact() { if (artifact == null) { - artifact = new ArrayList(); + artifact = new ArrayList<>(); } return this.artifact; } - } - } diff --git a/plugin/src/main/java/org/jetbrains/idea/maven/vfs/MavenGotoPropertyFileContributor.java b/plugin/src/main/java/org/jetbrains/idea/maven/vfs/MavenGotoPropertyFileContributor.java index 030de95a..d4810161 100644 --- a/plugin/src/main/java/org/jetbrains/idea/maven/vfs/MavenGotoPropertyFileContributor.java +++ b/plugin/src/main/java/org/jetbrains/idea/maven/vfs/MavenGotoPropertyFileContributor.java @@ -27,30 +27,24 @@ import javax.annotation.Nonnull; @ExtensionImpl -public class MavenGotoPropertyFileContributor implements GotoFileContributor -{ - @Nonnull - public String[] getNames(Project project, boolean includeNonProjectItems) - { - if(!includeNonProjectItems) - { - return ArrayUtil.EMPTY_STRING_ARRAY; - } - return MavenPropertiesVirtualFileSystem.PROPERTIES_FILES; - } +public class MavenGotoPropertyFileContributor implements GotoFileContributor { + @Nonnull + public String[] getNames(Project project, boolean includeNonProjectItems) { + if (!includeNonProjectItems) { + return ArrayUtil.EMPTY_STRING_ARRAY; + } + return MavenPropertiesVirtualFileSystem.PROPERTIES_FILES; + } - @Nonnull - public NavigationItem[] getItemsByName(String name, String pattern, Project project, boolean includeNonProjectItems) - { - VirtualFile file = MavenPropertiesVirtualFileSystem.getInstance().findFileByPath(name); - if(file != null) - { - PsiFile psiFile = PsiManager.getInstance(project).findFile(file); - if(psiFile != null) - { - return new NavigationItem[]{psiFile}; - } - } - return NavigationItem.EMPTY_NAVIGATION_ITEM_ARRAY; - } + @Nonnull + public NavigationItem[] getItemsByName(String name, String pattern, Project project, boolean includeNonProjectItems) { + VirtualFile file = MavenPropertiesVirtualFileSystem.getInstance().findFileByPath(name); + if (file != null) { + PsiFile psiFile = PsiManager.getInstance(project).findFile(file); + if (psiFile != null) { + return new NavigationItem[]{psiFile}; + } + } + return NavigationItem.EMPTY_NAVIGATION_ITEM_ARRAY; + } } diff --git a/plugin/src/main/java/org/jetbrains/idea/maven/vfs/MavenPropertiesVirtualFile.java b/plugin/src/main/java/org/jetbrains/idea/maven/vfs/MavenPropertiesVirtualFile.java index 028db2bc..d4f9ee54 100644 --- a/plugin/src/main/java/org/jetbrains/idea/maven/vfs/MavenPropertiesVirtualFile.java +++ b/plugin/src/main/java/org/jetbrains/idea/maven/vfs/MavenPropertiesVirtualFile.java @@ -29,91 +29,93 @@ import java.util.TreeSet; public class MavenPropertiesVirtualFile extends VirtualFile { - private final String myPath; - private final VirtualFileSystem myFS; - private final byte[] myContent; - - public MavenPropertiesVirtualFile(String path, Properties properties, VirtualFileSystem FS) { - myPath = path; - myFS = FS; - - myContent = createContent(properties); - } - - private byte[] createContent(Properties properties) { - StringBuilder builder = new StringBuilder(); - TreeSet sortedKeys = new TreeSet((Set)properties.keySet()); - for (String each : sortedKeys) { - builder.append(StringUtil.escapeProperty(each, true)); - builder.append("="); - builder.append(StringUtil.escapeProperty(properties.getProperty(each), false)); - builder.append("\n"); - } - return builder.toString().getBytes(); - } - - @Nonnull - public String getName() { - return myPath; - } - - @Nonnull - public VirtualFileSystem getFileSystem() { - return myFS; - } - - public String getPath() { - return myPath; - } - - public boolean isWritable() { - return false; - } - - public boolean isDirectory() { - return false; - } - - public boolean isValid() { - return true; - } - - public VirtualFile getParent() { - return null; - } - - public VirtualFile[] getChildren() { - return null; - } - - @Nonnull - public byte[] contentsToByteArray() throws IOException { - if (myContent == null) throw new IOException(); - return myContent; - } - - public long getTimeStamp() { - return -1; - } - - @Override - public long getModificationStamp() { - return myContent.hashCode(); - } - - public long getLength() { - return myContent.length; - } - - public void refresh(boolean asynchronous, boolean recursive, Runnable postRunnable) { - } - - public InputStream getInputStream() throws IOException { - return VirtualFileUtil.byteStreamSkippingBOM(myContent,this); - } - - @Nonnull - public OutputStream getOutputStream(Object requestor, long newModificationStamp, long newTimeStamp) throws IOException { - throw new UnsupportedOperationException(); - } + private final String myPath; + private final VirtualFileSystem myFS; + private final byte[] myContent; + + public MavenPropertiesVirtualFile(String path, Properties properties, VirtualFileSystem FS) { + myPath = path; + myFS = FS; + + myContent = createContent(properties); + } + + private byte[] createContent(Properties properties) { + StringBuilder builder = new StringBuilder(); + TreeSet sortedKeys = new TreeSet((Set)properties.keySet()); + for (String each : sortedKeys) { + builder.append(StringUtil.escapeProperty(each, true)); + builder.append("="); + builder.append(StringUtil.escapeProperty(properties.getProperty(each), false)); + builder.append("\n"); + } + return builder.toString().getBytes(); + } + + @Nonnull + public String getName() { + return myPath; + } + + @Nonnull + public VirtualFileSystem getFileSystem() { + return myFS; + } + + public String getPath() { + return myPath; + } + + public boolean isWritable() { + return false; + } + + public boolean isDirectory() { + return false; + } + + public boolean isValid() { + return true; + } + + public VirtualFile getParent() { + return null; + } + + public VirtualFile[] getChildren() { + return null; + } + + @Nonnull + public byte[] contentsToByteArray() throws IOException { + if (myContent == null) { + throw new IOException(); + } + return myContent; + } + + public long getTimeStamp() { + return -1; + } + + @Override + public long getModificationStamp() { + return myContent.hashCode(); + } + + public long getLength() { + return myContent.length; + } + + public void refresh(boolean asynchronous, boolean recursive, Runnable postRunnable) { + } + + public InputStream getInputStream() throws IOException { + return VirtualFileUtil.byteStreamSkippingBOM(myContent, this); + } + + @Nonnull + public OutputStream getOutputStream(Object requestor, long newModificationStamp, long newTimeStamp) throws IOException { + throw new UnsupportedOperationException(); + } } diff --git a/plugin/src/main/java/org/jetbrains/idea/maven/vfs/MavenPropertiesVirtualFileSystem.java b/plugin/src/main/java/org/jetbrains/idea/maven/vfs/MavenPropertiesVirtualFileSystem.java index 969ac4af..d87a2c32 100644 --- a/plugin/src/main/java/org/jetbrains/idea/maven/vfs/MavenPropertiesVirtualFileSystem.java +++ b/plugin/src/main/java/org/jetbrains/idea/maven/vfs/MavenPropertiesVirtualFileSystem.java @@ -23,8 +23,10 @@ import consulo.ide.impl.idea.openapi.vfs.ex.dummy.DummyFileSystem; import consulo.virtualFileSystem.VirtualFile; import org.jetbrains.annotations.NonNls; + import javax.annotation.Nonnull; import javax.annotation.Nullable; + import org.jetbrains.idea.maven.dom.MavenDomUtil; import java.util.Map; @@ -32,109 +34,114 @@ @ExtensionImpl public class MavenPropertiesVirtualFileSystem extends DummyFileSystem { - @NonNls public static final String PROTOCOL = "maven-properties"; + @NonNls + public static final String PROTOCOL = "maven-properties"; + + @NonNls + public static final String SYSTEM_PROPERTIES_FILE = "System.properties"; + @NonNls + public static final String ENV_PROPERTIES_FILE = "Environment.properties"; - @NonNls public static final String SYSTEM_PROPERTIES_FILE = "System.properties"; - @NonNls public static final String ENV_PROPERTIES_FILE = "Environment.properties"; + public static final String[] PROPERTIES_FILES = new String[]{SYSTEM_PROPERTIES_FILE, ENV_PROPERTIES_FILE}; - public static final String[] PROPERTIES_FILES = new String[]{SYSTEM_PROPERTIES_FILE, ENV_PROPERTIES_FILE}; + private VirtualFile mySystemPropertiesFile; + private VirtualFile myEnvPropertiesFile; - private VirtualFile mySystemPropertiesFile; - private VirtualFile myEnvPropertiesFile; + public static MavenPropertiesVirtualFileSystem getInstance() { + return (MavenPropertiesVirtualFileSystem)VirtualFileManager.getInstance().getFileSystem(PROTOCOL); + } - public static MavenPropertiesVirtualFileSystem getInstance() { - return (MavenPropertiesVirtualFileSystem)VirtualFileManager.getInstance().getFileSystem(PROTOCOL); - } + @Nonnull + public String getProtocol() { + return PROTOCOL; + } - @Nonnull - public String getProtocol() { - return PROTOCOL; - } + public VirtualFile getSystemPropertiesFile() { + if (mySystemPropertiesFile == null) { + Properties systemProperties = new Properties(); - public VirtualFile getSystemPropertiesFile() { - if (mySystemPropertiesFile == null) { - Properties systemProperties = new Properties(); + for (Map.Entry entry : System.getProperties().entrySet()) { + if (entry.getKey() instanceof String && entry.getValue() instanceof String) { + String key = (String)entry.getKey(); + if (!key.startsWith("idea.")) { + systemProperties.setProperty(key, (String)entry.getValue()); + } + } + } - for (Map.Entry entry : System.getProperties().entrySet()) { - if (entry.getKey() instanceof String && entry.getValue() instanceof String) { - String key = (String)entry.getKey(); - if (!key.startsWith("idea.")) { - systemProperties.setProperty(key, (String)entry.getValue()); - } + mySystemPropertiesFile = new MavenPropertiesVirtualFile(SYSTEM_PROPERTIES_FILE, systemProperties, this); } - } - mySystemPropertiesFile = new MavenPropertiesVirtualFile(SYSTEM_PROPERTIES_FILE, systemProperties, this); + return mySystemPropertiesFile; } - return mySystemPropertiesFile; - } + public VirtualFile getEnvPropertiesFile() { + if (myEnvPropertiesFile == null) { + Properties envProperties = new Properties(); - public VirtualFile getEnvPropertiesFile() { - if (myEnvPropertiesFile == null) { - Properties envProperties = new Properties(); + for (Map.Entry each : System.getenv().entrySet()) { + String key = each.getKey(); + if (key.startsWith("=")) { + continue; + } + envProperties.setProperty(SystemInfo.isWindows ? key.toUpperCase() : key, each.getValue()); + } - for (Map.Entry each : System.getenv().entrySet()) { - String key = each.getKey(); - if (key.startsWith("=")) continue; - envProperties.setProperty(SystemInfo.isWindows ? key.toUpperCase() : key, each.getValue()); - } + myEnvPropertiesFile = new MavenPropertiesVirtualFile(ENV_PROPERTIES_FILE, envProperties, this); + } - myEnvPropertiesFile = new MavenPropertiesVirtualFile(ENV_PROPERTIES_FILE, envProperties, this); + return myEnvPropertiesFile; } - return myEnvPropertiesFile; - } + //@Override + //public boolean isPhysical() { + // return false; + //} - //@Override - //public boolean isPhysical() { - // return false; - //} + public synchronized VirtualFile findFileByPath(@Nonnull @NonNls String path) { + if (path.equals(SYSTEM_PROPERTIES_FILE)) { + return getSystemPropertiesFile(); + } + + if (path.equals(ENV_PROPERTIES_FILE)) { + return getEnvPropertiesFile(); + } + + return null; + } - public synchronized VirtualFile findFileByPath(@Nonnull @NonNls String path) { - if (path.equals(SYSTEM_PROPERTIES_FILE)) { - return getSystemPropertiesFile(); + @Nullable + public IProperty findSystemProperty(Project project, @Nonnull String propertyName) { + return MavenDomUtil.findProperty(project, getSystemPropertiesFile(), propertyName); } - if (path.equals(ENV_PROPERTIES_FILE)) { - return getEnvPropertiesFile(); + @Nullable + public IProperty findEnvProperty(Project project, @Nonnull String propertyName) { + return MavenDomUtil.findProperty(project, getEnvPropertiesFile(), propertyName); } - return null; - } - - @Nullable - public IProperty findSystemProperty(Project project, @Nonnull String propertyName) { - return MavenDomUtil.findProperty(project, getSystemPropertiesFile(), propertyName); - } - - @Nullable - public IProperty findEnvProperty(Project project, @Nonnull String propertyName) { - return MavenDomUtil.findProperty(project, getEnvPropertiesFile(), propertyName); - } - - //protected void deleteFile(Object requestor, VirtualFile vFile) throws IOException { - // throw new UnsupportedOperationException(); - //} - // - //protected void moveFile(Object requestor, VirtualFile vFile, VirtualFile newParent) throws IOException { - // throw new UnsupportedOperationException(); - //} - // - //protected void renameFile(Object requestor, VirtualFile vFile, String newName) throws IOException { - // throw new UnsupportedOperationException(); - //} - // - //protected VirtualFile createChildFile(Object requestor, VirtualFile vDir, String fileName) throws IOException { - // throw new UnsupportedOperationException(); - //} - // - //protected VirtualFile createChildDirectory(Object requestor, VirtualFile vDir, String dirName) throws IOException { - // throw new UnsupportedOperationException(); - //} - // - //protected VirtualFile copyFile(Object requestor, VirtualFile virtualFile, VirtualFile newParent, String copyName) - // throws IOException { - // throw new UnsupportedOperationException(); - //} + //protected void deleteFile(Object requestor, VirtualFile vFile) throws IOException { + // throw new UnsupportedOperationException(); + //} + // + //protected void moveFile(Object requestor, VirtualFile vFile, VirtualFile newParent) throws IOException { + // throw new UnsupportedOperationException(); + //} + // + //protected void renameFile(Object requestor, VirtualFile vFile, String newName) throws IOException { + // throw new UnsupportedOperationException(); + //} + // + //protected VirtualFile createChildFile(Object requestor, VirtualFile vDir, String fileName) throws IOException { + // throw new UnsupportedOperationException(); + //} + // + //protected VirtualFile createChildDirectory(Object requestor, VirtualFile vDir, String dirName) throws IOException { + // throw new UnsupportedOperationException(); + //} + // + //protected VirtualFile copyFile(Object requestor, VirtualFile virtualFile, VirtualFile newParent, String copyName) + // throws IOException { + // throw new UnsupportedOperationException(); + //} } diff --git a/plugin/src/main/java/org/jetbrains/idea/maven/wizards/MavenAddArchetypeDialog.java b/plugin/src/main/java/org/jetbrains/idea/maven/wizards/MavenAddArchetypeDialog.java index 09a471dd..ad16df4c 100644 --- a/plugin/src/main/java/org/jetbrains/idea/maven/wizards/MavenAddArchetypeDialog.java +++ b/plugin/src/main/java/org/jetbrains/idea/maven/wizards/MavenAddArchetypeDialog.java @@ -27,69 +27,77 @@ import java.util.List; public class MavenAddArchetypeDialog extends DialogWrapper { - private JPanel myMainPanel; - private JTextField myGroupIdField; - private JTextField myArtifactIdField; - private JTextField myVersionField; - private JTextField myRepositoryField; + private JPanel myMainPanel; + private JTextField myGroupIdField; + private JTextField myArtifactIdField; + private JTextField myVersionField; + private JTextField myRepositoryField; - public MavenAddArchetypeDialog(Component parent) { - super(parent, false); - setTitle("Add Archetype"); + public MavenAddArchetypeDialog(Component parent) { + super(parent, false); + setTitle("Add Archetype"); - init(); + init(); - DocumentAdapter l = new DocumentAdapter() { - @Override - protected void textChanged(DocumentEvent e) { - doValidateInput(); - } - }; + DocumentAdapter l = new DocumentAdapter() { + @Override + protected void textChanged(DocumentEvent e) { + doValidateInput(); + } + }; - myGroupIdField.getDocument().addDocumentListener(l); - myArtifactIdField.getDocument().addDocumentListener(l); - myVersionField.getDocument().addDocumentListener(l); - myRepositoryField.getDocument().addDocumentListener(l); + myGroupIdField.getDocument().addDocumentListener(l); + myArtifactIdField.getDocument().addDocumentListener(l); + myVersionField.getDocument().addDocumentListener(l); + myRepositoryField.getDocument().addDocumentListener(l); - doValidateInput(); - } + doValidateInput(); + } - protected JComponent createCenterPanel() { - return myMainPanel; - } + protected JComponent createCenterPanel() { + return myMainPanel; + } - @Override - public JComponent getPreferredFocusedComponent() { - return myGroupIdField; - } + @Override + public JComponent getPreferredFocusedComponent() { + return myGroupIdField; + } - @Override - protected String getHelpId() { - return "Add_Archetype_Dialog"; - } + @Override + protected String getHelpId() { + return "Add_Archetype_Dialog"; + } - private void doValidateInput() { - List errors = new ArrayList(); - if (StringUtil.isEmptyOrSpaces(myGroupIdField.getText())) errors.add("GroupId"); - if (StringUtil.isEmptyOrSpaces(myArtifactIdField.getText())) errors.add("ArtifactId"); - if (StringUtil.isEmptyOrSpaces(myVersionField.getText())) errors.add("Version"); + private void doValidateInput() { + List errors = new ArrayList(); + if (StringUtil.isEmptyOrSpaces(myGroupIdField.getText())) { + errors.add("GroupId"); + } + if (StringUtil.isEmptyOrSpaces(myArtifactIdField.getText())) { + errors.add("ArtifactId"); + } + if (StringUtil.isEmptyOrSpaces(myVersionField.getText())) { + errors.add("Version"); + } - if (errors.isEmpty()) { - setErrorText(null); - getOKAction().setEnabled(true); - return; + if (errors.isEmpty()) { + setErrorText(null); + getOKAction().setEnabled(true); + return; + } + String message = "Please specify " + StringUtil.join(errors, ", "); + setErrorText(message); + getOKAction().setEnabled(false); + getRootPane().revalidate(); } - String message = "Please specify " + StringUtil.join(errors, ", "); - setErrorText(message); - getOKAction().setEnabled(false); - getRootPane().revalidate(); - } - public MavenArchetype getArchetype() { - return new MavenArchetype(myGroupIdField.getText(), - myArtifactIdField.getText(), - myVersionField.getText(), - myRepositoryField.getText(), - null); - } + public MavenArchetype getArchetype() { + return new MavenArchetype( + myGroupIdField.getText(), + myArtifactIdField.getText(), + myVersionField.getText(), + myRepositoryField.getText(), + null + ); + } } diff --git a/plugin/src/main/java/org/jetbrains/idea/maven/wizards/MavenModuleBuilderHelper.java b/plugin/src/main/java/org/jetbrains/idea/maven/wizards/MavenModuleBuilderHelper.java index 351e0da6..7056b3e0 100644 --- a/plugin/src/main/java/org/jetbrains/idea/maven/wizards/MavenModuleBuilderHelper.java +++ b/plugin/src/main/java/org/jetbrains/idea/maven/wizards/MavenModuleBuilderHelper.java @@ -52,240 +52,213 @@ import java.util.Collections; import java.util.Map; -public class MavenModuleBuilderHelper -{ - private final MavenId myProjectId; - - private final MavenProject myAggregatorProject; - private final MavenProject myParentProject; - - private final boolean myInheritGroupId; - private final boolean myInheritVersion; - - private final MavenArchetype myArchetype; - private final Map myPropertiesToCreateByArtifact; - - private final String myCommandName; - - public MavenModuleBuilderHelper(@Nonnull MavenId projectId, - MavenProject aggregatorProject, - MavenProject parentProject, - boolean inheritGroupId, - boolean inheritVersion, - MavenArchetype archetype, - Map propertiesToCreateByArtifact, - String commaneName) - { - myProjectId = projectId; - myAggregatorProject = aggregatorProject; - myParentProject = parentProject; - myInheritGroupId = inheritGroupId; - myInheritVersion = inheritVersion; - myArchetype = archetype; - myPropertiesToCreateByArtifact = propertiesToCreateByArtifact; - myCommandName = commaneName; - } - - public void configure(final Project project, final VirtualFile root, final boolean isInteractive) - { - PsiFile[] psiFiles = myAggregatorProject != null ? new PsiFile[]{getPsiFile(project, myAggregatorProject.getFile())} : PsiFile.EMPTY_ARRAY; - final VirtualFile pom = new WriteCommandAction(project, myCommandName, psiFiles) - { - @Override - protected void run(Result result) throws Throwable - { - VirtualFile file; - try - { - file = root.createChildData(this, MavenConstants.POM_XML); - MavenUtil.runOrApplyMavenProjectFileTemplate(project, file, myProjectId, isInteractive); - result.setResult(file); - } - catch(IOException e) - { - showError(project, e); - return; - } - - updateProjectPom(project, file); - - if(myAggregatorProject != null) - { - MavenDomProjectModel model = MavenDomUtil.getMavenDomProjectModel(project, myAggregatorProject.getFile()); - model.getPackaging().setStringValue("pom"); - MavenDomModule module = model.getModules().addModule(); - module.setValue(getPsiFile(project, file)); - } - } - }.execute().getResultObject(); - - if(pom == null) - { - return; - } - - if(myAggregatorProject == null) - { - MavenProjectsManager manager = MavenProjectsManager.getInstance(project); - manager.addManagedFiles(Collections.singletonList(pom)); - } - - if(myArchetype == null) - { - try - { - VirtualFileUtil.createDirectories(root.getPath() + "/src/main/java"); - VirtualFileUtil.createDirectories(root.getPath() + "/src/main/resources"); - VirtualFileUtil.createDirectories(root.getPath() + "/src/test/java"); - } - catch(IOException e) - { - MavenLog.LOG.info(e); - } - } - - // execute when current dialog is closed (e.g. Project Structure) - MavenUtil.invokeLater(project, Application.get().getNoneModalityState(), new Runnable() - { - public void run() - { - if(!pom.isValid()) - { - return; - } - - EditorHelper.openInEditor(getPsiFile(project, pom)); - if(myArchetype != null) - { - generateFromArchetype(project, pom); - } - } - }); - } - - private void updateProjectPom(final Project project, final VirtualFile pom) - { - if(myParentProject == null) - { - return; - } - - new WriteCommandAction.Simple(project, myCommandName) - { - protected void run() throws Throwable - { - MavenDomProjectModel model = MavenDomUtil.getMavenDomProjectModel(project, pom); - if(model == null) - { - return; - } - - MavenDomUtil.updateMavenParent(model, myParentProject); - - if(myInheritGroupId) - { - XmlElement el = model.getGroupId().getXmlElement(); - if(el != null) - { - el.delete(); - } - } - if(myInheritVersion) - { - XmlElement el = model.getVersion().getXmlElement(); - if(el != null) - { - el.delete(); - } - } - - CodeStyleManager.getInstance(project).reformat(getPsiFile(project, pom)); - - pom.putUserData(MavenProjectsManagerWatcher.FORCE_IMPORT_AND_RESOLVE_ON_REFRESH, Boolean.TRUE); - try - { - Document doc = FileDocumentManager.getInstance().getDocument(pom); - PsiDocumentManager.getInstance(project).doPostponedOperationsAndUnblockDocument(doc); - FileDocumentManager.getInstance().saveDocument(doc); - } - finally - { - pom.putUserData(MavenProjectsManagerWatcher.FORCE_IMPORT_AND_RESOLVE_ON_REFRESH, null); - } - } - }.execute(); - } - - private PsiFile getPsiFile(Project project, VirtualFile pom) - { - return PsiManager.getInstance(project).findFile(pom); - } - - private void generateFromArchetype(final Project project, final VirtualFile pom) - { - final File workingDir; - try - { - workingDir = FileUtil.createTempDirectory("archetype", "tmp"); - workingDir.deleteOnExit(); - } - catch(IOException e) - { - showError(project, e); - return; - } - - MavenRunnerParameters params = new MavenRunnerParameters(false, workingDir.getPath(), Collections.singletonList("org.apache.maven.plugins:maven-archetype-plugin:RELEASE:generate"), - Collections.emptyList()); - - - MavenRunner runner = MavenRunner.getInstance(project); - MavenRunnerSettings settings = runner.getState().clone(); - Map props = settings.getMavenProperties(); - - props.put("interactiveMode", "false"); - //props.put("archetypeGroupId", myArchetype.groupId); - //props.put("archetypeArtifactId", myArchetype.artifactId); - //props.put("archetypeVersion", myArchetype.version); - //if (myArchetype.repository != null) props.put("archetypeRepository", myArchetype.repository); - - //props.put("groupId", myProjectId.getGroupId()); - //props.put("artifactId", myProjectId.getArtifactId()); - //props.put("version", myProjectId.getVersion()); - - props.putAll(myPropertiesToCreateByArtifact); - - runner.run(params, settings, new Runnable() - { - public void run() - { - copyGeneratedFiles(workingDir, pom, project); - } - }); - } - - private void copyGeneratedFiles(File workingDir, VirtualFile pom, Project project) - { - try - { - FileUtil.copyDir(new File(workingDir, myProjectId.getArtifactId()), new File(pom.getParent().getPath())); - } - catch(IOException e) - { - showError(project, e); - return; - } - - FileUtil.delete(workingDir); - - pom.refresh(false, false); - updateProjectPom(project, pom); - - LocalFileSystem.getInstance().refreshWithoutFileWatcher(true); - } - - private void showError(Project project, Throwable e) - { - MavenUtil.showError(project, "Failed to create a Maven project", e); - } +public class MavenModuleBuilderHelper { + private final MavenId myProjectId; + + private final MavenProject myAggregatorProject; + private final MavenProject myParentProject; + + private final boolean myInheritGroupId; + private final boolean myInheritVersion; + + private final MavenArchetype myArchetype; + private final Map myPropertiesToCreateByArtifact; + + private final String myCommandName; + + public MavenModuleBuilderHelper( + @Nonnull MavenId projectId, + MavenProject aggregatorProject, + MavenProject parentProject, + boolean inheritGroupId, + boolean inheritVersion, + MavenArchetype archetype, + Map propertiesToCreateByArtifact, + String commaneName + ) { + myProjectId = projectId; + myAggregatorProject = aggregatorProject; + myParentProject = parentProject; + myInheritGroupId = inheritGroupId; + myInheritVersion = inheritVersion; + myArchetype = archetype; + myPropertiesToCreateByArtifact = propertiesToCreateByArtifact; + myCommandName = commaneName; + } + + public void configure(final Project project, final VirtualFile root, final boolean isInteractive) { + PsiFile[] psiFiles = + myAggregatorProject != null ? new PsiFile[]{getPsiFile(project, myAggregatorProject.getFile())} : PsiFile.EMPTY_ARRAY; + final VirtualFile pom = new WriteCommandAction(project, myCommandName, psiFiles) { + @Override + protected void run(Result result) throws Throwable { + VirtualFile file; + try { + file = root.createChildData(this, MavenConstants.POM_XML); + MavenUtil.runOrApplyMavenProjectFileTemplate(project, file, myProjectId, isInteractive); + result.setResult(file); + } + catch (IOException e) { + showError(project, e); + return; + } + + updateProjectPom(project, file); + + if (myAggregatorProject != null) { + MavenDomProjectModel model = MavenDomUtil.getMavenDomProjectModel(project, myAggregatorProject.getFile()); + model.getPackaging().setStringValue("pom"); + MavenDomModule module = model.getModules().addModule(); + module.setValue(getPsiFile(project, file)); + } + } + }.execute().getResultObject(); + + if (pom == null) { + return; + } + + if (myAggregatorProject == null) { + MavenProjectsManager manager = MavenProjectsManager.getInstance(project); + manager.addManagedFiles(Collections.singletonList(pom)); + } + + if (myArchetype == null) { + try { + VirtualFileUtil.createDirectories(root.getPath() + "/src/main/java"); + VirtualFileUtil.createDirectories(root.getPath() + "/src/main/resources"); + VirtualFileUtil.createDirectories(root.getPath() + "/src/test/java"); + } + catch (IOException e) { + MavenLog.LOG.info(e); + } + } + + // execute when current dialog is closed (e.g. Project Structure) + MavenUtil.invokeLater(project, Application.get().getNoneModalityState(), new Runnable() { + public void run() { + if (!pom.isValid()) { + return; + } + + EditorHelper.openInEditor(getPsiFile(project, pom)); + if (myArchetype != null) { + generateFromArchetype(project, pom); + } + } + }); + } + + private void updateProjectPom(final Project project, final VirtualFile pom) { + if (myParentProject == null) { + return; + } + + new WriteCommandAction.Simple(project, myCommandName) { + protected void run() throws Throwable { + MavenDomProjectModel model = MavenDomUtil.getMavenDomProjectModel(project, pom); + if (model == null) { + return; + } + + MavenDomUtil.updateMavenParent(model, myParentProject); + + if (myInheritGroupId) { + XmlElement el = model.getGroupId().getXmlElement(); + if (el != null) { + el.delete(); + } + } + if (myInheritVersion) { + XmlElement el = model.getVersion().getXmlElement(); + if (el != null) { + el.delete(); + } + } + + CodeStyleManager.getInstance(project).reformat(getPsiFile(project, pom)); + + pom.putUserData(MavenProjectsManagerWatcher.FORCE_IMPORT_AND_RESOLVE_ON_REFRESH, Boolean.TRUE); + try { + Document doc = FileDocumentManager.getInstance().getDocument(pom); + PsiDocumentManager.getInstance(project).doPostponedOperationsAndUnblockDocument(doc); + FileDocumentManager.getInstance().saveDocument(doc); + } + finally { + pom.putUserData(MavenProjectsManagerWatcher.FORCE_IMPORT_AND_RESOLVE_ON_REFRESH, null); + } + } + }.execute(); + } + + private PsiFile getPsiFile(Project project, VirtualFile pom) { + return PsiManager.getInstance(project).findFile(pom); + } + + private void generateFromArchetype(final Project project, final VirtualFile pom) { + final File workingDir; + try { + workingDir = FileUtil.createTempDirectory("archetype", "tmp"); + workingDir.deleteOnExit(); + } + catch (IOException e) { + showError(project, e); + return; + } + + MavenRunnerParameters params = new MavenRunnerParameters( + false, + workingDir.getPath(), + Collections.singletonList("org.apache.maven.plugins:maven-archetype-plugin:RELEASE:generate"), + Collections.emptyList() + ); + + + MavenRunner runner = MavenRunner.getInstance(project); + MavenRunnerSettings settings = runner.getState().clone(); + Map props = settings.getMavenProperties(); + + props.put("interactiveMode", "false"); + //props.put("archetypeGroupId", myArchetype.groupId); + //props.put("archetypeArtifactId", myArchetype.artifactId); + //props.put("archetypeVersion", myArchetype.version); + //if (myArchetype.repository != null) props.put("archetypeRepository", myArchetype.repository); + + //props.put("groupId", myProjectId.getGroupId()); + //props.put("artifactId", myProjectId.getArtifactId()); + //props.put("version", myProjectId.getVersion()); + + props.putAll(myPropertiesToCreateByArtifact); + + runner.run( + params, + settings, + new Runnable() { + public void run() { + copyGeneratedFiles(workingDir, pom, project); + } + } + ); + } + + private void copyGeneratedFiles(File workingDir, VirtualFile pom, Project project) { + try { + FileUtil.copyDir(new File(workingDir, myProjectId.getArtifactId()), new File(pom.getParent().getPath())); + } + catch (IOException e) { + showError(project, e); + return; + } + + FileUtil.delete(workingDir); + + pom.refresh(false, false); + updateProjectPom(project, pom); + + LocalFileSystem.getInstance().refreshWithoutFileWatcher(true); + } + + private void showError(Project project, Throwable e) { + MavenUtil.showError(project, "Failed to create a Maven project", e); + } } diff --git a/plugin/src/main/java/org/jetbrains/idea/maven/wizards/MavenModuleWizardStep.java b/plugin/src/main/java/org/jetbrains/idea/maven/wizards/MavenModuleWizardStep.java index 5396cadb..0310a797 100644 --- a/plugin/src/main/java/org/jetbrains/idea/maven/wizards/MavenModuleWizardStep.java +++ b/plugin/src/main/java/org/jetbrains/idea/maven/wizards/MavenModuleWizardStep.java @@ -51,532 +51,470 @@ import java.util.List; import java.util.*; -public class MavenModuleWizardStep implements WizardStep -{ - private static final String INHERIT_GROUP_ID_KEY = "MavenModuleWizard.inheritGroupId"; - private static final String INHERIT_VERSION_KEY = "MavenModuleWizard.inheritVersion"; - private static final String ARCHETYPE_ARTIFACT_ID_KEY = "MavenModuleWizard.archetypeArtifactIdKey"; - private static final String ARCHETYPE_GROUP_ID_KEY = "MavenModuleWizard.archetypeGroupIdKey"; - private static final String ARCHETYPE_VERSION_KEY = "MavenModuleWizard.archetypeVersionKey"; - - private final Project myProjectOrNull; - private final MavenNewModuleContext myContext; - private MavenProject myAggregator; - private MavenProject myParent; - - private String myInheritedGroupId; - private String myInheritedVersion; - - private JPanel myMainPanel; - - private JTextField myGroupIdField; - private JCheckBox myInheritGroupIdCheckBox; - private JTextField myArtifactIdField; - private JTextField myVersionField; - private JCheckBox myInheritVersionCheckBox; - - private JCheckBox myUseArchetypeCheckBox; - private JButton myAddArchetypeButton; - private JScrollPane myArchetypesScrollPane; - private JPanel myArchetypesPanel; - private Tree myArchetypesTree; - private JScrollPane myArchetypeDescriptionScrollPane; - private JTextArea myArchetypeDescriptionField; - - private Object myCurrentUpdaterMarker; - private final AsyncProcessIcon myLoadingIcon = new AsyncProcessIcon.Big(getClass() + ".loading"); - - private boolean skipUpdateUI; - - public MavenModuleWizardStep(MavenNewModuleContext context) - { - myProjectOrNull = null; - myContext = context; - - initComponents(); - loadSettings(); - } - - private void initComponents() - { - myArchetypesTree = new Tree(); - myArchetypesTree.setModel(new DefaultTreeModel(new DefaultMutableTreeNode())); - myArchetypesScrollPane = ScrollPaneFactory.createScrollPane(myArchetypesTree); - - myArchetypesPanel.add(myArchetypesScrollPane, "archetypes"); - - JPanel loadingPanel = new JPanel(new GridBagLayout()); - JPanel bp = new JPanel(new BorderLayout(10, 10)); - bp.add(new JLabel("Loading archetype list..."), BorderLayout.NORTH); - bp.add(myLoadingIcon, BorderLayout.CENTER); - - loadingPanel.add(bp, new GridBagConstraints()); - - myArchetypesPanel.add(ScrollPaneFactory.createScrollPane(loadingPanel), "loading"); - ((CardLayout) myArchetypesPanel.getLayout()).show(myArchetypesPanel, "archetypes"); - - ActionListener updatingListener = e -> updateComponents(); - myInheritGroupIdCheckBox.addActionListener(updatingListener); - myInheritVersionCheckBox.addActionListener(updatingListener); - - myUseArchetypeCheckBox.addActionListener(updatingListener); - myUseArchetypeCheckBox.addActionListener(e -> archetypeMayBeChanged()); - - myAddArchetypeButton.addActionListener(e -> doAddArchetype()); - - myArchetypesTree.setRootVisible(false); - myArchetypesTree.setShowsRootHandles(true); - myArchetypesTree.setCellRenderer(new MyRenderer()); - myArchetypesTree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION); - - myArchetypesTree.getSelectionModel().addTreeSelectionListener(e -> { - updateArchetypeDescription(); - archetypeMayBeChanged(); - }); - - new TreeSpeedSearch(myArchetypesTree, path -> { - MavenArchetype info = getArchetypeInfoFromPathComponent(path.getLastPathComponent()); - return info.groupId + ":" + info.artifactId + ":" + info.version; - }).setComparator(new SpeedSearchComparator(false)); - - myArchetypeDescriptionField.setEditable(false); - myArchetypeDescriptionField.setBackground(UIUtil.getPanelBackground()); - } - - private void archetypeMayBeChanged() - { - MavenArchetype selectedArchetype = getSelectedArchetype(); - if(((myContext.getArchetype() == null) != (selectedArchetype == null))) - { - myContext.setArchetype(selectedArchetype); - skipUpdateUI = true; - try - { - //fireStateChanged(); - } - finally - { - skipUpdateUI = false; - } - } - } - - @Override - public JComponent getSwingPreferredFocusedComponent() - { - return myGroupIdField; - } - - private MavenProject doSelectProject(MavenProject current) - { - assert myProjectOrNull != null : "must not be called when creating a new project"; - - SelectMavenProjectDialog d = new SelectMavenProjectDialog(myProjectOrNull, current); - d.show(); - if(!d.isOK()) - { - return current; - } - return d.getResult(); - } - - private void doAddArchetype() - { - MavenAddArchetypeDialog dialog = new MavenAddArchetypeDialog(myMainPanel); - dialog.show(); - if(!dialog.isOK()) - { - return; - } - - MavenArchetype archetype = dialog.getArchetype(); - MavenIndicesManager.getInstance().addArchetype(archetype); - updateArchetypesList(archetype); - } - - @Override - public void onStepLeave(MavenNewModuleContext context) - { - saveSettings(); - - updateDataModel(); - } - - public void updateDataModel() - { - // myContext.setProjectBuilder(myBuilder); - myContext.setAggregatorProject(myAggregator); - myContext.setParentProject(myParent); - - myContext.setProjectId(new MavenId(myGroupIdField.getText(), - myArtifactIdField.getText(), - myVersionField.getText())); - myContext.setInheritedOptions(myInheritGroupIdCheckBox.isSelected(), - myInheritVersionCheckBox.isSelected()); - - myContext.setArchetype(getSelectedArchetype()); - } - - private void loadSettings() - { - myContext.setInheritedOptions(getSavedValue(INHERIT_GROUP_ID_KEY, true), - getSavedValue(INHERIT_VERSION_KEY, true)); - - String archGroupId = getSavedValue(ARCHETYPE_GROUP_ID_KEY, null); - String archArtifactId = getSavedValue(ARCHETYPE_ARTIFACT_ID_KEY, null); - String archVersion = getSavedValue(ARCHETYPE_VERSION_KEY, null); - if(archGroupId == null || archArtifactId == null || archVersion == null) - { - myContext.setArchetype(null); - } - else - { - myContext.setArchetype(new MavenArchetype(archGroupId, archArtifactId, archVersion, null, null)); - } - } - - private void saveSettings() - { - saveValue(INHERIT_GROUP_ID_KEY, myInheritGroupIdCheckBox.isSelected()); - saveValue(INHERIT_VERSION_KEY, myInheritVersionCheckBox.isSelected()); - - MavenArchetype arch = getSelectedArchetype(); - saveValue(ARCHETYPE_GROUP_ID_KEY, arch == null ? null : arch.groupId); - saveValue(ARCHETYPE_ARTIFACT_ID_KEY, arch == null ? null : arch.artifactId); - saveValue(ARCHETYPE_VERSION_KEY, arch == null ? null : arch.version); - } - - private boolean getSavedValue(String key, boolean defaultValue) - { - return getSavedValue(key, String.valueOf(defaultValue)).equals(String.valueOf(true)); - } - - private static String getSavedValue(String key, String defaultValue) - { - String value = ApplicationPropertiesComponent.getInstance().getValue(key); - return value == null ? defaultValue : value; - } - - private void saveValue(String key, boolean value) - { - saveValue(key, String.valueOf(value)); - } - - private static void saveValue(String key, String value) - { - ApplicationPropertiesComponent props = ApplicationPropertiesComponent.getInstance(); - props.setValue(key, value); - } - - @RequiredUIAccess - @Nonnull - @Override - public Component getComponent(@Nonnull MavenNewModuleContext context, @Nonnull Disposable uiDisposable) - { - throw new UnsupportedOperationException("desktop only"); - } - - @Nonnull - @Override - public JComponent getSwingComponent(@Nonnull MavenNewModuleContext context, @Nonnull Disposable uiDisposable) - { - Disposer.register(uiDisposable, myLoadingIcon); - return myMainPanel; - } - - @Override - public void validateStep(@Nonnull MavenNewModuleContext context) throws WizardStepValidationException - { - if(StringUtil.isEmptyOrSpaces(myGroupIdField.getText())) - { - throw new WizardStepValidationException("Please, specify groupId"); - } - - if(StringUtil.isEmptyOrSpaces(myArtifactIdField.getText())) - { - throw new WizardStepValidationException("Please, specify artifactId"); - } - - if(StringUtil.isEmptyOrSpaces(myVersionField.getText())) - { - throw new WizardStepValidationException("Please, specify version"); - } - } - - @Override - public void onStepEnter(@Nonnull MavenNewModuleContext context) - { - updateStep(); - } - - public void updateStep() - { - if(skipUpdateUI) - { - return; - } - - if(isMavenizedProject()) - { - MavenProject parent = myContext.findPotentialParentProject(myProjectOrNull); - myAggregator = parent; - myParent = parent; - } - - MavenId projectId = myContext.getProjectId(); - - if(projectId == null) - { - myArtifactIdField.setText(myContext.getName()); - myGroupIdField.setText(myParent == null ? myContext.getName() : myParent.getMavenId().getGroupId()); - myVersionField.setText(myParent == null ? "1.0-SNAPSHOT" : myParent.getMavenId().getVersion()); - } - else - { - myArtifactIdField.setText(projectId.getArtifactId()); - myGroupIdField.setText(projectId.getGroupId()); - myVersionField.setText(projectId.getVersion()); - } - - myInheritGroupIdCheckBox.setSelected(myContext.isInheritGroupId()); - myInheritVersionCheckBox.setSelected(myContext.isInheritVersion()); - - MavenArchetype selectedArch = getSelectedArchetype(); - if(selectedArch == null) - { - selectedArch = myContext.getArchetype(); - } - if(selectedArch != null) - { - myUseArchetypeCheckBox.setSelected(true); - } - - if(myArchetypesTree.getRowCount() == 0) - { - updateArchetypesList(selectedArch); - } - updateComponents(); - } - - private void updateArchetypesList(final MavenArchetype selected) - { - ApplicationManager.getApplication().assertIsDispatchThread(); - - myLoadingIcon.setBackground(myArchetypesTree.getBackground()); - - ((CardLayout) myArchetypesPanel.getLayout()).show(myArchetypesPanel, "loading"); - - final Object currentUpdaterMarker = new Object(); - myCurrentUpdaterMarker = currentUpdaterMarker; - - ApplicationManager.getApplication().executeOnPooledThread((Runnable) () -> { - final Set archetypes = MavenIndicesManager.getInstance().getArchetypes(); - - SwingUtilities.invokeLater(() -> { - if(currentUpdaterMarker != myCurrentUpdaterMarker) - { - return; // Other updater has been run. - } - - ((CardLayout) myArchetypesPanel.getLayout()).show(myArchetypesPanel, "archetypes"); - - TreeNode root = groupAndSortArchetypes(archetypes); - TreeModel model = new DefaultTreeModel(root); - myArchetypesTree.setModel(model); - - if(selected != null) - { - TreePath path = findNodePath(selected, model, model.getRoot()); - if(path != null) - { - myArchetypesTree.expandPath(path.getParentPath()); - TreeUtil.selectPath(myArchetypesTree, path, true); - } - } - - updateArchetypeDescription(); - }); - }); - } - - private void updateArchetypeDescription() - { - MavenArchetype sel = getSelectedArchetype(); - String desc = sel == null ? null : sel.description; - if(StringUtil.isEmptyOrSpaces(desc)) - { - myArchetypeDescriptionScrollPane.setVisible(false); - } - else - { - myArchetypeDescriptionScrollPane.setVisible(true); - myArchetypeDescriptionField.setText(desc); - } - myMainPanel.revalidate(); - } - - @Nullable - private static TreePath findNodePath(MavenArchetype object, TreeModel model, Object parent) - { - for(int i = 0; i < model.getChildCount(parent); i++) - { - DefaultMutableTreeNode each = (DefaultMutableTreeNode) model.getChild(parent, i); - if(each.getUserObject().equals(object)) - { - return new TreePath(each.getPath()); - } - - TreePath result = findNodePath(object, model, each); - if(result != null) - { - return result; - } - } - return null; - } - - private static TreeNode groupAndSortArchetypes(Set archetypes) - { - List list = new ArrayList(archetypes); - - Collections.sort(list, (o1, o2) -> { - String key1 = o1.groupId + ":" + o1.artifactId; - String key2 = o2.groupId + ":" + o2.artifactId; - - int result = key1.compareToIgnoreCase(key2); - if(result != 0) - { - return result; - } - - return o2.version.compareToIgnoreCase(o1.version); - }); - - Map> map = new TreeMap>(); - - for(MavenArchetype each : list) - { - String key = each.groupId + ":" + each.artifactId; - List versions = map.get(key); - if(versions == null) - { - versions = new ArrayList(); - map.put(key, versions); - } - versions.add(each); - } - - DefaultMutableTreeNode result = new DefaultMutableTreeNode("root", true); - for(List each : map.values()) - { - MavenArchetype eachArchetype = each.get(0); - DefaultMutableTreeNode node = new DefaultMutableTreeNode(eachArchetype, true); - for(MavenArchetype eachVersion : each) - { - DefaultMutableTreeNode versionNode = new DefaultMutableTreeNode(eachVersion, false); - node.add(versionNode); - } - result.add(node); - } - - return result; - } - - private boolean isMavenizedProject() - { - return myProjectOrNull != null && MavenProjectsManager.getInstance(myProjectOrNull).isMavenizedProject(); - } - - private void updateComponents() - { - if(myParent == null) - { - myGroupIdField.setEnabled(true); - myVersionField.setEnabled(true); - myInheritGroupIdCheckBox.setEnabled(false); - myInheritVersionCheckBox.setEnabled(false); - } - else - { - myGroupIdField.setEnabled(!myInheritGroupIdCheckBox.isSelected()); - myVersionField.setEnabled(!myInheritVersionCheckBox.isSelected()); - - if(myInheritGroupIdCheckBox.isSelected() - || myGroupIdField.getText().equals(myInheritedGroupId)) - { - myGroupIdField.setText(myParent.getMavenId().getGroupId()); - } - if(myInheritVersionCheckBox.isSelected() - || myVersionField.getText().equals(myInheritedVersion)) - { - myVersionField.setText(myParent.getMavenId().getVersion()); - } - myInheritedGroupId = myGroupIdField.getText(); - myInheritedVersion = myVersionField.getText(); - - myInheritGroupIdCheckBox.setEnabled(true); - myInheritVersionCheckBox.setEnabled(true); - } - - boolean archetypesEnabled = myUseArchetypeCheckBox.isSelected(); - myAddArchetypeButton.setEnabled(archetypesEnabled); - myArchetypesTree.setEnabled(archetypesEnabled); - myArchetypesTree.setBackground(archetypesEnabled ? UIUtil.getListBackground() : UIUtil.getPanelBackground()); - } - - private static String formatProjectString(MavenProject project) - { - if(project == null) - { - return ""; - } - return project.getMavenId().getDisplayString(); - } - - @Nullable - private MavenArchetype getSelectedArchetype() - { - if(!myUseArchetypeCheckBox.isSelected() || myArchetypesTree.isSelectionEmpty()) - { - return null; - } - return getArchetypeInfoFromPathComponent(myArchetypesTree.getLastSelectedPathComponent()); - } - - private static MavenArchetype getArchetypeInfoFromPathComponent(Object sel) - { - return (MavenArchetype) ((DefaultMutableTreeNode) sel).getUserObject(); - } - - private static class MyRenderer extends ColoredTreeCellRenderer - { - public void customizeCellRenderer(JTree tree, - Object value, - boolean selected, - boolean expanded, - boolean leaf, - int row, - boolean hasFocus) - { - Object userObject = ((DefaultMutableTreeNode) value).getUserObject(); - if(!(userObject instanceof MavenArchetype)) - { - return; - } - - MavenArchetype info = (MavenArchetype) userObject; - - if(leaf) - { - append(info.artifactId, SimpleTextAttributes.GRAY_ATTRIBUTES); - append(":" + info.version, SimpleTextAttributes.REGULAR_ATTRIBUTES); - } - else - { - append(info.groupId + ":", SimpleTextAttributes.GRAY_ATTRIBUTES); - append(info.artifactId, SimpleTextAttributes.REGULAR_ATTRIBUTES); - } - } - } +public class MavenModuleWizardStep implements WizardStep { + private static final String INHERIT_GROUP_ID_KEY = "MavenModuleWizard.inheritGroupId"; + private static final String INHERIT_VERSION_KEY = "MavenModuleWizard.inheritVersion"; + private static final String ARCHETYPE_ARTIFACT_ID_KEY = "MavenModuleWizard.archetypeArtifactIdKey"; + private static final String ARCHETYPE_GROUP_ID_KEY = "MavenModuleWizard.archetypeGroupIdKey"; + private static final String ARCHETYPE_VERSION_KEY = "MavenModuleWizard.archetypeVersionKey"; + + private final Project myProjectOrNull; + private final MavenNewModuleContext myContext; + private MavenProject myAggregator; + private MavenProject myParent; + + private String myInheritedGroupId; + private String myInheritedVersion; + + private JPanel myMainPanel; + + private JTextField myGroupIdField; + private JCheckBox myInheritGroupIdCheckBox; + private JTextField myArtifactIdField; + private JTextField myVersionField; + private JCheckBox myInheritVersionCheckBox; + + private JCheckBox myUseArchetypeCheckBox; + private JButton myAddArchetypeButton; + private JScrollPane myArchetypesScrollPane; + private JPanel myArchetypesPanel; + private Tree myArchetypesTree; + private JScrollPane myArchetypeDescriptionScrollPane; + private JTextArea myArchetypeDescriptionField; + + private Object myCurrentUpdaterMarker; + private final AsyncProcessIcon myLoadingIcon = new AsyncProcessIcon.Big(getClass() + ".loading"); + + private boolean skipUpdateUI; + + public MavenModuleWizardStep(MavenNewModuleContext context) { + myProjectOrNull = null; + myContext = context; + + initComponents(); + loadSettings(); + } + + private void initComponents() { + myArchetypesTree = new Tree(); + myArchetypesTree.setModel(new DefaultTreeModel(new DefaultMutableTreeNode())); + myArchetypesScrollPane = ScrollPaneFactory.createScrollPane(myArchetypesTree); + + myArchetypesPanel.add(myArchetypesScrollPane, "archetypes"); + + JPanel loadingPanel = new JPanel(new GridBagLayout()); + JPanel bp = new JPanel(new BorderLayout(10, 10)); + bp.add(new JLabel("Loading archetype list..."), BorderLayout.NORTH); + bp.add(myLoadingIcon, BorderLayout.CENTER); + + loadingPanel.add(bp, new GridBagConstraints()); + + myArchetypesPanel.add(ScrollPaneFactory.createScrollPane(loadingPanel), "loading"); + ((CardLayout)myArchetypesPanel.getLayout()).show(myArchetypesPanel, "archetypes"); + + ActionListener updatingListener = e -> updateComponents(); + myInheritGroupIdCheckBox.addActionListener(updatingListener); + myInheritVersionCheckBox.addActionListener(updatingListener); + + myUseArchetypeCheckBox.addActionListener(updatingListener); + myUseArchetypeCheckBox.addActionListener(e -> archetypeMayBeChanged()); + + myAddArchetypeButton.addActionListener(e -> doAddArchetype()); + + myArchetypesTree.setRootVisible(false); + myArchetypesTree.setShowsRootHandles(true); + myArchetypesTree.setCellRenderer(new MyRenderer()); + myArchetypesTree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION); + + myArchetypesTree.getSelectionModel().addTreeSelectionListener(e -> { + updateArchetypeDescription(); + archetypeMayBeChanged(); + }); + + new TreeSpeedSearch(myArchetypesTree, path -> { + MavenArchetype info = getArchetypeInfoFromPathComponent(path.getLastPathComponent()); + return info.groupId + ":" + info.artifactId + ":" + info.version; + }).setComparator(new SpeedSearchComparator(false)); + + myArchetypeDescriptionField.setEditable(false); + myArchetypeDescriptionField.setBackground(UIUtil.getPanelBackground()); + } + + private void archetypeMayBeChanged() { + MavenArchetype selectedArchetype = getSelectedArchetype(); + if (((myContext.getArchetype() == null) != (selectedArchetype == null))) { + myContext.setArchetype(selectedArchetype); + skipUpdateUI = true; + try { + //fireStateChanged(); + } + finally { + skipUpdateUI = false; + } + } + } + + @Override + public JComponent getSwingPreferredFocusedComponent() { + return myGroupIdField; + } + + private MavenProject doSelectProject(MavenProject current) { + assert myProjectOrNull != null : "must not be called when creating a new project"; + + SelectMavenProjectDialog d = new SelectMavenProjectDialog(myProjectOrNull, current); + d.show(); + if (!d.isOK()) { + return current; + } + return d.getResult(); + } + + private void doAddArchetype() { + MavenAddArchetypeDialog dialog = new MavenAddArchetypeDialog(myMainPanel); + dialog.show(); + if (!dialog.isOK()) { + return; + } + + MavenArchetype archetype = dialog.getArchetype(); + MavenIndicesManager.getInstance().addArchetype(archetype); + updateArchetypesList(archetype); + } + + @Override + public void onStepLeave(MavenNewModuleContext context) { + saveSettings(); + + updateDataModel(); + } + + public void updateDataModel() { + // myContext.setProjectBuilder(myBuilder); + myContext.setAggregatorProject(myAggregator); + myContext.setParentProject(myParent); + + myContext.setProjectId(new MavenId( + myGroupIdField.getText(), + myArtifactIdField.getText(), + myVersionField.getText() + )); + myContext.setInheritedOptions( + myInheritGroupIdCheckBox.isSelected(), + myInheritVersionCheckBox.isSelected() + ); + + myContext.setArchetype(getSelectedArchetype()); + } + + private void loadSettings() { + myContext.setInheritedOptions( + getSavedValue(INHERIT_GROUP_ID_KEY, true), + getSavedValue(INHERIT_VERSION_KEY, true) + ); + + String archGroupId = getSavedValue(ARCHETYPE_GROUP_ID_KEY, null); + String archArtifactId = getSavedValue(ARCHETYPE_ARTIFACT_ID_KEY, null); + String archVersion = getSavedValue(ARCHETYPE_VERSION_KEY, null); + if (archGroupId == null || archArtifactId == null || archVersion == null) { + myContext.setArchetype(null); + } + else { + myContext.setArchetype(new MavenArchetype(archGroupId, archArtifactId, archVersion, null, null)); + } + } + + private void saveSettings() { + saveValue(INHERIT_GROUP_ID_KEY, myInheritGroupIdCheckBox.isSelected()); + saveValue(INHERIT_VERSION_KEY, myInheritVersionCheckBox.isSelected()); + + MavenArchetype arch = getSelectedArchetype(); + saveValue(ARCHETYPE_GROUP_ID_KEY, arch == null ? null : arch.groupId); + saveValue(ARCHETYPE_ARTIFACT_ID_KEY, arch == null ? null : arch.artifactId); + saveValue(ARCHETYPE_VERSION_KEY, arch == null ? null : arch.version); + } + + private boolean getSavedValue(String key, boolean defaultValue) { + return getSavedValue(key, String.valueOf(defaultValue)).equals(String.valueOf(true)); + } + + private static String getSavedValue(String key, String defaultValue) { + String value = ApplicationPropertiesComponent.getInstance().getValue(key); + return value == null ? defaultValue : value; + } + + private void saveValue(String key, boolean value) { + saveValue(key, String.valueOf(value)); + } + + private static void saveValue(String key, String value) { + ApplicationPropertiesComponent props = ApplicationPropertiesComponent.getInstance(); + props.setValue(key, value); + } + + @RequiredUIAccess + @Nonnull + @Override + public Component getComponent(@Nonnull MavenNewModuleContext context, @Nonnull Disposable uiDisposable) { + throw new UnsupportedOperationException("desktop only"); + } + + @Nonnull + @Override + public JComponent getSwingComponent(@Nonnull MavenNewModuleContext context, @Nonnull Disposable uiDisposable) { + Disposer.register(uiDisposable, myLoadingIcon); + return myMainPanel; + } + + @Override + public void validateStep(@Nonnull MavenNewModuleContext context) throws WizardStepValidationException { + if (StringUtil.isEmptyOrSpaces(myGroupIdField.getText())) { + throw new WizardStepValidationException("Please, specify groupId"); + } + + if (StringUtil.isEmptyOrSpaces(myArtifactIdField.getText())) { + throw new WizardStepValidationException("Please, specify artifactId"); + } + + if (StringUtil.isEmptyOrSpaces(myVersionField.getText())) { + throw new WizardStepValidationException("Please, specify version"); + } + } + + @Override + public void onStepEnter(@Nonnull MavenNewModuleContext context) { + updateStep(); + } + + public void updateStep() { + if (skipUpdateUI) { + return; + } + + if (isMavenizedProject()) { + MavenProject parent = myContext.findPotentialParentProject(myProjectOrNull); + myAggregator = parent; + myParent = parent; + } + + MavenId projectId = myContext.getProjectId(); + + if (projectId == null) { + myArtifactIdField.setText(myContext.getName()); + myGroupIdField.setText(myParent == null ? myContext.getName() : myParent.getMavenId().getGroupId()); + myVersionField.setText(myParent == null ? "1.0-SNAPSHOT" : myParent.getMavenId().getVersion()); + } + else { + myArtifactIdField.setText(projectId.getArtifactId()); + myGroupIdField.setText(projectId.getGroupId()); + myVersionField.setText(projectId.getVersion()); + } + + myInheritGroupIdCheckBox.setSelected(myContext.isInheritGroupId()); + myInheritVersionCheckBox.setSelected(myContext.isInheritVersion()); + + MavenArchetype selectedArch = getSelectedArchetype(); + if (selectedArch == null) { + selectedArch = myContext.getArchetype(); + } + if (selectedArch != null) { + myUseArchetypeCheckBox.setSelected(true); + } + + if (myArchetypesTree.getRowCount() == 0) { + updateArchetypesList(selectedArch); + } + updateComponents(); + } + + private void updateArchetypesList(final MavenArchetype selected) { + ApplicationManager.getApplication().assertIsDispatchThread(); + + myLoadingIcon.setBackground(myArchetypesTree.getBackground()); + + ((CardLayout)myArchetypesPanel.getLayout()).show(myArchetypesPanel, "loading"); + + final Object currentUpdaterMarker = new Object(); + myCurrentUpdaterMarker = currentUpdaterMarker; + + ApplicationManager.getApplication().executeOnPooledThread((Runnable)() -> { + final Set archetypes = MavenIndicesManager.getInstance().getArchetypes(); + + SwingUtilities.invokeLater(() -> { + if (currentUpdaterMarker != myCurrentUpdaterMarker) { + return; // Other updater has been run. + } + + ((CardLayout)myArchetypesPanel.getLayout()).show(myArchetypesPanel, "archetypes"); + + TreeNode root = groupAndSortArchetypes(archetypes); + TreeModel model = new DefaultTreeModel(root); + myArchetypesTree.setModel(model); + + if (selected != null) { + TreePath path = findNodePath(selected, model, model.getRoot()); + if (path != null) { + myArchetypesTree.expandPath(path.getParentPath()); + TreeUtil.selectPath(myArchetypesTree, path, true); + } + } + + updateArchetypeDescription(); + }); + }); + } + + private void updateArchetypeDescription() { + MavenArchetype sel = getSelectedArchetype(); + String desc = sel == null ? null : sel.description; + if (StringUtil.isEmptyOrSpaces(desc)) { + myArchetypeDescriptionScrollPane.setVisible(false); + } + else { + myArchetypeDescriptionScrollPane.setVisible(true); + myArchetypeDescriptionField.setText(desc); + } + myMainPanel.revalidate(); + } + + @Nullable + private static TreePath findNodePath(MavenArchetype object, TreeModel model, Object parent) { + for (int i = 0; i < model.getChildCount(parent); i++) { + DefaultMutableTreeNode each = (DefaultMutableTreeNode)model.getChild(parent, i); + if (each.getUserObject().equals(object)) { + return new TreePath(each.getPath()); + } + + TreePath result = findNodePath(object, model, each); + if (result != null) { + return result; + } + } + return null; + } + + private static TreeNode groupAndSortArchetypes(Set archetypes) { + List list = new ArrayList<>(archetypes); + + Collections.sort(list, (o1, o2) -> { + String key1 = o1.groupId + ":" + o1.artifactId; + String key2 = o2.groupId + ":" + o2.artifactId; + + int result = key1.compareToIgnoreCase(key2); + if (result != 0) { + return result; + } + + return o2.version.compareToIgnoreCase(o1.version); + }); + + Map> map = new TreeMap<>(); + + for (MavenArchetype each : list) { + String key = each.groupId + ":" + each.artifactId; + List versions = map.get(key); + if (versions == null) { + versions = new ArrayList<>(); + map.put(key, versions); + } + versions.add(each); + } + + DefaultMutableTreeNode result = new DefaultMutableTreeNode("root", true); + for (List each : map.values()) { + MavenArchetype eachArchetype = each.get(0); + DefaultMutableTreeNode node = new DefaultMutableTreeNode(eachArchetype, true); + for (MavenArchetype eachVersion : each) { + DefaultMutableTreeNode versionNode = new DefaultMutableTreeNode(eachVersion, false); + node.add(versionNode); + } + result.add(node); + } + + return result; + } + + private boolean isMavenizedProject() { + return myProjectOrNull != null && MavenProjectsManager.getInstance(myProjectOrNull).isMavenizedProject(); + } + + private void updateComponents() { + if (myParent == null) { + myGroupIdField.setEnabled(true); + myVersionField.setEnabled(true); + myInheritGroupIdCheckBox.setEnabled(false); + myInheritVersionCheckBox.setEnabled(false); + } + else { + myGroupIdField.setEnabled(!myInheritGroupIdCheckBox.isSelected()); + myVersionField.setEnabled(!myInheritVersionCheckBox.isSelected()); + + if (myInheritGroupIdCheckBox.isSelected() + || myGroupIdField.getText().equals(myInheritedGroupId)) { + myGroupIdField.setText(myParent.getMavenId().getGroupId()); + } + if (myInheritVersionCheckBox.isSelected() + || myVersionField.getText().equals(myInheritedVersion)) { + myVersionField.setText(myParent.getMavenId().getVersion()); + } + myInheritedGroupId = myGroupIdField.getText(); + myInheritedVersion = myVersionField.getText(); + + myInheritGroupIdCheckBox.setEnabled(true); + myInheritVersionCheckBox.setEnabled(true); + } + + boolean archetypesEnabled = myUseArchetypeCheckBox.isSelected(); + myAddArchetypeButton.setEnabled(archetypesEnabled); + myArchetypesTree.setEnabled(archetypesEnabled); + myArchetypesTree.setBackground(archetypesEnabled ? UIUtil.getListBackground() : UIUtil.getPanelBackground()); + } + + private static String formatProjectString(MavenProject project) { + if (project == null) { + return ""; + } + return project.getMavenId().getDisplayString(); + } + + @Nullable + private MavenArchetype getSelectedArchetype() { + if (!myUseArchetypeCheckBox.isSelected() || myArchetypesTree.isSelectionEmpty()) { + return null; + } + return getArchetypeInfoFromPathComponent(myArchetypesTree.getLastSelectedPathComponent()); + } + + private static MavenArchetype getArchetypeInfoFromPathComponent(Object sel) { + return (MavenArchetype)((DefaultMutableTreeNode)sel).getUserObject(); + } + + private static class MyRenderer extends ColoredTreeCellRenderer { + public void customizeCellRenderer( + JTree tree, + Object value, + boolean selected, + boolean expanded, + boolean leaf, + int row, + boolean hasFocus + ) { + Object userObject = ((DefaultMutableTreeNode)value).getUserObject(); + if (!(userObject instanceof MavenArchetype)) { + return; + } + + MavenArchetype info = (MavenArchetype)userObject; + + if (leaf) { + append(info.artifactId, SimpleTextAttributes.GRAY_ATTRIBUTES); + append(":" + info.version, SimpleTextAttributes.REGULAR_ATTRIBUTES); + } + else { + append(info.groupId + ":", SimpleTextAttributes.GRAY_ATTRIBUTES); + append(info.artifactId, SimpleTextAttributes.REGULAR_ATTRIBUTES); + } + } + } } diff --git a/plugin/src/main/java/org/jetbrains/idea/maven/wizards/MavenProjectImportStep.java b/plugin/src/main/java/org/jetbrains/idea/maven/wizards/MavenProjectImportStep.java index 653a4c9a..3b63cdc9 100644 --- a/plugin/src/main/java/org/jetbrains/idea/maven/wizards/MavenProjectImportStep.java +++ b/plugin/src/main/java/org/jetbrains/idea/maven/wizards/MavenProjectImportStep.java @@ -35,165 +35,149 @@ import java.awt.event.ActionEvent; import java.awt.event.ActionListener; -public class MavenProjectImportStep implements WizardStep -{ - private final JPanel myPanel; - private final NamePathComponent myRootPathComponent; - private final MavenImportingSettingsForm myImportingSettingsForm; - private final MavenImportModuleContext myContext; - - public MavenProjectImportStep(MavenImportModuleContext context) - { - myContext = context; - - myImportingSettingsForm = new MavenImportingSettingsForm(true, context.isNewProject()); - - myRootPathComponent = new NamePathComponent("", ProjectBundle.message("maven.import.label.select.root"), ProjectBundle.message("maven.import.title.select.root"), "", false, false); - - JButton envSettingsButton = new JButton(ProjectBundle.message("maven.import.environment.settings")); - envSettingsButton.addActionListener(new ActionListener() - { - @Override - public void actionPerformed(ActionEvent e) - { - ShowSettingsUtil.getInstance().editConfigurable(myPanel, new MavenEnvironmentConfigurable()); - } - }); - - myPanel = new JPanel(new GridBagLayout()); - - GridBagConstraints c = new GridBagConstraints(); - c.gridx = 0; - c.gridy = 0; - c.weightx = 1; - c.fill = GridBagConstraints.HORIZONTAL; - c.insets = new Insets(4, 4, 0, 4); - - myPanel.add(myRootPathComponent, c); - - c.gridy = 1; - c.insets = new Insets(4, 4, 0, 4); - myPanel.add(myImportingSettingsForm.createComponent(), c); - - c.gridy = 2; - c.fill = GridBagConstraints.NONE; - c.anchor = GridBagConstraints.NORTHEAST; - c.weighty = 1; - c.insets = new Insets(4 + envSettingsButton.getPreferredSize().height, 4, 4, 4); - myPanel.add(envSettingsButton, c); - - myRootPathComponent.setNameComponentVisible(false); - } - - @RequiredUIAccess - @Nonnull - @Override - public Component getComponent(@Nonnull MavenImportModuleContext context, @Nonnull Disposable disposable) - { - throw new UnsupportedOperationException("destop only"); - } - - @RequiredUIAccess - @Nonnull - @Override - public JComponent getSwingComponent(@Nonnull MavenImportModuleContext context, @Nonnull Disposable disposable) - { - return myPanel; - } - - @Override - public void onStepEnter(@Nonnull MavenImportModuleContext mavenImportModuleContext) - { - if(!myRootPathComponent.isPathChangedByUser()) - { - final VirtualFile rootDirectory = myContext.getRootDirectory(); - final String path; - if(rootDirectory != null) - { - path = rootDirectory.getPath(); - } - else - { - path = myContext.getPath(); - } - if(path != null) - { - myRootPathComponent.setPath(FileUtil.toSystemDependentName(path)); - myRootPathComponent.getPathComponent().selectAll(); - } - } - myImportingSettingsForm.setData(getImportingSettings()); - } - - @Override - public void onStepLeave(@Nonnull MavenImportModuleContext mavenImportModuleContext) - { - MavenImportingSettings settings = getImportingSettings(); - myImportingSettingsForm.getData(settings); - suggestProjectNameAndPath(settings.getDedicatedModuleDir(), myRootPathComponent.getPath()); - myContext.setRootDirectory(myContext.getProject(), myRootPathComponent.getPath()); - } - - protected void suggestProjectNameAndPath(final String alternativePath, final String path) - { - myContext.setPath(alternativePath != null && alternativePath.length() > 0 ? alternativePath : path); - final String global = FileUtil.toSystemIndependentName(path); - myContext.setName(global.substring(global.lastIndexOf("/") + 1)); - } - - @Override - public JComponent getSwingPreferredFocusedComponent() - { - return myRootPathComponent.getPathComponent(); - } - - private MavenGeneralSettings getGeneralSettings() - { - return myContext.getGeneralSettings(); - } - - private MavenImportingSettings getImportingSettings() - { - return myContext.getImportingSettings(); - } - - class MavenEnvironmentConfigurable implements Configurable - { - MavenEnvironmentForm myForm = new MavenEnvironmentForm(); - - @Override - @Nls - public String getDisplayName() - { - return ProjectBundle.message("maven.import.environment.settings.title"); - } - - @RequiredUIAccess - @Override - public JComponent createComponent(@Nonnull Disposable uiDisposable) - { - return myForm.createComponent(uiDisposable); - } - - @RequiredUIAccess - @Override - public boolean isModified() - { - return myForm.isModified(getGeneralSettings()); - } - - @RequiredUIAccess - @Override - public void apply() throws ConfigurationException - { - myForm.setData(getGeneralSettings()); - } - - @RequiredUIAccess - @Override - public void reset() - { - myForm.getData(getGeneralSettings()); - } - } +public class MavenProjectImportStep implements WizardStep { + private final JPanel myPanel; + private final NamePathComponent myRootPathComponent; + private final MavenImportingSettingsForm myImportingSettingsForm; + private final MavenImportModuleContext myContext; + + public MavenProjectImportStep(MavenImportModuleContext context) { + myContext = context; + + myImportingSettingsForm = new MavenImportingSettingsForm(true, context.isNewProject()); + + myRootPathComponent = new NamePathComponent("", + ProjectBundle.message("maven.import.label.select.root"), + ProjectBundle.message("maven.import.title.select.root"), + "", + false, + false + ); + + JButton envSettingsButton = new JButton(ProjectBundle.message("maven.import.environment.settings")); + envSettingsButton.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + ShowSettingsUtil.getInstance().editConfigurable(myPanel, new MavenEnvironmentConfigurable()); + } + }); + + myPanel = new JPanel(new GridBagLayout()); + + GridBagConstraints c = new GridBagConstraints(); + c.gridx = 0; + c.gridy = 0; + c.weightx = 1; + c.fill = GridBagConstraints.HORIZONTAL; + c.insets = new Insets(4, 4, 0, 4); + + myPanel.add(myRootPathComponent, c); + + c.gridy = 1; + c.insets = new Insets(4, 4, 0, 4); + myPanel.add(myImportingSettingsForm.createComponent(), c); + + c.gridy = 2; + c.fill = GridBagConstraints.NONE; + c.anchor = GridBagConstraints.NORTHEAST; + c.weighty = 1; + c.insets = new Insets(4 + envSettingsButton.getPreferredSize().height, 4, 4, 4); + myPanel.add(envSettingsButton, c); + + myRootPathComponent.setNameComponentVisible(false); + } + + @RequiredUIAccess + @Nonnull + @Override + public Component getComponent(@Nonnull MavenImportModuleContext context, @Nonnull Disposable disposable) { + throw new UnsupportedOperationException("destop only"); + } + + @RequiredUIAccess + @Nonnull + @Override + public JComponent getSwingComponent(@Nonnull MavenImportModuleContext context, @Nonnull Disposable disposable) { + return myPanel; + } + + @Override + public void onStepEnter(@Nonnull MavenImportModuleContext mavenImportModuleContext) { + if (!myRootPathComponent.isPathChangedByUser()) { + final VirtualFile rootDirectory = myContext.getRootDirectory(); + final String path; + if (rootDirectory != null) { + path = rootDirectory.getPath(); + } + else { + path = myContext.getPath(); + } + if (path != null) { + myRootPathComponent.setPath(FileUtil.toSystemDependentName(path)); + myRootPathComponent.getPathComponent().selectAll(); + } + } + myImportingSettingsForm.setData(getImportingSettings()); + } + + @Override + public void onStepLeave(@Nonnull MavenImportModuleContext mavenImportModuleContext) { + MavenImportingSettings settings = getImportingSettings(); + myImportingSettingsForm.getData(settings); + suggestProjectNameAndPath(settings.getDedicatedModuleDir(), myRootPathComponent.getPath()); + myContext.setRootDirectory(myContext.getProject(), myRootPathComponent.getPath()); + } + + protected void suggestProjectNameAndPath(final String alternativePath, final String path) { + myContext.setPath(alternativePath != null && alternativePath.length() > 0 ? alternativePath : path); + final String global = FileUtil.toSystemIndependentName(path); + myContext.setName(global.substring(global.lastIndexOf("/") + 1)); + } + + @Override + public JComponent getSwingPreferredFocusedComponent() { + return myRootPathComponent.getPathComponent(); + } + + private MavenGeneralSettings getGeneralSettings() { + return myContext.getGeneralSettings(); + } + + private MavenImportingSettings getImportingSettings() { + return myContext.getImportingSettings(); + } + + class MavenEnvironmentConfigurable implements Configurable { + MavenEnvironmentForm myForm = new MavenEnvironmentForm(); + + @Override + @Nls + public String getDisplayName() { + return ProjectBundle.message("maven.import.environment.settings.title"); + } + + @RequiredUIAccess + @Override + public JComponent createComponent(@Nonnull Disposable uiDisposable) { + return myForm.createComponent(uiDisposable); + } + + @RequiredUIAccess + @Override + public boolean isModified() { + return myForm.isModified(getGeneralSettings()); + } + + @RequiredUIAccess + @Override + public void apply() throws ConfigurationException { + myForm.setData(getGeneralSettings()); + } + + @RequiredUIAccess + @Override + public void reset() { + myForm.getData(getGeneralSettings()); + } + } } diff --git a/plugin/src/main/java/org/jetbrains/idea/maven/wizards/SelectImportedProjectsStep.java b/plugin/src/main/java/org/jetbrains/idea/maven/wizards/SelectImportedProjectsStep.java index 3812343e..cf8692ac 100644 --- a/plugin/src/main/java/org/jetbrains/idea/maven/wizards/SelectImportedProjectsStep.java +++ b/plugin/src/main/java/org/jetbrains/idea/maven/wizards/SelectImportedProjectsStep.java @@ -42,146 +42,157 @@ /** * @author Vladislav.Kaznacheev */ -public abstract class SelectImportedProjectsStep implements WizardStep -{ - private final JPanel panel; - protected final ElementsChooser fileChooser; - protected final MavenImportModuleContext myContext; - - public SelectImportedProjectsStep(MavenImportModuleContext context) - { - myContext = context; - fileChooser = new ElementsChooser(true) - { - @Override - protected String getItemText(@Nonnull MavenProject item) - { - return getElementText(item); - } - - @Override - protected Image getItemIcon(@Nonnull final MavenProject item) - { - return getElementIcon(item); - } - }; - - panel = new JPanel(new GridLayoutManager(3, 1, JBUI.emptyInsets(), -1, -1)); - - panel.add(fileChooser, new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_NORTH, GridConstraints.FILL_BOTH, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_WANT_GROW, - GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_WANT_GROW, null, null, null)); - - final AnAction selectAllAction = new AnAction(RefactoringBundle.message("select.all.button"), null, PlatformIconGroup.actionsSelectall()) - { - @RequiredUIAccess - @Override - public void actionPerformed(@Nonnull AnActionEvent e) - { - fileChooser.setAllElementsMarked(true); - } - - @Override - public boolean displayTextInToolbar() - { - return true; - } - }; - final AnAction unselectAllAction = new AnAction(RefactoringBundle.message("unselect.all.button"), null, PlatformIconGroup.actionsUnselectall()) - { - @RequiredUIAccess - @Override - public void actionPerformed(@Nonnull AnActionEvent e) - { - fileChooser.setAllElementsMarked(false); - } - - @Override - public boolean displayTextInToolbar() - { - return true; - } - }; - ActionToolbar toolbar = ActionManager.getInstance().createActionToolbar(ActionPlaces.UNKNOWN, new DefaultActionGroup(selectAllAction, unselectAllAction), true); - toolbar.setTargetComponent(panel); - final JComponent actionToolbar = toolbar.getComponent(); - panel.add(actionToolbar, new GridConstraints(1, 0, 1, 1, GridConstraints.ANCHOR_NORTH, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints - .SIZEPOLICY_WANT_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK, null, null, null)); - } - - @Nullable - protected Image getElementIcon(final MavenProject item) - { - return null; - } - - protected abstract String getElementText(final MavenProject item); - - @RequiredUIAccess - @Nonnull - @Override - public Component getComponent(@Nonnull MavenImportModuleContext context, @Nonnull Disposable disposable) - { - throw new UnsupportedOperationException("desktop only"); - } - - @RequiredUIAccess - @Nonnull - @Override - public JComponent getSwingComponent(@Nonnull MavenImportModuleContext context, @Nonnull Disposable disposable) - { - return panel; - } - - protected boolean isElementEnabled(MavenProject element) - { - return true; - } - - @Override - public void onStepEnter(@Nonnull MavenImportModuleContext context) - { - fileChooser.clear(); - List list = context.getList(); - if(list != null) - { - for(MavenProject element : list) - { - boolean isEnabled = isElementEnabled(element); - fileChooser.addElement(element, isEnabled && getContext().isMarked(element)); - if(!isEnabled) - { - fileChooser.disableElement(element); - } - } - } - - fileChooser.setBorder(IdeBorderFactory.createTitledBorder(IdeBundle.message("project.import.select.title", ProjectBundle.message("maven.name")), false)); - } - - @Override - public void onStepLeave(@Nonnull MavenImportModuleContext context) - { - context.setList(fileChooser.getMarkedElements()); - - updateDataModel(); - } - - @Override - public void validateStep(@Nonnull MavenImportModuleContext context) throws WizardStepValidationException - { - onStepLeave(context); - if(fileChooser.getMarkedElements().size() == 0) - { - throw new WizardStepValidationException("Nothing found to import"); - } - } - - public void updateDataModel() - { - } - - public MavenImportModuleContext getContext() - { - return myContext; - } +public abstract class SelectImportedProjectsStep implements WizardStep { + private final JPanel panel; + protected final ElementsChooser fileChooser; + protected final MavenImportModuleContext myContext; + + public SelectImportedProjectsStep(MavenImportModuleContext context) { + myContext = context; + fileChooser = new ElementsChooser<>(true) { + @Override + protected String getItemText(@Nonnull MavenProject item) { + return getElementText(item); + } + + @Override + protected Image getItemIcon(@Nonnull final MavenProject item) { + return getElementIcon(item); + } + }; + + panel = new JPanel(new GridLayoutManager(3, 1, JBUI.emptyInsets(), -1, -1)); + + panel.add(fileChooser, new GridConstraints( + 0, + 0, + 1, + 1, + GridConstraints.ANCHOR_NORTH, + GridConstraints.FILL_BOTH, + GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_WANT_GROW, + GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_WANT_GROW, + null, + null, + null + )); + + final AnAction selectAllAction = + new AnAction(RefactoringBundle.message("select.all.button"), null, PlatformIconGroup.actionsSelectall()) { + @RequiredUIAccess + @Override + public void actionPerformed(@Nonnull AnActionEvent e) { + fileChooser.setAllElementsMarked(true); + } + + @Override + public boolean displayTextInToolbar() { + return true; + } + }; + final AnAction unselectAllAction = + new AnAction(RefactoringBundle.message("unselect.all.button"), null, PlatformIconGroup.actionsUnselectall()) { + @RequiredUIAccess + @Override + public void actionPerformed(@Nonnull AnActionEvent e) { + fileChooser.setAllElementsMarked(false); + } + + @Override + public boolean displayTextInToolbar() { + return true; + } + }; + ActionToolbar toolbar = ActionManager.getInstance() + .createActionToolbar(ActionPlaces.UNKNOWN, new DefaultActionGroup(selectAllAction, unselectAllAction), true); + toolbar.setTargetComponent(panel); + final JComponent actionToolbar = toolbar.getComponent(); + panel.add( + actionToolbar, + new GridConstraints( + 1, + 0, + 1, + 1, + GridConstraints.ANCHOR_NORTH, + GridConstraints.FILL_HORIZONTAL, + GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints + .SIZEPOLICY_WANT_GROW, + GridConstraints.SIZEPOLICY_CAN_SHRINK, + null, + null, + null + ) + ); + } + + @Nullable + protected Image getElementIcon(final MavenProject item) { + return null; + } + + protected abstract String getElementText(final MavenProject item); + + @RequiredUIAccess + @Nonnull + @Override + public Component getComponent(@Nonnull MavenImportModuleContext context, @Nonnull Disposable disposable) { + throw new UnsupportedOperationException("desktop only"); + } + + @RequiredUIAccess + @Nonnull + @Override + public JComponent getSwingComponent(@Nonnull MavenImportModuleContext context, @Nonnull Disposable disposable) { + return panel; + } + + protected boolean isElementEnabled(MavenProject element) { + return true; + } + + @Override + public void onStepEnter(@Nonnull MavenImportModuleContext context) { + fileChooser.clear(); + List list = context.getList(); + if (list != null) { + for (MavenProject element : list) { + boolean isEnabled = isElementEnabled(element); + fileChooser.addElement(element, isEnabled && getContext().isMarked(element)); + if (!isEnabled) { + fileChooser.disableElement(element); + } + } + } + + fileChooser.setBorder(IdeBorderFactory.createTitledBorder( + IdeBundle.message( + "project.import.select.title", + ProjectBundle.message("maven.name") + ), + false + )); + } + + @Override + public void onStepLeave(@Nonnull MavenImportModuleContext context) { + context.setList(fileChooser.getMarkedElements()); + + updateDataModel(); + } + + @Override + public void validateStep(@Nonnull MavenImportModuleContext context) throws WizardStepValidationException { + onStepLeave(context); + if (fileChooser.getMarkedElements().size() == 0) { + throw new WizardStepValidationException("Nothing found to import"); + } + } + + public void updateDataModel() { + } + + public MavenImportModuleContext getContext() { + return myContext; + } } diff --git a/plugin/src/main/java/org/jetbrains/idea/maven/wizards/SelectProfilesStep.java b/plugin/src/main/java/org/jetbrains/idea/maven/wizards/SelectProfilesStep.java index 1ef2c833..e230bff6 100644 --- a/plugin/src/main/java/org/jetbrains/idea/maven/wizards/SelectProfilesStep.java +++ b/plugin/src/main/java/org/jetbrains/idea/maven/wizards/SelectProfilesStep.java @@ -34,200 +34,178 @@ /** * @author Vladislav.Kaznacheev */ -public class SelectProfilesStep implements WizardStep -{ - private JPanel panel; - private MultiStateElementsChooser profileChooser; - private MavenProfileKindMarkStateDescriptor myMarkStateDescriptor; - - private final MavenImportModuleContext myContext; - - public SelectProfilesStep(MavenImportModuleContext context) - { - myContext = context; - } - - @Override - public boolean isVisible(MavenImportModuleContext context) - { - return !myContext.getProfiles().isEmpty(); - } - - public void createUIComponents() - { - myMarkStateDescriptor = new MavenProfileKindMarkStateDescriptor(); - profileChooser = new MultiStateElementsChooser<>(true, myMarkStateDescriptor); - } - - @RequiredUIAccess - @Nonnull - @Override - public consulo.ui.Component getComponent(@Nonnull MavenImportModuleContext context, @Nonnull Disposable uiDisposable) - { - throw new UnsupportedOperationException("desktop only"); - } - - @Override - public JComponent getSwingComponent(@Nonnull MavenImportModuleContext context, @Nonnull Disposable uiDisposable) - { - return panel; - } - - @Override - public void onStepEnter(@Nonnull MavenImportModuleContext mavenImportModuleContext) - { - List allProfiles = myContext.getProfiles(); - List activatedProfiles = myContext.getActivatedProfiles(); - MavenExplicitProfiles selectedProfiles = myContext.getSelectedProfiles(); - List enabledProfiles = new ArrayList<>(selectedProfiles.getEnabledProfiles()); - List disabledProfiles = new ArrayList<>(selectedProfiles.getDisabledProfiles()); - enabledProfiles.retainAll(allProfiles); // mark only existing profiles - disabledProfiles.retainAll(allProfiles); // mark only existing profiles - - myMarkStateDescriptor.setActivatedProfiles(activatedProfiles); - profileChooser.setElements(allProfiles, null); - profileChooser.markElements(enabledProfiles, MavenProfileKind.EXPLICIT); - profileChooser.markElements(disabledProfiles, MavenProfileKind.NONE); - } - - @Override - public void onStepLeave(@Nonnull MavenImportModuleContext context) - { - Collection activatedProfiles = myMarkStateDescriptor.getActivatedProfiles(); - MavenExplicitProfiles newSelectedProfiles = MavenExplicitProfiles.NONE.clone(); - for(Map.Entry entry : profileChooser.getElementMarkStates().entrySet()) - { - String profile = entry.getKey(); - MavenProfileKind profileKind = entry.getValue(); - switch(profileKind) - { - case NONE: - if(activatedProfiles.contains(profile)) - { - newSelectedProfiles.getDisabledProfiles().add(profile); - } - break; - case EXPLICIT: - newSelectedProfiles.getEnabledProfiles().add(profile); - break; - case IMPLICIT: - break; - } - } - myContext.setSelectedProfiles(newSelectedProfiles); - } - - private static class MavenProfileKindMarkStateDescriptor implements MultiStateElementsChooser.MarkStateDescriptor - { - private Collection myActivatedProfiles = Collections.emptySet(); - - public Collection getActivatedProfiles() - { - return myActivatedProfiles; - } - - public void setActivatedProfiles(Collection activatedProfiles) - { - myActivatedProfiles = new HashSet<>(activatedProfiles); - } - - @Nonnull - @Override - public MavenProfileKind getDefaultState(@Nonnull String element) - { - return myActivatedProfiles.contains(element) ? MavenProfileKind.IMPLICIT : MavenProfileKind.NONE; - } - - @Nonnull - @Override - public MavenProfileKind getNextState(@Nonnull String element, @Nonnull MavenProfileKind state) - { - MavenProfileKind nextState; - switch(state) - { - case NONE: - nextState = MavenProfileKind.EXPLICIT; - break; - case EXPLICIT: - nextState = getDefaultState(element); - break; - case IMPLICIT: - default: - nextState = MavenProfileKind.NONE; - break; - } - return nextState; - } - - @Nullable - @Override - public MavenProfileKind getNextState(@Nonnull Map elementsWithStates) - { - MavenProfileKind nextState = null; - for(Map.Entry entry : elementsWithStates.entrySet()) - { - MavenProfileKind nextElementState = getNextState(entry.getKey(), entry.getValue()); - if(nextState == null) - { - nextState = nextElementState; - } - else if(!nextState.equals(nextElementState)) - { - nextState = null; - break; - } - } - return nextState; - } - - @Override - public boolean isMarked(@Nonnull MavenProfileKind state) - { - return state != MavenProfileKind.NONE; - } - - @Nullable - @Override - public MavenProfileKind getMarkState(@Nullable Object value) - { - return value instanceof MavenProfileKind ? (MavenProfileKind) value : null; - } - - @Nullable - @Override - public TableCellRenderer getMarkRenderer() - { - return new CheckboxTableCellRenderer(); - } - } - - private static class CheckboxTableCellRenderer extends JCheckBox implements TableCellRenderer - { - public CheckboxTableCellRenderer() - { - setHorizontalAlignment(SwingConstants.CENTER); - setBorder(null); - } - - @Override - public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) - { - if(isSelected) - { - setForeground(table.getSelectionForeground()); - super.setBackground(table.getSelectionBackground()); - } - else - { - setForeground(table.getForeground()); - setBackground(table.getBackground()); - } - - MavenProfileKind state = (MavenProfileKind) value; - setSelected(state != MavenProfileKind.NONE); - setEnabled(state != MavenProfileKind.IMPLICIT); - - return this; - } - } +public class SelectProfilesStep implements WizardStep { + private JPanel panel; + private MultiStateElementsChooser profileChooser; + private MavenProfileKindMarkStateDescriptor myMarkStateDescriptor; + + private final MavenImportModuleContext myContext; + + public SelectProfilesStep(MavenImportModuleContext context) { + myContext = context; + } + + @Override + public boolean isVisible(MavenImportModuleContext context) { + return !myContext.getProfiles().isEmpty(); + } + + public void createUIComponents() { + myMarkStateDescriptor = new MavenProfileKindMarkStateDescriptor(); + profileChooser = new MultiStateElementsChooser<>(true, myMarkStateDescriptor); + } + + @RequiredUIAccess + @Nonnull + @Override + public consulo.ui.Component getComponent(@Nonnull MavenImportModuleContext context, @Nonnull Disposable uiDisposable) { + throw new UnsupportedOperationException("desktop only"); + } + + @Override + public JComponent getSwingComponent(@Nonnull MavenImportModuleContext context, @Nonnull Disposable uiDisposable) { + return panel; + } + + @Override + public void onStepEnter(@Nonnull MavenImportModuleContext mavenImportModuleContext) { + List allProfiles = myContext.getProfiles(); + List activatedProfiles = myContext.getActivatedProfiles(); + MavenExplicitProfiles selectedProfiles = myContext.getSelectedProfiles(); + List enabledProfiles = new ArrayList<>(selectedProfiles.getEnabledProfiles()); + List disabledProfiles = new ArrayList<>(selectedProfiles.getDisabledProfiles()); + enabledProfiles.retainAll(allProfiles); // mark only existing profiles + disabledProfiles.retainAll(allProfiles); // mark only existing profiles + + myMarkStateDescriptor.setActivatedProfiles(activatedProfiles); + profileChooser.setElements(allProfiles, null); + profileChooser.markElements(enabledProfiles, MavenProfileKind.EXPLICIT); + profileChooser.markElements(disabledProfiles, MavenProfileKind.NONE); + } + + @Override + public void onStepLeave(@Nonnull MavenImportModuleContext context) { + Collection activatedProfiles = myMarkStateDescriptor.getActivatedProfiles(); + MavenExplicitProfiles newSelectedProfiles = MavenExplicitProfiles.NONE.clone(); + for (Map.Entry entry : profileChooser.getElementMarkStates().entrySet()) { + String profile = entry.getKey(); + MavenProfileKind profileKind = entry.getValue(); + switch (profileKind) { + case NONE: + if (activatedProfiles.contains(profile)) { + newSelectedProfiles.getDisabledProfiles().add(profile); + } + break; + case EXPLICIT: + newSelectedProfiles.getEnabledProfiles().add(profile); + break; + case IMPLICIT: + break; + } + } + myContext.setSelectedProfiles(newSelectedProfiles); + } + + private static class MavenProfileKindMarkStateDescriptor implements MultiStateElementsChooser.MarkStateDescriptor { + private Collection myActivatedProfiles = Collections.emptySet(); + + public Collection getActivatedProfiles() { + return myActivatedProfiles; + } + + public void setActivatedProfiles(Collection activatedProfiles) { + myActivatedProfiles = new HashSet<>(activatedProfiles); + } + + @Nonnull + @Override + public MavenProfileKind getDefaultState(@Nonnull String element) { + return myActivatedProfiles.contains(element) ? MavenProfileKind.IMPLICIT : MavenProfileKind.NONE; + } + + @Nonnull + @Override + public MavenProfileKind getNextState(@Nonnull String element, @Nonnull MavenProfileKind state) { + MavenProfileKind nextState; + switch (state) { + case NONE: + nextState = MavenProfileKind.EXPLICIT; + break; + case EXPLICIT: + nextState = getDefaultState(element); + break; + case IMPLICIT: + default: + nextState = MavenProfileKind.NONE; + break; + } + return nextState; + } + + @Nullable + @Override + public MavenProfileKind getNextState(@Nonnull Map elementsWithStates) { + MavenProfileKind nextState = null; + for (Map.Entry entry : elementsWithStates.entrySet()) { + MavenProfileKind nextElementState = getNextState(entry.getKey(), entry.getValue()); + if (nextState == null) { + nextState = nextElementState; + } + else if (!nextState.equals(nextElementState)) { + nextState = null; + break; + } + } + return nextState; + } + + @Override + public boolean isMarked(@Nonnull MavenProfileKind state) { + return state != MavenProfileKind.NONE; + } + + @Nullable + @Override + public MavenProfileKind getMarkState(@Nullable Object value) { + return value instanceof MavenProfileKind ? (MavenProfileKind)value : null; + } + + @Nullable + @Override + public TableCellRenderer getMarkRenderer() { + return new CheckboxTableCellRenderer(); + } + } + + private static class CheckboxTableCellRenderer extends JCheckBox implements TableCellRenderer { + public CheckboxTableCellRenderer() { + setHorizontalAlignment(SwingConstants.CENTER); + setBorder(null); + } + + @Override + public Component getTableCellRendererComponent( + JTable table, + Object value, + boolean isSelected, + boolean hasFocus, + int row, + int column + ) { + if (isSelected) { + setForeground(table.getSelectionForeground()); + super.setBackground(table.getSelectionBackground()); + } + else { + setForeground(table.getForeground()); + setBackground(table.getBackground()); + } + + MavenProfileKind state = (MavenProfileKind)value; + setSelected(state != MavenProfileKind.NONE); + setEnabled(state != MavenProfileKind.IMPLICIT); + + return this; + } + } } diff --git a/plugin/src/main/java/org/jetbrains/idea/maven/wizards/SelectPropertiesStep.java b/plugin/src/main/java/org/jetbrains/idea/maven/wizards/SelectPropertiesStep.java index dcaf2072..e1991c4d 100644 --- a/plugin/src/main/java/org/jetbrains/idea/maven/wizards/SelectPropertiesStep.java +++ b/plugin/src/main/java/org/jetbrains/idea/maven/wizards/SelectPropertiesStep.java @@ -42,117 +42,101 @@ /** * @author Sergey Evdokimov */ -public class SelectPropertiesStep implements WizardStep -{ - private final Project myProjectOrNull; - - private JPanel myMainPanel; - private JPanel myEnvironmentPanel; - private JPanel myPropertiesPanel; - - private MavenEnvironmentForm myEnvironmentForm; - @Nullable - private MavenPropertiesPanel myMavenPropertiesPanel; - - private Map mySelectedProps = Map.of(); - - public SelectPropertiesStep() - { - myProjectOrNull = null; - } - - private void initComponents(@Nonnull Disposable uiDisposable) - { - myEnvironmentForm = new MavenEnvironmentForm(); - - Project project = myProjectOrNull == null ? ProjectManager.getInstance().getDefaultProject() : myProjectOrNull; - myEnvironmentForm.getData(MavenProjectsManager.getInstance(project).getGeneralSettings().clone()); - - myEnvironmentPanel.add(myEnvironmentForm.createComponent(uiDisposable), BorderLayout.CENTER); - - myMavenPropertiesPanel = new MavenPropertiesPanel(new HashMap<>()); - myPropertiesPanel.add(myMavenPropertiesPanel); - myMavenPropertiesPanel.setDataFromMap(mySelectedProps); - } - - @Override - public void onStepEnter(@Nonnull MavenNewModuleContext context) - { - MavenArchetype archetype = context.getArchetype(); - - Map props = new LinkedHashMap(); - - MavenId projectId = context.getProjectId(); - - props.put("groupId", projectId.getGroupId()); - props.put("artifactId", projectId.getArtifactId()); - props.put("version", projectId.getVersion()); - - props.put("archetypeGroupId", archetype.groupId); - props.put("archetypeArtifactId", archetype.artifactId); - props.put("archetypeVersion", archetype.version); - if(archetype.repository != null) - { - props.put("archetypeRepository", archetype.repository); - } - - if(myMavenPropertiesPanel != null) - { - myMavenPropertiesPanel.setDataFromMap(props); - } - else - { - mySelectedProps = props; - } - } - - @Override - public void onStepLeave(@Nonnull MavenNewModuleContext context) - { - context.setEnvironmentForm(myEnvironmentForm); - if(myMavenPropertiesPanel != null) - { - context.setPropertiesToCreateByArtifact(myMavenPropertiesPanel.getDataAsMap()); - } - else - { - context.setPropertiesToCreateByArtifact(mySelectedProps); - } - } - - @RequiredUIAccess - @Nonnull - @Override - public Component getComponent(@Nonnull MavenNewModuleContext context, @Nonnull Disposable uiDisposable) - { - throw new UnsupportedOperationException("desktop only"); - } - - @Override - public JComponent getSwingComponent(@Nonnull MavenNewModuleContext context, @Nonnull Disposable uiDisposable) - { - initComponents(uiDisposable); - return myMainPanel; - } - - @Override - public boolean isVisible(@Nonnull MavenNewModuleContext context) - { - return context.getArchetype() != null; - } - - @Override - public void validateStep(@Nonnull MavenNewModuleContext context) throws WizardStepValidationException - { - File mavenHome = MavenUtil.resolveMavenHomeDirectory(myEnvironmentForm.getMavenHome()); - if(mavenHome == null) - { - throw new WizardStepValidationException("Maven home directory is not specified"); - } - - if(!MavenUtil.isValidMavenHome(mavenHome)) - { - throw new WizardStepValidationException("Maven home directory is invalid: " + mavenHome); - } - } +public class SelectPropertiesStep implements WizardStep { + private final Project myProjectOrNull; + + private JPanel myMainPanel; + private JPanel myEnvironmentPanel; + private JPanel myPropertiesPanel; + + private MavenEnvironmentForm myEnvironmentForm; + @Nullable + private MavenPropertiesPanel myMavenPropertiesPanel; + + private Map mySelectedProps = Map.of(); + + public SelectPropertiesStep() { + myProjectOrNull = null; + } + + private void initComponents(@Nonnull Disposable uiDisposable) { + myEnvironmentForm = new MavenEnvironmentForm(); + + Project project = myProjectOrNull == null ? ProjectManager.getInstance().getDefaultProject() : myProjectOrNull; + myEnvironmentForm.getData(MavenProjectsManager.getInstance(project).getGeneralSettings().clone()); + + myEnvironmentPanel.add(myEnvironmentForm.createComponent(uiDisposable), BorderLayout.CENTER); + + myMavenPropertiesPanel = new MavenPropertiesPanel(new HashMap<>()); + myPropertiesPanel.add(myMavenPropertiesPanel); + myMavenPropertiesPanel.setDataFromMap(mySelectedProps); + } + + @Override + public void onStepEnter(@Nonnull MavenNewModuleContext context) { + MavenArchetype archetype = context.getArchetype(); + + Map props = new LinkedHashMap(); + + MavenId projectId = context.getProjectId(); + + props.put("groupId", projectId.getGroupId()); + props.put("artifactId", projectId.getArtifactId()); + props.put("version", projectId.getVersion()); + + props.put("archetypeGroupId", archetype.groupId); + props.put("archetypeArtifactId", archetype.artifactId); + props.put("archetypeVersion", archetype.version); + if (archetype.repository != null) { + props.put("archetypeRepository", archetype.repository); + } + + if (myMavenPropertiesPanel != null) { + myMavenPropertiesPanel.setDataFromMap(props); + } + else { + mySelectedProps = props; + } + } + + @Override + public void onStepLeave(@Nonnull MavenNewModuleContext context) { + context.setEnvironmentForm(myEnvironmentForm); + if (myMavenPropertiesPanel != null) { + context.setPropertiesToCreateByArtifact(myMavenPropertiesPanel.getDataAsMap()); + } + else { + context.setPropertiesToCreateByArtifact(mySelectedProps); + } + } + + @RequiredUIAccess + @Nonnull + @Override + public Component getComponent(@Nonnull MavenNewModuleContext context, @Nonnull Disposable uiDisposable) { + throw new UnsupportedOperationException("desktop only"); + } + + @Override + public JComponent getSwingComponent(@Nonnull MavenNewModuleContext context, @Nonnull Disposable uiDisposable) { + initComponents(uiDisposable); + return myMainPanel; + } + + @Override + public boolean isVisible(@Nonnull MavenNewModuleContext context) { + return context.getArchetype() != null; + } + + @Override + public void validateStep(@Nonnull MavenNewModuleContext context) throws WizardStepValidationException { + File mavenHome = MavenUtil.resolveMavenHomeDirectory(myEnvironmentForm.getMavenHome()); + if (mavenHome == null) { + throw new WizardStepValidationException("Maven home directory is not specified"); + } + + if (!MavenUtil.isValidMavenHome(mavenHome)) { + throw new WizardStepValidationException("Maven home directory is invalid: " + mavenHome); + } + } }