diff --git a/plugin/src/main/java/org/jetbrains/idea/maven/dom/DependencyConflictId.java b/plugin/src/main/java/org/jetbrains/idea/maven/dom/DependencyConflictId.java index ec78ecde..3f34d263 100644 --- a/plugin/src/main/java/org/jetbrains/idea/maven/dom/DependencyConflictId.java +++ b/plugin/src/main/java/org/jetbrains/idea/maven/dom/DependencyConflictId.java @@ -12,126 +12,98 @@ * * @author Sergey Evdokimov */ -public class DependencyConflictId -{ - private final String groupId; - private final String artifactId; - private final String type; - private final String classifier; - - public DependencyConflictId(@Nonnull String groupId, @Nonnull String artifactId, @Nullable String type, @Nullable String classifier) - { - this.groupId = groupId; - this.artifactId = artifactId; - this.type = StringUtil.isEmpty(type) ? "jar" : type; - this.classifier = classifier; - } - - @Nullable - public static DependencyConflictId create(@Nonnull MavenDomDependency dep) - { - String groupId = dep.getGroupId().getStringValue(); - if(StringUtil.isEmpty(groupId)) - { - return null; - } - - String artifactId = dep.getArtifactId().getStringValue(); - if(StringUtil.isEmpty(artifactId)) - { - return null; - } - - //noinspection ConstantConditions - return new DependencyConflictId(groupId, artifactId, dep.getType().getStringValue(), dep.getClassifier().getStringValue()); - } - - @Nullable - public static DependencyConflictId create(@Nonnull MavenArtifact dep) - { - return create(dep.getGroupId(), dep.getArtifactId(), dep.getType(), dep.getClassifier()); - } - - @Nullable - public static DependencyConflictId create(String groupId, String artifactId, String type, String classifier) - { - if(StringUtil.isEmpty(groupId)) - { - return null; - } - if(StringUtil.isEmpty(artifactId)) - { - return null; - } - - return new DependencyConflictId(groupId, artifactId, type, classifier); - } - - @Nonnull - public String getGroupId() - { - return groupId; - } - - @Nonnull - public String getArtifactId() - { - return artifactId; - } - - @Nonnull - public String getType() - { - return type; - } - - @Nullable - public String getClassifier() - { - return classifier; - } - - @Override - public boolean equals(Object o) - { - if(this == o) - { - return true; - } - if(!(o instanceof DependencyConflictId)) - { - return false; - } - - DependencyConflictId id = (DependencyConflictId) o; - - if(!artifactId.equals(id.artifactId)) - { - return false; - } - if(classifier != null ? !classifier.equals(id.classifier) : id.classifier != null) - { - return false; - } - if(!groupId.equals(id.groupId)) - { - return false; - } - if(!type.equals(id.type)) - { - return false; - } - - return true; - } - - @Override - public int hashCode() - { - int result = groupId.hashCode(); - result = 31 * result + artifactId.hashCode(); - result = 31 * result + type.hashCode(); - result = 31 * result + (classifier != null ? classifier.hashCode() : 0); - return result; - } +public class DependencyConflictId { + private final String groupId; + private final String artifactId; + private final String type; + private final String classifier; + + public DependencyConflictId(@Nonnull String groupId, @Nonnull String artifactId, @Nullable String type, @Nullable String classifier) { + this.groupId = groupId; + this.artifactId = artifactId; + this.type = StringUtil.isEmpty(type) ? "jar" : type; + this.classifier = classifier; + } + + @Nullable + public static DependencyConflictId create(@Nonnull MavenDomDependency dep) { + String groupId = dep.getGroupId().getStringValue(); + if (StringUtil.isEmpty(groupId)) { + return null; + } + + String artifactId = dep.getArtifactId().getStringValue(); + if (StringUtil.isEmpty(artifactId)) { + return null; + } + + //noinspection ConstantConditions + return new DependencyConflictId(groupId, artifactId, dep.getType().getStringValue(), dep.getClassifier().getStringValue()); + } + + @Nullable + public static DependencyConflictId create(@Nonnull MavenArtifact dep) { + return create(dep.getGroupId(), dep.getArtifactId(), dep.getType(), dep.getClassifier()); + } + + @Nullable + public static DependencyConflictId create(String groupId, String artifactId, String type, String classifier) { + if (StringUtil.isEmpty(groupId)) { + return null; + } + if (StringUtil.isEmpty(artifactId)) { + return null; + } + + return new DependencyConflictId(groupId, artifactId, type, classifier); + } + + @Nonnull + public String getGroupId() { + return groupId; + } + + @Nonnull + public String getArtifactId() { + return artifactId; + } + + @Nonnull + public String getType() { + return type; + } + + @Nullable + public String getClassifier() { + return classifier; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (!(o instanceof DependencyConflictId)) { + return false; + } + + DependencyConflictId id = (DependencyConflictId)o; + + if (!artifactId.equals(id.artifactId)) { + return false; + } + if (classifier != null ? !classifier.equals(id.classifier) : id.classifier != null) { + return false; + } + return groupId.equals(id.groupId) && type.equals(id.type); + } + + @Override + public int hashCode() { + int result = groupId.hashCode(); + result = 31 * result + artifactId.hashCode(); + result = 31 * result + type.hashCode(); + result = 31 * result + (classifier != null ? classifier.hashCode() : 0); + return result; + } } diff --git a/plugin/src/main/java/org/jetbrains/idea/maven/dom/MavenDomBundle.java b/plugin/src/main/java/org/jetbrains/idea/maven/dom/MavenDomBundle.java index 78395c46..738b8cdf 100644 --- a/plugin/src/main/java/org/jetbrains/idea/maven/dom/MavenDomBundle.java +++ b/plugin/src/main/java/org/jetbrains/idea/maven/dom/MavenDomBundle.java @@ -15,34 +15,42 @@ */ package org.jetbrains.idea.maven.dom; +import consulo.annotation.DeprecationInfo; +import consulo.annotation.internal.MigratedExtensionsTo; import consulo.application.CommonBundle; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.PropertyKey; +import org.jetbrains.idea.maven.localize.MavenDomLocalize; import java.lang.ref.Reference; import java.lang.ref.SoftReference; import java.util.ResourceBundle; +@Deprecated +@DeprecationInfo("Use MavenDomLocalize") +@MigratedExtensionsTo(MavenDomLocalize.class) public class MavenDomBundle { - private static Reference ourBundle; + private static Reference ourBundle; - @NonNls - private static final String BUNDLE = "MavenDomBundle"; + @NonNls + private static final String BUNDLE = "MavenDomBundle"; - private MavenDomBundle() { - } + private MavenDomBundle() { + } - public static String message(@PropertyKey(resourceBundle = BUNDLE) String key, Object... params) { - return CommonBundle.message(getBundle(), key, params); - } + public static String message(@PropertyKey(resourceBundle = BUNDLE) String key, Object... params) { + return CommonBundle.message(getBundle(), key, params); + } - private static ResourceBundle getBundle() { - ResourceBundle bundle = null; - if (ourBundle != null) bundle = ourBundle.get(); - if (bundle == null) { - bundle = ResourceBundle.getBundle(BUNDLE); - ourBundle = new SoftReference(bundle); + private static ResourceBundle getBundle() { + ResourceBundle bundle = null; + if (ourBundle != null) { + bundle = ourBundle.get(); + } + if (bundle == null) { + bundle = ResourceBundle.getBundle(BUNDLE); + ourBundle = new SoftReference<>(bundle); + } + return bundle; } - return bundle; - } } diff --git a/plugin/src/main/java/org/jetbrains/idea/maven/dom/MavenDomElement.java b/plugin/src/main/java/org/jetbrains/idea/maven/dom/MavenDomElement.java index 7c83bccc..b2897fd8 100644 --- a/plugin/src/main/java/org/jetbrains/idea/maven/dom/MavenDomElement.java +++ b/plugin/src/main/java/org/jetbrains/idea/maven/dom/MavenDomElement.java @@ -20,6 +20,5 @@ import consulo.xml.util.xml.NameStrategy; @NameStrategy(JavaNameStrategy.class) -public interface MavenDomElement extends DomElement -{ +public interface MavenDomElement extends DomElement { } diff --git a/plugin/src/main/java/org/jetbrains/idea/maven/dom/MavenDomElementDescriptorHolder.java b/plugin/src/main/java/org/jetbrains/idea/maven/dom/MavenDomElementDescriptorHolder.java index 9ae0b0d9..8c875ab3 100644 --- a/plugin/src/main/java/org/jetbrains/idea/maven/dom/MavenDomElementDescriptorHolder.java +++ b/plugin/src/main/java/org/jetbrains/idea/maven/dom/MavenDomElementDescriptorHolder.java @@ -18,6 +18,7 @@ import com.intellij.xml.XmlElementDescriptor; import com.intellij.xml.impl.schema.XmlNSDescriptorImpl; +import consulo.annotation.access.RequiredReadAction; import consulo.annotation.component.ComponentScope; import consulo.annotation.component.ServiceAPI; import consulo.annotation.component.ServiceImpl; @@ -48,144 +49,121 @@ @Singleton @ServiceAPI(ComponentScope.PROJECT) @ServiceImpl -public class MavenDomElementDescriptorHolder -{ - private static final Logger LOG = Logger.getInstance(MavenDomElementDescriptorHolder.class); - - private enum FileKind - { - PROJECT_FILE - { - public String getSchemaUrl() - { - return MavenSchemaProvider.MAVEN_PROJECT_SCHEMA_URL; - } - }, - PROFILES_FILE - { - public String getSchemaUrl() - { - return MavenSchemaProvider.MAVEN_PROFILES_SCHEMA_URL; - } - }, - SETTINGS_FILE - { - public String getSchemaUrl() - { - return MavenSchemaProvider.MAVEN_SETTINGS_SCHEMA_URL; - } - }; - - public abstract String getSchemaUrl(); - } - - private final Project myProject; - private final Map> myDescriptorsMap = new HashMap>(); - - @Inject - public MavenDomElementDescriptorHolder(Project project) - { - myProject = project; - } - - public static MavenDomElementDescriptorHolder getInstance(@Nonnull Project project) - { - return ServiceManager.getService(project, MavenDomElementDescriptorHolder.class); - } - - @Nullable - public XmlElementDescriptor getDescriptor(@Nonnull XmlTag tag) - { - FileKind kind = getFileKind(tag.getContainingFile()); - if(kind == null) - { - return null; - } - - XmlNSDescriptorImpl desc; - synchronized(this) - { - desc = tryGetOrCreateDescriptor(kind); - if(desc == null) - { - return null; - } - } - LOG.assertTrue(tag.isValid()); - LOG.assertTrue(desc.isValid()); - return desc.getElementDescriptor(tag.getName(), desc.getDefaultNamespace()); - } - - @Nullable - private XmlNSDescriptorImpl tryGetOrCreateDescriptor(final FileKind kind) - { - CachedValue result = myDescriptorsMap.get(kind); - if(result == null) - { - result = CachedValuesManager.getManager(myProject).createCachedValue(new CachedValueProvider() - { - @Override - public Result compute() - { - return Result.create(doCreateDescriptor(kind), PsiModificationTracker.OUT_OF_CODE_BLOCK_MODIFICATION_COUNT); - } - }, false); - myDescriptorsMap.put(kind, result); - } - return result.getValue(); - } - - @Nullable - private XmlNSDescriptorImpl doCreateDescriptor(FileKind kind) - { - String schemaUrl = kind.getSchemaUrl(); - String location = ExternalResourceManager.getInstance().getResourceLocation(schemaUrl); - if(schemaUrl.equals(location)) - { - return null; - } - - VirtualFile schema; - try - { - schema = VirtualFileUtil.findFileByURL(new URL(location)); - } - catch(MalformedURLException ignore) - { - return null; - } - - if(schema == null) - { - return null; - } - - PsiFile psiFile = PsiManager.getInstance(myProject).findFile(schema); - if(!(psiFile instanceof XmlFile)) - { - return null; - } - - XmlNSDescriptorImpl result = new XmlNSDescriptorImpl(); - result.init(psiFile); - return result; - } - - @Nullable - private FileKind getFileKind(PsiFile file) - { - if(MavenDomUtil.isProjectFile(file)) - { - return FileKind.PROJECT_FILE; - } - if(MavenDomUtil.isProfilesFile(file)) - { - return FileKind.PROFILES_FILE; - } - if(MavenDomUtil.isSettingsFile(file)) - { - return FileKind.SETTINGS_FILE; - } - return null; - } +public class MavenDomElementDescriptorHolder { + private static final Logger LOG = Logger.getInstance(MavenDomElementDescriptorHolder.class); + + private enum FileKind { + PROJECT_FILE { + @Override + public String getSchemaUrl() { + return MavenSchemaProvider.MAVEN_PROJECT_SCHEMA_URL; + } + }, + PROFILES_FILE { + @Override + public String getSchemaUrl() { + return MavenSchemaProvider.MAVEN_PROFILES_SCHEMA_URL; + } + }, + SETTINGS_FILE { + @Override + public String getSchemaUrl() { + return MavenSchemaProvider.MAVEN_SETTINGS_SCHEMA_URL; + } + }; + + public abstract String getSchemaUrl(); + } + + private final Project myProject; + private final Map> myDescriptorsMap = new HashMap<>(); + + @Inject + public MavenDomElementDescriptorHolder(Project project) { + myProject = project; + } + + public static MavenDomElementDescriptorHolder getInstance(@Nonnull Project project) { + return ServiceManager.getService(project, MavenDomElementDescriptorHolder.class); + } + + @Nullable + public XmlElementDescriptor getDescriptor(@Nonnull XmlTag tag) { + FileKind kind = getFileKind(tag.getContainingFile()); + if (kind == null) { + return null; + } + + XmlNSDescriptorImpl desc; + synchronized (this) { + desc = tryGetOrCreateDescriptor(kind); + if (desc == null) { + return null; + } + } + LOG.assertTrue(tag.isValid()); + LOG.assertTrue(desc.isValid()); + return desc.getElementDescriptor(tag.getName(), desc.getDefaultNamespace()); + } + + @Nullable + private XmlNSDescriptorImpl tryGetOrCreateDescriptor(final FileKind kind) { + CachedValue result = myDescriptorsMap.get(kind); + if (result == null) { + result = CachedValuesManager.getManager(myProject).createCachedValue( + () -> CachedValueProvider.Result.create( + doCreateDescriptor(kind), + PsiModificationTracker.OUT_OF_CODE_BLOCK_MODIFICATION_COUNT + ), + false + ); + myDescriptorsMap.put(kind, result); + } + return result.getValue(); + } + + @Nullable + @RequiredReadAction + private XmlNSDescriptorImpl doCreateDescriptor(FileKind kind) { + String schemaUrl = kind.getSchemaUrl(); + String location = ExternalResourceManager.getInstance().getResourceLocation(schemaUrl); + if (schemaUrl.equals(location)) { + return null; + } + + VirtualFile schema; + try { + schema = VirtualFileUtil.findFileByURL(new URL(location)); + } + catch (MalformedURLException ignore) { + return null; + } + + if (schema == null) { + return null; + } + + PsiFile psiFile = PsiManager.getInstance(myProject).findFile(schema); + if (!(psiFile instanceof XmlFile)) { + return null; + } + + XmlNSDescriptorImpl result = new XmlNSDescriptorImpl(); + result.init(psiFile); + return result; + } + + @Nullable + private FileKind getFileKind(PsiFile file) { + if (MavenDomUtil.isProjectFile(file)) { + return FileKind.PROJECT_FILE; + } + if (MavenDomUtil.isProfilesFile(file)) { + return FileKind.PROFILES_FILE; + } + if (MavenDomUtil.isSettingsFile(file)) { + return FileKind.SETTINGS_FILE; + } + return null; + } } diff --git a/plugin/src/main/java/org/jetbrains/idea/maven/dom/MavenDomElementDescriptorProvider.java b/plugin/src/main/java/org/jetbrains/idea/maven/dom/MavenDomElementDescriptorProvider.java index cab9505e..53936841 100644 --- a/plugin/src/main/java/org/jetbrains/idea/maven/dom/MavenDomElementDescriptorProvider.java +++ b/plugin/src/main/java/org/jetbrains/idea/maven/dom/MavenDomElementDescriptorProvider.java @@ -21,10 +21,9 @@ import consulo.xml.psi.xml.XmlTag; @ExtensionImpl -public class MavenDomElementDescriptorProvider implements XmlElementDescriptorProvider -{ - public XmlElementDescriptor getDescriptor(XmlTag tag) - { - return MavenDomElementDescriptorHolder.getInstance(tag.getProject()).getDescriptor(tag); - } +public class MavenDomElementDescriptorProvider implements XmlElementDescriptorProvider { + @Override + public XmlElementDescriptor getDescriptor(XmlTag tag) { + return MavenDomElementDescriptorHolder.getInstance(tag.getProject()).getDescriptor(tag); + } } diff --git a/plugin/src/main/java/org/jetbrains/idea/maven/dom/MavenDomFileDescription.java b/plugin/src/main/java/org/jetbrains/idea/maven/dom/MavenDomFileDescription.java index 5421be74..c23ee0f9 100644 --- a/plugin/src/main/java/org/jetbrains/idea/maven/dom/MavenDomFileDescription.java +++ b/plugin/src/main/java/org/jetbrains/idea/maven/dom/MavenDomFileDescription.java @@ -23,17 +23,17 @@ import javax.annotation.Nonnull; public abstract class MavenDomFileDescription extends DomFileDescription { - public MavenDomFileDescription(Class rootElementClass, String rootTagName) { - super(rootElementClass, rootTagName); - } + public MavenDomFileDescription(Class rootElementClass, String rootTagName) { + super(rootElementClass, rootTagName); + } - @Override - public boolean isMyFile(@Nonnull XmlFile file) { - return MavenDomUtil.isMavenFile(file) && super.isMyFile(file); - } + @Override + public boolean isMyFile(@Nonnull XmlFile file) { + return MavenDomUtil.isMavenFile(file) && super.isMyFile(file); + } - @Override - public DomElementsAnnotator createAnnotator() { - return new MavenDomAnnotator(); - } + @Override + public DomElementsAnnotator createAnnotator() { + return new MavenDomAnnotator(); + } } diff --git a/plugin/src/main/java/org/jetbrains/idea/maven/dom/MavenDomOldProfilesModelDescription.java b/plugin/src/main/java/org/jetbrains/idea/maven/dom/MavenDomOldProfilesModelDescription.java index 7111ffee..452e3a0f 100644 --- a/plugin/src/main/java/org/jetbrains/idea/maven/dom/MavenDomOldProfilesModelDescription.java +++ b/plugin/src/main/java/org/jetbrains/idea/maven/dom/MavenDomOldProfilesModelDescription.java @@ -20,7 +20,7 @@ @ExtensionImpl public class MavenDomOldProfilesModelDescription extends MavenDomFileDescription { - public MavenDomOldProfilesModelDescription() { - super(MavenDomOldProfilesModel.class, "profiles"); - } + public MavenDomOldProfilesModelDescription() { + super(MavenDomOldProfilesModel.class, "profiles"); + } } diff --git a/plugin/src/main/java/org/jetbrains/idea/maven/dom/MavenDomPluginModelDescription.java b/plugin/src/main/java/org/jetbrains/idea/maven/dom/MavenDomPluginModelDescription.java index d702c90d..bf4b0948 100644 --- a/plugin/src/main/java/org/jetbrains/idea/maven/dom/MavenDomPluginModelDescription.java +++ b/plugin/src/main/java/org/jetbrains/idea/maven/dom/MavenDomPluginModelDescription.java @@ -21,7 +21,7 @@ @ExtensionImpl public class MavenDomPluginModelDescription extends DomFileDescription { - public MavenDomPluginModelDescription() { - super(MavenDomPluginModel.class, "plugin"); - } + public MavenDomPluginModelDescription() { + super(MavenDomPluginModel.class, "plugin"); + } } diff --git a/plugin/src/main/java/org/jetbrains/idea/maven/dom/MavenDomProfilesModelDescription.java b/plugin/src/main/java/org/jetbrains/idea/maven/dom/MavenDomProfilesModelDescription.java index 426e53d7..42c24130 100644 --- a/plugin/src/main/java/org/jetbrains/idea/maven/dom/MavenDomProfilesModelDescription.java +++ b/plugin/src/main/java/org/jetbrains/idea/maven/dom/MavenDomProfilesModelDescription.java @@ -20,7 +20,7 @@ @ExtensionImpl public class MavenDomProfilesModelDescription extends MavenDomFileDescription { - public MavenDomProfilesModelDescription() { - super(MavenDomProfilesModel.class, "profilesXml"); - } + public MavenDomProfilesModelDescription() { + super(MavenDomProfilesModel.class, "profilesXml"); + } } \ No newline at end of file diff --git a/plugin/src/main/java/org/jetbrains/idea/maven/dom/MavenDomProjectModelDescription.java b/plugin/src/main/java/org/jetbrains/idea/maven/dom/MavenDomProjectModelDescription.java index cc4f346f..44c78092 100644 --- a/plugin/src/main/java/org/jetbrains/idea/maven/dom/MavenDomProjectModelDescription.java +++ b/plugin/src/main/java/org/jetbrains/idea/maven/dom/MavenDomProjectModelDescription.java @@ -20,7 +20,7 @@ @ExtensionImpl public class MavenDomProjectModelDescription extends MavenDomFileDescription { - public MavenDomProjectModelDescription() { - super(MavenDomProjectModel.class, "project"); - } + public MavenDomProjectModelDescription() { + super(MavenDomProjectModel.class, "project"); + } } diff --git a/plugin/src/main/java/org/jetbrains/idea/maven/dom/MavenDomProjectProcessorUtils.java b/plugin/src/main/java/org/jetbrains/idea/maven/dom/MavenDomProjectProcessorUtils.java index 77707ba1..de634e61 100644 --- a/plugin/src/main/java/org/jetbrains/idea/maven/dom/MavenDomProjectProcessorUtils.java +++ b/plugin/src/main/java/org/jetbrains/idea/maven/dom/MavenDomProjectProcessorUtils.java @@ -15,9 +15,9 @@ */ package org.jetbrains.idea.maven.dom; +import consulo.annotation.access.RequiredReadAction; import consulo.application.util.function.Processor; import consulo.language.psi.PsiElement; -import consulo.language.psi.PsiFile; import consulo.maven.rt.server.common.model.MavenId; import consulo.project.Project; import consulo.util.collection.ContainerUtil; @@ -42,647 +42,632 @@ import java.util.Set; import java.util.function.Function; -public class MavenDomProjectProcessorUtils -{ - private MavenDomProjectProcessorUtils() - { - } - - @Nonnull - public static Set getChildrenProjects(@Nonnull final MavenDomProjectModel model) - { - Set models = new HashSet(); - - collectChildrenProjects(model, models); - - return models; - } - - private static void collectChildrenProjects(@Nonnull final MavenDomProjectModel model, @Nonnull Set models) - { - MavenProject mavenProject = MavenDomUtil.findProject(model); - if(mavenProject != null) - { - final Project project = model.getManager().getProject(); - for(MavenProject inheritor : MavenProjectsManager.getInstance(project).findInheritors(mavenProject)) - { - MavenDomProjectModel inheritorProjectModel = MavenDomUtil.getMavenDomProjectModel(project, inheritor.getFile()); - if(inheritorProjectModel != null && !models.contains(inheritorProjectModel)) - { - models.add(inheritorProjectModel); - collectChildrenProjects(inheritorProjectModel, models); - } - } - } - } - - @Nonnull - public static Set collectParentProjects(@Nonnull final MavenDomProjectModel projectDom) - { - final Set parents = new HashSet(); - - Processor collectProcessor = model -> { - parents.add(model); - return false; - }; - processParentProjects(projectDom, collectProcessor); - - return parents; - } - - public static void processParentProjects(@Nonnull final MavenDomProjectModel projectDom, @Nonnull final Processor - processor) - { - Set processed = new HashSet(); - Project project = projectDom.getManager().getProject(); - MavenDomProjectModel parent = findParent(projectDom, project); - while(parent != null) - { - if(processed.contains(parent)) - { - break; - } - processed.add(parent); - if(processor.process(parent)) - { - break; - } - - parent = findParent(parent, project); - } - } - - @Nullable - public static MavenDomProjectModel findParent(@Nonnull MavenDomProjectModel model, Project project) - { - return findParent(model.getMavenParent(), project); - } - - @Nullable - public static MavenDomProjectModel findParent(@Nonnull MavenDomParent mavenDomParent, Project project) - { - if(!DomUtil.hasXml(mavenDomParent)) - { - return null; - } - - MavenId id = new MavenId(mavenDomParent.getGroupId().getStringValue(), mavenDomParent.getArtifactId().getStringValue(), - mavenDomParent.getVersion().getStringValue()); - MavenProject mavenProject = MavenProjectsManager.getInstance(project).findProject(id); - - return mavenProject != null ? MavenDomUtil.getMavenDomProjectModel(project, mavenProject.getFile()) : null; - } - - @Nullable - public static XmlTag searchProperty(@Nonnull final String propertyName, @Nonnull MavenDomProjectModel projectDom, @Nonnull final Project project) - { - SearchProcessor searchProcessor = new SearchProcessor() - { - @Override - protected XmlTag find(MavenDomProperties element) - { - return findProperty(element, propertyName); - } - }; - - processProperties(projectDom, searchProcessor, project); - return searchProcessor.myResult; - } - - @Nullable - public static XmlTag findProperty(@Nonnull MavenDomProperties mavenDomProperties, @Nonnull String propertyName) - { - XmlTag propertiesTag = mavenDomProperties.getXmlTag(); - if(propertiesTag == null) - { - return null; - } - - for(XmlTag each : propertiesTag.getSubTags()) - { - if(each.getName().equals(propertyName)) - { - return each; - } - } - - return null; - } - - public static Set collectProperties(@Nonnull MavenDomProjectModel projectDom, @Nonnull final Project project) - { - final Set properties = new HashSet(); - - Processor collectProcessor = mavenDomProperties -> { - XmlTag propertiesTag = mavenDomProperties.getXmlTag(); - if(propertiesTag != null) - { - ContainerUtil.addAll(properties, propertiesTag.getSubTags()); - } - return false; - }; - - processProperties(projectDom, collectProcessor, project); - - return properties; - } - - - @Nonnull - public static Set searchDependencyUsages(@Nonnull final MavenDomDependency dependency) - { - final MavenDomProjectModel model = dependency.getParentOfType(MavenDomProjectModel.class, false); - if(model != null) - { - DependencyConflictId dependencyId = DependencyConflictId.create(dependency); - if(dependencyId != null) - { - return searchDependencyUsages(model, dependencyId, Collections.singleton(dependency)); - } - } - return Collections.emptySet(); - } - - @Nonnull - public static Set searchDependencyUsages(@Nonnull final MavenDomProjectModel model, - @Nonnull final DependencyConflictId dependencyId, @Nonnull final Set excludes) - { - Project project = model.getManager().getProject(); - final Set usages = new HashSet(); - Processor collectProcessor = mavenDomProjectModel -> { - if(!model.equals(mavenDomProjectModel)) - { - for(MavenDomDependency domDependency : mavenDomProjectModel.getDependencies().getDependencies()) - { - if(excludes.contains(domDependency)) - { - continue; - } - - if(dependencyId.equals(DependencyConflictId.create(domDependency))) - { - usages.add(domDependency); - } - } - } - return false; - }; - - processChildrenRecursively(model, collectProcessor, project, new HashSet(), true); - - return usages; - } - - @Nonnull - public static Collection searchManagedPluginUsages(@Nonnull final MavenDomPlugin plugin) - { - String artifactId = plugin.getArtifactId().getStringValue(); - if(artifactId == null) - { - return Collections.emptyList(); - } - - String groupId = plugin.getGroupId().getStringValue(); - - MavenDomProjectModel model = plugin.getParentOfType(MavenDomProjectModel.class, false); - if(model == null) - { - return Collections.emptyList(); - } - - return searchManagedPluginUsages(model, groupId, artifactId); - } - - @Nonnull - public static Collection searchManagedPluginUsages(@Nonnull final MavenDomProjectModel model, @Nullable final String groupId, - @Nonnull final String artifactId) - { - Project project = model.getManager().getProject(); - - final Set usages = new HashSet(); - - Processor collectProcessor = mavenDomProjectModel -> { - for(MavenDomPlugin domPlugin : mavenDomProjectModel.getBuild().getPlugins().getPlugins()) - { - if(MavenPluginDomUtil.isPlugin(domPlugin, groupId, artifactId)) - { - usages.add(domPlugin); - } - } - return false; - }; - - processChildrenRecursively(model, collectProcessor, project, new HashSet(), true); - - return usages; - } - - public static void processChildrenRecursively(@Nullable MavenDomProjectModel model, @Nonnull Processor processor) - { - processChildrenRecursively(model, processor, true); - } - - public static void processChildrenRecursively(@Nullable MavenDomProjectModel model, @Nonnull Processor processor, - boolean processCurrentModel) - { - if(model != null) - { - processChildrenRecursively(model, processor, model.getManager().getProject(), new HashSet(), processCurrentModel); - } - } - - public static void processChildrenRecursively(@Nullable MavenDomProjectModel model, @Nonnull Processor processor, - @Nonnull Project project, @Nonnull Set processedModels, boolean strict) - { - if(model != null && !processedModels.contains(model)) - { - processedModels.add(model); - - if(strict && processor.process(model)) - { - return; - } - - MavenProject mavenProject = MavenDomUtil.findProject(model); - if(mavenProject != null) - { - for(MavenProject childProject : MavenProjectsManager.getInstance(project).findInheritors(mavenProject)) - { - MavenDomProjectModel childProjectModel = MavenDomUtil.getMavenDomProjectModel(project, childProject.getFile()); - - processChildrenRecursively(childProjectModel, processor, project, processedModels, true); - } - } - } - } - - @Nullable - public static MavenDomDependency searchManagingDependency(@Nonnull final MavenDomDependency dependency) - { - return searchManagingDependency(dependency, dependency.getManager().getProject()); - } - - @Nullable - public static MavenDomDependency searchManagingDependency(@Nonnull final MavenDomDependency dependency, @Nonnull final Project project) - { - final DependencyConflictId depId = DependencyConflictId.create(dependency); - if(depId == null) - { - return null; - } - - final MavenDomProjectModel model = dependency.getParentOfType(MavenDomProjectModel.class, false); - if(model == null) - { - return null; - } - - final Ref res = new Ref(); - - Processor processor = dependency1 -> { - if(depId.equals(DependencyConflictId.create(dependency1))) - { - res.set(dependency1); - return true; - } - - return false; - }; - - processDependenciesInDependencyManagement(model, processor, project); - - return res.get(); - } - - @Nullable - public static MavenDomPlugin searchManagingPlugin(@Nonnull final MavenDomPlugin plugin) - { - final String artifactId = plugin.getArtifactId().getStringValue(); - final String groupId = plugin.getGroupId().getStringValue(); - if(artifactId == null) - { - return null; - } - - final MavenDomProjectModel model = plugin.getParentOfType(MavenDomProjectModel.class, false); - if(model == null) - { - return null; - } - - SearchProcessor processor = new SearchProcessor() - { - @Override - protected MavenDomPlugin find(MavenDomPlugins mavenDomPlugins) - { - if(!model.equals(mavenDomPlugins.getParentOfType(MavenDomProjectModel.class, true))) - { - for(MavenDomPlugin domPlugin : mavenDomPlugins.getPlugins()) - { - if(MavenPluginDomUtil.isPlugin(domPlugin, groupId, artifactId)) - { - return domPlugin; - } - } - } - - return null; - } - }; - - Function domProfileFunction = mavenDomProfile -> mavenDomProfile.getBuild().getPluginManagement().getPlugins(); - - process(model, processor, model.getManager().getProject(), domProfileFunction, domProfileFunction); - - return processor.myResult; - } - - - public static boolean processDependenciesInDependencyManagement(@Nonnull MavenDomProjectModel projectDom, - @Nonnull final Processor processor, @Nonnull final Project project) - { - - Processor managedDependenciesListProcessor = dependencies -> { - SmartList importDependencies = null; - - for(MavenDomDependency domDependency : dependencies.getDependencies()) - { - if("import".equals(domDependency.getScope().getRawText())) - { - if(importDependencies == null) - { - importDependencies = new SmartList(); - } - - importDependencies.add(domDependency); - } - else - { - if(processor.process(domDependency)) - { - return true; - } - } - } - - if(importDependencies != null) - { - for(MavenDomDependency domDependency : importDependencies) - { - GenericDomValue version = domDependency.getVersion(); - if(version.getXmlElement() != null) - { - GenericDomValueReference reference = new GenericDomValueReference(version); - PsiElement resolve = reference.resolve(); - - if(resolve instanceof XmlFile) - { - MavenDomProjectModel dependModel = MavenDomUtil.getMavenDomModel((PsiFile) resolve, MavenDomProjectModel.class); - if(dependModel != null) - { - for(MavenDomDependency dep : dependModel.getDependencyManagement().getDependencies().getDependencies()) - { - if(processor.process(dep)) - { - return true; - } - } - } - } - } - } - } - - return false; - }; - - Function domFunction = mavenDomProfile -> mavenDomProfile.getDependencyManagement().getDependencies(); - - return process(projectDom, managedDependenciesListProcessor, project, domFunction, domFunction); - } - - public static boolean processDependencies(@Nonnull MavenDomProjectModel projectDom, @Nonnull final Processor processor) - { - - Function domFunction = mavenDomProfile -> mavenDomProfile.getDependencies(); - - return process(projectDom, processor, projectDom.getManager().getProject(), domFunction, domFunction); - } - - public static boolean processProperties(@Nonnull MavenDomProjectModel projectDom, @Nonnull final Processor processor, - @Nonnull final Project project) - { - - Function domFunction = mavenDomProfile -> mavenDomProfile.getProperties(); - - return process(projectDom, processor, project, domFunction, domFunction); - } - - public static boolean process(@Nonnull MavenDomProjectModel projectDom, @Nonnull final Processor processor, - @Nonnull final Project project, @Nonnull final Function domProfileFunction, - @Nonnull final Function projectDomFunction) - { - - return process(projectDom, processor, project, domProfileFunction, projectDomFunction, new HashSet()); - } - - - public static boolean process(@Nonnull MavenDomProjectModel projectDom, @Nonnull final Processor processor, - @Nonnull final Project project, @Nonnull final Function domProfileFunction, - @Nonnull final Function projectDomFunction, final Set processed) - { - if(processed.contains(projectDom)) - { - return true; - } - processed.add(projectDom); - - MavenProject mavenProjectOrNull = MavenDomUtil.findProject(projectDom); - - if(processSettingsXml(mavenProjectOrNull, processor, project, domProfileFunction)) - { - return true; - } - if(processProject(projectDom, mavenProjectOrNull, processor, project, domProfileFunction, projectDomFunction)) - { - return true; - } - - return processParentProjectFile(projectDom, processor, project, domProfileFunction, projectDomFunction, processed); - } - - private static boolean processParentProjectFile(MavenDomProjectModel projectDom, final Processor processor, final Project project, - final Function domProfileFunction, final Function projectDomFunction, - final Set processed) - { - Boolean aBoolean = new DomParentProjectFileProcessor(MavenProjectsManager.getInstance(project)) - { - protected Boolean doProcessParent(VirtualFile parentFile) - { - MavenDomProjectModel parentProjectDom = MavenDomUtil.getMavenDomProjectModel(project, parentFile); - if(parentProjectDom == null) - { - return false; - } - - return MavenDomProjectProcessorUtils.process(parentProjectDom, processor, project, domProfileFunction, projectDomFunction, - processed); - } - }.process(projectDom); - - return aBoolean == null ? false : aBoolean.booleanValue(); - } - - - private static boolean processSettingsXml(@Nullable MavenProject mavenProject, @Nonnull Processor processor, @Nonnull Project project, - Function domProfileFunction) - { - MavenGeneralSettings settings = MavenProjectsManager.getInstance(project).getGeneralSettings(); - - for(VirtualFile each : settings.getEffectiveSettingsFiles()) - { - MavenDomSettingsModel settingsDom = MavenDomUtil.getMavenDomModel(project, each, MavenDomSettingsModel.class); - if(settingsDom == null) - { - continue; - } - - if(processProfiles(settingsDom.getProfiles(), mavenProject, processor, domProfileFunction)) - { - return true; - } - } - return false; - } - - private static boolean processProject(MavenDomProjectModel projectDom, MavenProject mavenProjectOrNull, Processor processor, - Project project, Function domProfileFunction, Function projectDomFunction) - { - - if(processProfilesXml(MavenDomUtil.getVirtualFile(projectDom), mavenProjectOrNull, processor, project, domProfileFunction)) - { - return true; - } - - if(processProfiles(projectDom.getProfiles(), mavenProjectOrNull, processor, domProfileFunction)) - { - return true; - } - - T t = projectDomFunction.apply(projectDom); - return t != null && processor.process(t); - } - - private static boolean processProfilesXml(VirtualFile projectFile, MavenProject mavenProjectOrNull, Processor processor, Project project, - Function f) - { - VirtualFile profilesFile = MavenUtil.findProfilesXmlFile(projectFile); - if(profilesFile == null) - { - return false; - } - - MavenDomProfiles profiles = MavenDomUtil.getMavenDomProfilesModel(project, profilesFile); - if(profiles == null) - { - return false; - } - - return processProfiles(profiles, mavenProjectOrNull, processor, f); - } - - private static boolean processProfiles(MavenDomProfiles profilesDom, MavenProject mavenProjectOrNull, Processor processor, - Function f) - { - Collection activePropfiles = mavenProjectOrNull == null ? null : mavenProjectOrNull.getActivatedProfilesIds().getEnabledProfiles(); - for(MavenDomProfile each : profilesDom.getProfiles()) - { - XmlTag idTag = each.getId().getXmlTag(); - if(idTag == null) - { - continue; - } - if(activePropfiles != null && !activePropfiles.contains(idTag.getValue().getTrimmedText())) - { - continue; - } - - if(processProfile(each, processor, f)) - { - return true; - } - } - return false; - } - - private static boolean processProfile(MavenDomProfile profileDom, Processor processor, Function f) - { - T t = f.apply(profileDom); - return t != null && processor.process(t); - } - - public abstract static class DomParentProjectFileProcessor extends MavenParentProjectFileProcessor - { - private final MavenProjectsManager myManager; - - public DomParentProjectFileProcessor(MavenProjectsManager manager) - { - myManager = manager; - } - - protected VirtualFile findManagedFile(@Nonnull MavenId id) - { - MavenProject project = myManager.findProject(id); - return project == null ? null : project.getFile(); - } - - @Nullable - public T process(@Nonnull MavenDomProjectModel projectDom) - { - MavenDomParent parent = projectDom.getMavenParent(); - MavenParentDesc parentDesc = null; - if(DomUtil.hasXml(parent)) - { - String parentGroupId = parent.getGroupId().getStringValue(); - String parentArtifactId = parent.getArtifactId().getStringValue(); - String parentVersion = parent.getVersion().getStringValue(); - String parentRelativePath = parent.getRelativePath().getStringValue(); - if(StringUtil.isEmptyOrSpaces(parentRelativePath)) - { - parentRelativePath = "../pom.xml"; - } - MavenId parentId = new MavenId(parentGroupId, parentArtifactId, parentVersion); - parentDesc = new MavenParentDesc(parentId, parentRelativePath); - } - - return process(myManager.getGeneralSettings(), MavenDomUtil.getVirtualFile(projectDom), parentDesc); - } - } - - public abstract static class SearchProcessor implements Processor - { - - private R myResult; - - @Override - public final boolean process(T t) - { - R res = find(t); - if(res != null) - { - myResult = res; - return true; - } - - return false; - } - - @Nullable - protected abstract R find(T element); - - public R getResult() - { - return myResult; - } - } +public class MavenDomProjectProcessorUtils { + private MavenDomProjectProcessorUtils() { + } + + @Nonnull + @RequiredReadAction + public static Set getChildrenProjects(@Nonnull final MavenDomProjectModel model) { + Set models = new HashSet<>(); + + collectChildrenProjects(model, models); + + return models; + } + + @RequiredReadAction + private static void collectChildrenProjects(@Nonnull final MavenDomProjectModel model, @Nonnull Set models) { + MavenProject mavenProject = MavenDomUtil.findProject(model); + if (mavenProject != null) { + final Project project = model.getManager().getProject(); + for (MavenProject inheritor : MavenProjectsManager.getInstance(project).findInheritors(mavenProject)) { + MavenDomProjectModel inheritorProjectModel = MavenDomUtil.getMavenDomProjectModel(project, inheritor.getFile()); + if (inheritorProjectModel != null && !models.contains(inheritorProjectModel)) { + models.add(inheritorProjectModel); + collectChildrenProjects(inheritorProjectModel, models); + } + } + } + } + + @Nonnull + @RequiredReadAction + public static Set collectParentProjects(@Nonnull final MavenDomProjectModel projectDom) { + final Set parents = new HashSet<>(); + + Processor collectProcessor = model -> { + parents.add(model); + return false; + }; + processParentProjects(projectDom, collectProcessor); + + return parents; + } + + @RequiredReadAction + public static void processParentProjects( + @Nonnull final MavenDomProjectModel projectDom, + @Nonnull final Processor processor + ) { + Set processed = new HashSet<>(); + Project project = projectDom.getManager().getProject(); + MavenDomProjectModel parent = findParent(projectDom, project); + while (parent != null) { + if (processed.contains(parent)) { + break; + } + processed.add(parent); + if (processor.process(parent)) { + break; + } + + parent = findParent(parent, project); + } + } + + @Nullable + @RequiredReadAction + public static MavenDomProjectModel findParent(@Nonnull MavenDomProjectModel model, Project project) { + return findParent(model.getMavenParent(), project); + } + + @Nullable + @RequiredReadAction + public static MavenDomProjectModel findParent(@Nonnull MavenDomParent mavenDomParent, Project project) { + if (!DomUtil.hasXml(mavenDomParent)) { + return null; + } + + MavenId id = new MavenId(mavenDomParent.getGroupId().getStringValue(), mavenDomParent.getArtifactId().getStringValue(), + mavenDomParent.getVersion().getStringValue() + ); + MavenProject mavenProject = MavenProjectsManager.getInstance(project).findProject(id); + + return mavenProject != null ? MavenDomUtil.getMavenDomProjectModel(project, mavenProject.getFile()) : null; + } + + @Nullable + @RequiredReadAction + public static XmlTag searchProperty( + @Nonnull final String propertyName, + @Nonnull MavenDomProjectModel projectDom, + @Nonnull final Project project + ) { + SearchProcessor searchProcessor = new SearchProcessor<>() { + @Override + protected XmlTag find(MavenDomProperties element) { + return findProperty(element, propertyName); + } + }; + + processProperties(projectDom, searchProcessor, project); + return searchProcessor.myResult; + } + + @Nullable + public static XmlTag findProperty(@Nonnull MavenDomProperties mavenDomProperties, @Nonnull String propertyName) { + XmlTag propertiesTag = mavenDomProperties.getXmlTag(); + if (propertiesTag == null) { + return null; + } + + for (XmlTag each : propertiesTag.getSubTags()) { + if (each.getName().equals(propertyName)) { + return each; + } + } + + return null; + } + + @RequiredReadAction + public static Set collectProperties(@Nonnull MavenDomProjectModel projectDom, @Nonnull final Project project) { + final Set properties = new HashSet<>(); + + Processor collectProcessor = mavenDomProperties -> { + XmlTag propertiesTag = mavenDomProperties.getXmlTag(); + if (propertiesTag != null) { + ContainerUtil.addAll(properties, propertiesTag.getSubTags()); + } + return false; + }; + + processProperties(projectDom, collectProcessor, project); + + return properties; + } + + @Nonnull + @RequiredReadAction + public static Set searchDependencyUsages(@Nonnull final MavenDomDependency dependency) { + final MavenDomProjectModel model = dependency.getParentOfType(MavenDomProjectModel.class, false); + if (model != null) { + DependencyConflictId dependencyId = DependencyConflictId.create(dependency); + if (dependencyId != null) { + return searchDependencyUsages(model, dependencyId, Collections.singleton(dependency)); + } + } + return Collections.emptySet(); + } + + @Nonnull + @RequiredReadAction + public static Set searchDependencyUsages( + @Nonnull final MavenDomProjectModel model, + @Nonnull final DependencyConflictId dependencyId, + @Nonnull final Set excludes + ) { + Project project = model.getManager().getProject(); + final Set usages = new HashSet<>(); + Processor collectProcessor = mavenDomProjectModel -> { + if (!model.equals(mavenDomProjectModel)) { + for (MavenDomDependency domDependency : mavenDomProjectModel.getDependencies().getDependencies()) { + if (excludes.contains(domDependency)) { + continue; + } + + if (dependencyId.equals(DependencyConflictId.create(domDependency))) { + usages.add(domDependency); + } + } + } + return false; + }; + + processChildrenRecursively(model, collectProcessor, project, new HashSet<>(), true); + + return usages; + } + + @Nonnull + @RequiredReadAction + public static Collection searchManagedPluginUsages(@Nonnull final MavenDomPlugin plugin) { + String artifactId = plugin.getArtifactId().getStringValue(); + if (artifactId == null) { + return Collections.emptyList(); + } + + String groupId = plugin.getGroupId().getStringValue(); + + MavenDomProjectModel model = plugin.getParentOfType(MavenDomProjectModel.class, false); + if (model == null) { + return Collections.emptyList(); + } + + return searchManagedPluginUsages(model, groupId, artifactId); + } + + @Nonnull + @RequiredReadAction + public static Collection searchManagedPluginUsages( + @Nonnull final MavenDomProjectModel model, + @Nullable final String groupId, + @Nonnull final String artifactId + ) { + Project project = model.getManager().getProject(); + + final Set usages = new HashSet<>(); + + Processor collectProcessor = mavenDomProjectModel -> { + for (MavenDomPlugin domPlugin : mavenDomProjectModel.getBuild().getPlugins().getPlugins()) { + if (MavenPluginDomUtil.isPlugin(domPlugin, groupId, artifactId)) { + usages.add(domPlugin); + } + } + return false; + }; + + processChildrenRecursively(model, collectProcessor, project, new HashSet<>(), true); + + return usages; + } + + @RequiredReadAction + public static void processChildrenRecursively( + @Nullable MavenDomProjectModel model, + @Nonnull Processor processor + ) { + processChildrenRecursively(model, processor, true); + } + + @RequiredReadAction + public static void processChildrenRecursively( + @Nullable MavenDomProjectModel model, + @Nonnull Processor processor, + boolean processCurrentModel + ) { + if (model != null) { + processChildrenRecursively( + model, + processor, + model.getManager().getProject(), + new HashSet<>(), + processCurrentModel + ); + } + } + + @RequiredReadAction + public static void processChildrenRecursively( + @Nullable MavenDomProjectModel model, + @Nonnull Processor processor, + @Nonnull Project project, + @Nonnull Set processedModels, + boolean strict + ) { + if (model != null && !processedModels.contains(model)) { + processedModels.add(model); + + if (strict && processor.process(model)) { + return; + } + + MavenProject mavenProject = MavenDomUtil.findProject(model); + if (mavenProject != null) { + for (MavenProject childProject : MavenProjectsManager.getInstance(project).findInheritors(mavenProject)) { + MavenDomProjectModel childProjectModel = MavenDomUtil.getMavenDomProjectModel(project, childProject.getFile()); + + processChildrenRecursively(childProjectModel, processor, project, processedModels, true); + } + } + } + } + + @Nullable + @RequiredReadAction + public static MavenDomDependency searchManagingDependency(@Nonnull final MavenDomDependency dependency) { + return searchManagingDependency(dependency, dependency.getManager().getProject()); + } + + @Nullable + @RequiredReadAction + public static MavenDomDependency searchManagingDependency( + @Nonnull final MavenDomDependency dependency, + @Nonnull final Project project + ) { + final DependencyConflictId depId = DependencyConflictId.create(dependency); + if (depId == null) { + return null; + } + + final MavenDomProjectModel model = dependency.getParentOfType(MavenDomProjectModel.class, false); + if (model == null) { + return null; + } + + final Ref res = new Ref<>(); + + Processor processor = dependency1 -> { + if (depId.equals(DependencyConflictId.create(dependency1))) { + res.set(dependency1); + return true; + } + + return false; + }; + + processDependenciesInDependencyManagement(model, processor, project); + + return res.get(); + } + + @Nullable + @RequiredReadAction + public static MavenDomPlugin searchManagingPlugin(@Nonnull final MavenDomPlugin plugin) { + final String artifactId = plugin.getArtifactId().getStringValue(); + final String groupId = plugin.getGroupId().getStringValue(); + if (artifactId == null) { + return null; + } + + final MavenDomProjectModel model = plugin.getParentOfType(MavenDomProjectModel.class, false); + if (model == null) { + return null; + } + + SearchProcessor processor = new SearchProcessor<>() { + @Override + protected MavenDomPlugin find(MavenDomPlugins mavenDomPlugins) { + if (!model.equals(mavenDomPlugins.getParentOfType(MavenDomProjectModel.class, true))) { + for (MavenDomPlugin domPlugin : mavenDomPlugins.getPlugins()) { + if (MavenPluginDomUtil.isPlugin(domPlugin, groupId, artifactId)) { + return domPlugin; + } + } + } + + return null; + } + }; + + Function domProfileFunction = + mavenDomProfile -> mavenDomProfile.getBuild().getPluginManagement().getPlugins(); + + process(model, processor, model.getManager().getProject(), domProfileFunction, domProfileFunction); + + return processor.myResult; + } + + @RequiredReadAction + public static boolean processDependenciesInDependencyManagement( + @Nonnull MavenDomProjectModel projectDom, + @Nonnull final Processor processor, + @Nonnull final Project project + ) { + Processor managedDependenciesListProcessor = dependencies -> { + SmartList importDependencies = null; + + for (MavenDomDependency domDependency : dependencies.getDependencies()) { + if ("import".equals(domDependency.getScope().getRawText())) { + if (importDependencies == null) { + importDependencies = new SmartList<>(); + } + + importDependencies.add(domDependency); + } + else if (processor.process(domDependency)) { + return true; + } + } + + if (importDependencies != null) { + for (MavenDomDependency domDependency : importDependencies) { + GenericDomValue version = domDependency.getVersion(); + if (version.getXmlElement() != null) { + GenericDomValueReference reference = new GenericDomValueReference<>(version); + PsiElement resolve = reference.resolve(); + + if (resolve instanceof XmlFile xmlFile) { + MavenDomProjectModel dependModel = MavenDomUtil.getMavenDomModel(xmlFile, MavenDomProjectModel.class); + if (dependModel != null) { + for (MavenDomDependency dep : dependModel.getDependencyManagement().getDependencies().getDependencies()) { + if (processor.process(dep)) { + return true; + } + } + } + } + } + } + } + + return false; + }; + + Function domFunction = + mavenDomProfile -> mavenDomProfile.getDependencyManagement().getDependencies(); + + return process(projectDom, managedDependenciesListProcessor, project, domFunction, domFunction); + } + + @RequiredReadAction + public static boolean processDependencies( + @Nonnull MavenDomProjectModel projectDom, + @Nonnull final Processor processor + ) { + Function domFunction = MavenDomProjectModelBase::getDependencies; + + return process(projectDom, processor, projectDom.getManager().getProject(), domFunction, domFunction); + } + + @RequiredReadAction + public static boolean processProperties( + @Nonnull MavenDomProjectModel projectDom, + @Nonnull final Processor processor, + @Nonnull final Project project + ) { + Function domFunction = MavenDomProjectModelBase::getProperties; + + return process(projectDom, processor, project, domFunction, domFunction); + } + + @RequiredReadAction + public static boolean process( + @Nonnull MavenDomProjectModel projectDom, + @Nonnull final Processor processor, + @Nonnull final Project project, + @Nonnull final Function domProfileFunction, + @Nonnull final Function projectDomFunction + ) { + return process(projectDom, processor, project, domProfileFunction, projectDomFunction, new HashSet<>()); + } + + @RequiredReadAction + public static boolean process( + @Nonnull MavenDomProjectModel projectDom, + @Nonnull final Processor processor, + @Nonnull final Project project, + @Nonnull final Function domProfileFunction, + @Nonnull final Function projectDomFunction, + final Set processed + ) { + if (processed.contains(projectDom)) { + return true; + } + processed.add(projectDom); + + MavenProject mavenProjectOrNull = MavenDomUtil.findProject(projectDom); + + if (processSettingsXml(mavenProjectOrNull, processor, project, domProfileFunction)) { + return true; + } + if (processProject(projectDom, mavenProjectOrNull, processor, project, domProfileFunction, projectDomFunction)) { + return true; + } + + return processParentProjectFile(projectDom, processor, project, domProfileFunction, projectDomFunction, processed); + } + + @RequiredReadAction + private static boolean processParentProjectFile( + MavenDomProjectModel projectDom, + final Processor processor, + final Project project, + final Function domProfileFunction, + final Function projectDomFunction, + final Set processed + ) { + Boolean aBoolean = new DomParentProjectFileProcessor(MavenProjectsManager.getInstance(project)) { + @Override + @RequiredReadAction + protected Boolean doProcessParent(VirtualFile parentFile) { + MavenDomProjectModel parentProjectDom = MavenDomUtil.getMavenDomProjectModel(project, parentFile); + return parentProjectDom != null && MavenDomProjectProcessorUtils.process( + parentProjectDom, + processor, + project, + domProfileFunction, + projectDomFunction, + processed + ); + } + }.process(projectDom); + + return aBoolean != null && aBoolean; + } + + @RequiredReadAction + private static boolean processSettingsXml( + @Nullable MavenProject mavenProject, + @Nonnull Processor processor, + @Nonnull Project project, + Function domProfileFunction + ) { + MavenGeneralSettings settings = MavenProjectsManager.getInstance(project).getGeneralSettings(); + + for (VirtualFile each : settings.getEffectiveSettingsFiles()) { + MavenDomSettingsModel settingsDom = MavenDomUtil.getMavenDomModel(project, each, MavenDomSettingsModel.class); + if (settingsDom == null) { + continue; + } + + if (processProfiles(settingsDom.getProfiles(), mavenProject, processor, domProfileFunction)) { + return true; + } + } + return false; + } + + @RequiredReadAction + private static boolean processProject( + MavenDomProjectModel projectDom, + MavenProject mavenProjectOrNull, + Processor processor, + Project project, + Function domProfileFunction, + Function projectDomFunction + ) { + if (processProfilesXml(MavenDomUtil.getVirtualFile(projectDom), mavenProjectOrNull, processor, project, domProfileFunction)) { + return true; + } + + if (processProfiles(projectDom.getProfiles(), mavenProjectOrNull, processor, domProfileFunction)) { + return true; + } + + T t = projectDomFunction.apply(projectDom); + return t != null && processor.process(t); + } + + @RequiredReadAction + private static boolean processProfilesXml( + VirtualFile projectFile, + MavenProject mavenProjectOrNull, + Processor processor, + Project project, + Function f + ) { + VirtualFile profilesFile = MavenUtil.findProfilesXmlFile(projectFile); + if (profilesFile == null) { + return false; + } + + MavenDomProfiles profiles = MavenDomUtil.getMavenDomProfilesModel(project, profilesFile); + return profiles != null && processProfiles(profiles, mavenProjectOrNull, processor, f); + } + + private static boolean processProfiles( + MavenDomProfiles profilesDom, + MavenProject mavenProjectOrNull, + Processor processor, + Function f + ) { + Collection activePropfiles = + mavenProjectOrNull == null ? null : mavenProjectOrNull.getActivatedProfilesIds().getEnabledProfiles(); + for (MavenDomProfile each : profilesDom.getProfiles()) { + XmlTag idTag = each.getId().getXmlTag(); + if (idTag == null) { + continue; + } + if (activePropfiles != null && !activePropfiles.contains(idTag.getValue().getTrimmedText())) { + continue; + } + + if (processProfile(each, processor, f)) { + return true; + } + } + return false; + } + + private static boolean processProfile(MavenDomProfile profileDom, Processor processor, Function f) { + T t = f.apply(profileDom); + return t != null && processor.process(t); + } + + public abstract static class DomParentProjectFileProcessor extends MavenParentProjectFileProcessor { + private final MavenProjectsManager myManager; + + public DomParentProjectFileProcessor(MavenProjectsManager manager) { + myManager = manager; + } + + @Override + protected VirtualFile findManagedFile(@Nonnull MavenId id) { + MavenProject project = myManager.findProject(id); + return project == null ? null : project.getFile(); + } + + @Nullable + public T process(@Nonnull MavenDomProjectModel projectDom) { + MavenDomParent parent = projectDom.getMavenParent(); + MavenParentDesc parentDesc = null; + if (DomUtil.hasXml(parent)) { + String parentGroupId = parent.getGroupId().getStringValue(); + String parentArtifactId = parent.getArtifactId().getStringValue(); + String parentVersion = parent.getVersion().getStringValue(); + String parentRelativePath = parent.getRelativePath().getStringValue(); + if (StringUtil.isEmptyOrSpaces(parentRelativePath)) { + parentRelativePath = "../pom.xml"; + } + MavenId parentId = new MavenId(parentGroupId, parentArtifactId, parentVersion); + parentDesc = new MavenParentDesc(parentId, parentRelativePath); + } + + return process(myManager.getGeneralSettings(), MavenDomUtil.getVirtualFile(projectDom), parentDesc); + } + } + + public abstract static class SearchProcessor implements Processor { + private R myResult; + + @Override + public final boolean process(T t) { + R res = find(t); + if (res != null) { + myResult = res; + return true; + } + + return false; + } + + @Nullable + protected abstract R find(T element); + + public R getResult() { + return myResult; + } + } } diff --git a/plugin/src/main/java/org/jetbrains/idea/maven/dom/MavenDomSettingsModelDescription.java b/plugin/src/main/java/org/jetbrains/idea/maven/dom/MavenDomSettingsModelDescription.java index 6430208e..f5dca2ad 100644 --- a/plugin/src/main/java/org/jetbrains/idea/maven/dom/MavenDomSettingsModelDescription.java +++ b/plugin/src/main/java/org/jetbrains/idea/maven/dom/MavenDomSettingsModelDescription.java @@ -20,7 +20,7 @@ @ExtensionImpl public class MavenDomSettingsModelDescription extends MavenDomFileDescription { - public MavenDomSettingsModelDescription() { - super(MavenDomSettingsModel.class, "settings"); - } + public MavenDomSettingsModelDescription() { + super(MavenDomSettingsModel.class, "settings"); + } } diff --git a/plugin/src/main/java/org/jetbrains/idea/maven/dom/MavenDomUtil.java b/plugin/src/main/java/org/jetbrains/idea/maven/dom/MavenDomUtil.java index bb37b393..17ddf7c2 100644 --- a/plugin/src/main/java/org/jetbrains/idea/maven/dom/MavenDomUtil.java +++ b/plugin/src/main/java/org/jetbrains/idea/maven/dom/MavenDomUtil.java @@ -17,6 +17,8 @@ import com.intellij.lang.properties.IProperty; import com.intellij.lang.properties.psi.PropertiesFile; +import consulo.annotation.access.RequiredReadAction; +import consulo.annotation.access.RequiredWriteAction; import consulo.codeEditor.Editor; import consulo.language.psi.PsiElement; import consulo.language.psi.PsiFile; @@ -58,536 +60,470 @@ import java.util.regex.Matcher; import java.util.regex.Pattern; -public class MavenDomUtil -{ - - private static final Key>> FILTERED_RESOURCES_ROOTS_KEY = Key.create("MavenDomUtil.FILTERED_RESOURCES_ROOTS"); - - // see http://maven.apache.org/settings.html - private static final Set SUBTAGS_IN_SETTINGS_FILE = Set.of("localRepository", "interactiveMode", "usePluginRegistry", - "offline", "pluginGroups", "servers", "mirrors", "proxies", "profiles", "activeProfiles"); - - public static boolean isMavenFile(PsiFile file) - { - return isProjectFile(file) || isProfilesFile(file) || isSettingsFile(file); - } - - public static boolean isProjectFile(PsiFile file) - { - if(!(file instanceof XmlFile)) - { - return false; - } - - String name = file.getName(); - return name.equals(MavenConstants.POM_XML) || - name.endsWith(".pom") || - name.equals(MavenConstants.SUPER_POM_XML); - } - - public static boolean isProfilesFile(PsiFile file) - { - if(!(file instanceof XmlFile)) - { - return false; - } - - return MavenConstants.PROFILES_XML.equals(file.getName()); - } - - public static boolean isSettingsFile(PsiFile file) - { - if(!(file instanceof XmlFile)) - { - return false; - } - - String name = file.getName(); - if(!name.equals(MavenConstants.SETTINGS_XML)) - { - return false; - } - - XmlTag rootTag = ((XmlFile) file).getRootTag(); - if(rootTag == null || !"settings".equals(rootTag.getName())) - { - return false; - } - - String xmlns = rootTag.getAttributeValue("xmlns"); - if(xmlns != null) - { - return xmlns.contains("maven"); - } - - boolean hasTag = false; - - for(PsiElement e = rootTag.getFirstChild(); e != null; e = e.getNextSibling()) - { - if(e instanceof XmlTag) - { - if(SUBTAGS_IN_SETTINGS_FILE.contains(((XmlTag) e).getName())) - { - return true; - } - hasTag = true; - } - } - - return !hasTag; - } - - public static boolean isMavenFile(PsiElement element) - { - return isMavenFile(element.getContainingFile()); - } - - @Nullable - public static Module findContainingMavenizedModule(@Nonnull PsiFile psiFile) - { - VirtualFile file = psiFile.getVirtualFile(); - if(file == null) - { - return null; - } - - Project project = psiFile.getProject(); - - MavenProjectsManager manager = MavenProjectsManager.getInstance(project); - if(!manager.isMavenizedProject()) - { - return null; - } - - ProjectFileIndex index = ProjectRootManager.getInstance(project).getFileIndex(); - - consulo.module.Module module = index.getModuleForFile(file); - if(module == null || !manager.isMavenizedModule(module)) - { - return null; - } - return module; - } - - public static boolean isMavenProperty(PsiElement target) - { - XmlTag tag = PsiTreeUtil.getParentOfType(target, XmlTag.class, false); - if(tag == null) - { - return false; - } - return DomUtil.findDomElement(tag, MavenDomProperties.class) != null; - } - - public static String calcRelativePath(VirtualFile parent, VirtualFile child) - { - String result = FileUtil.getRelativePath(parent.getPath(), child.getPath(), '/'); - if(result == null) - { - MavenLog.LOG.warn("cannot calculate relative path for\nparent: " + parent + "\nchild: " + child); - result = child.getPath(); - } - return FileUtil.toSystemIndependentName(result); - } - - public static MavenDomParent updateMavenParent(MavenDomProjectModel mavenModel, MavenProject parentProject) - { - MavenDomParent result = mavenModel.getMavenParent(); - - VirtualFile pomFile = DomUtil.getFile(mavenModel).getVirtualFile(); - Project project = mavenModel.getXmlElement().getProject(); - - MavenId parentId = parentProject.getMavenId(); - result.getGroupId().setStringValue(parentId.getGroupId()); - result.getArtifactId().setStringValue(parentId.getArtifactId()); - result.getVersion().setStringValue(parentId.getVersion()); - - if(!Comparing.equal(pomFile.getParent().getParent(), parentProject.getDirectoryFile())) - { - result.getRelativePath().setValue(PsiManager.getInstance(project).findFile(parentProject.getFile())); - } - - return result; - } - - public static T getImmediateParent(ConvertContext context, Class clazz) - { - DomElement parentElement = context.getInvocationElement().getParent(); - return clazz.isInstance(parentElement) ? (T) parentElement : null; - } - - @Nullable - public static VirtualFile getVirtualFile(@Nonnull DomElement element) - { - PsiFile psiFile = DomUtil.getFile(element); - return getVirtualFile(psiFile); - } - - @Nullable - public static VirtualFile getVirtualFile(@Nonnull PsiElement element) - { - PsiFile psiFile = element.getContainingFile(); - return getVirtualFile(psiFile); - } - - @Nullable - private static VirtualFile getVirtualFile(PsiFile psiFile) - { - if(psiFile == null) - { - return null; - } - psiFile = psiFile.getOriginalFile(); - return psiFile.getVirtualFile(); - } - - @Nullable - public static MavenProject findProject(@Nonnull MavenDomProjectModel projectDom) - { - XmlElement element = projectDom.getXmlElement(); - if(element == null) - { - return null; - } - - VirtualFile file = getVirtualFile(element); - if(file == null) - { - return null; - } - MavenProjectsManager manager = MavenProjectsManager.getInstance(element.getProject()); - return manager.findProject(file); - } - - @Nullable - public static MavenProject findContainingProject(@Nonnull DomElement element) - { - PsiElement psi = element.getXmlElement(); - return psi == null ? null : findContainingProject(psi); - } - - @Nullable - public static MavenProject findContainingProject(@Nonnull PsiElement element) - { - VirtualFile file = getVirtualFile(element); - if(file == null) - { - return null; - } - MavenProjectsManager manager = MavenProjectsManager.getInstance(element.getProject()); - return manager.findContainingProject(file); - } - - @Nullable - public static MavenDomProjectModel getMavenDomProjectModel(@Nonnull Project project, @Nonnull VirtualFile file) - { - return getMavenDomModel(project, file, MavenDomProjectModel.class); - } - - @Nullable - public static MavenDomProfiles getMavenDomProfilesModel(@Nonnull Project project, @Nonnull VirtualFile file) - { - MavenDomProfilesModel model = getMavenDomModel(project, file, MavenDomProfilesModel.class); - if(model != null) - { - return model.getProfiles(); - } - return getMavenDomModel(project, file, MavenDomProfiles.class); // try old-style model - } - - @Nullable - public static T getMavenDomModel(@Nonnull Project project, @Nonnull VirtualFile file, @Nonnull Class clazz) - { - if(!file.isValid()) - { - return null; - } - PsiFile psiFile = PsiManager.getInstance(project).findFile(file); - if(psiFile == null) - { - return null; - } - return getMavenDomModel(psiFile, clazz); - } - - @Nullable - public static T getMavenDomModel(@Nonnull PsiFile file, @Nonnull Class clazz) - { - DomFileElement fileElement = getMavenDomFile(file, clazz); - return fileElement == null ? null : fileElement.getRootElement(); - } - - @Nullable - private static DomFileElement getMavenDomFile(@Nonnull PsiFile file, @Nonnull Class clazz) - { - if(!(file instanceof XmlFile)) - { - return null; - } - return DomManager.getDomManager(file.getProject()).getFileElement((XmlFile) file, clazz); - } - - @Nullable - public static XmlTag findTag(@Nonnull DomElement domElement, @Nonnull String path) - { - List elements = StringUtil.split(path, "."); - if(elements.isEmpty()) - { - return null; - } - - Pair nameAndIndex = translateTagName(elements.get(0)); - String name = nameAndIndex.first; - Integer index = nameAndIndex.second; - - XmlTag result = domElement.getXmlTag(); - if(result == null || !name.equals(result.getName())) - { - return null; - } - result = getIndexedTag(result, index); - - for(String each : elements.subList(1, elements.size())) - { - nameAndIndex = translateTagName(each); - name = nameAndIndex.first; - index = nameAndIndex.second; - - result = result.findFirstSubTag(name); - if(result == null) - { - return null; - } - result = getIndexedTag(result, index); - } - return result; - } - - private static final Pattern XML_TAG_NAME_PATTERN = Pattern.compile("(\\S*)\\[(\\d*)\\]\\z"); - - private static Pair translateTagName(String text) - { - String tagName = text.trim(); - Integer index = null; - - Matcher matcher = XML_TAG_NAME_PATTERN.matcher(tagName); - if(matcher.find()) - { - tagName = matcher.group(1); - try - { - index = Integer.parseInt(matcher.group(2)); - } - catch(NumberFormatException e) - { - return null; - } - } - - return Pair.create(tagName, index); - } - - private static XmlTag getIndexedTag(XmlTag parent, Integer index) - { - if(index == null) - { - return parent; - } - - XmlTag[] children = parent.getSubTags(); - if(index < 0 || index >= children.length) - { - return null; - } - return children[index]; - } - - @Nullable - public static PropertiesFile getPropertiesFile(@Nonnull Project project, @Nonnull VirtualFile file) - { - PsiFile psiFile = PsiManager.getInstance(project).findFile(file); - if(!(psiFile instanceof PropertiesFile)) - { - return null; - } - return (PropertiesFile) psiFile; - } - - @Nullable - public static IProperty findProperty(@Nonnull Project project, @Nonnull VirtualFile file, @Nonnull String propName) - { - PropertiesFile propertiesFile = getPropertiesFile(project, file); - return propertiesFile == null ? null : propertiesFile.findPropertyByKey(propName); - } - - @Nullable - public static PsiElement findPropertyValue(@Nonnull Project project, @Nonnull VirtualFile file, @Nonnull String propName) - { - IProperty prop = findProperty(project, file, propName); - return prop == null ? null : prop.getPsiElement().getFirstChild().getNextSibling().getNextSibling(); - } - - private static Set getFilteredResourcesRoots(@Nonnull MavenProject mavenProject) - { - Pair> cachedValue = mavenProject.getCachedValue(FILTERED_RESOURCES_ROOTS_KEY); - - if(cachedValue == null || cachedValue.first != VirtualFileManager.getInstance().getModificationCount()) - { - Set set = null; - - for(MavenResource resource : ContainerUtil.concat(mavenProject.getResources(), mavenProject.getTestResources())) - { - if(!resource.isFiltered()) - { - continue; - } - - VirtualFile resourceDir = LocalFileSystem.getInstance().findFileByPath(resource.getDirectory()); - if(resourceDir == null) - { - continue; - } - - if(set == null) - { - set = new HashSet(); - } - - set.add(resourceDir); - } - - if(set == null) - { - set = Collections.emptySet(); - } - - cachedValue = Pair.create(VirtualFileManager.getInstance().getModificationCount(), set); - mavenProject.putCachedValue(FILTERED_RESOURCES_ROOTS_KEY, cachedValue); - } - - return cachedValue.second; - } - - public static boolean isFilteredResourceFile(PsiElement element) - { - VirtualFile file = getVirtualFile(element); - if(file == null) - { - return false; - } - - MavenProjectsManager manager = MavenProjectsManager.getInstance(element.getProject()); - MavenProject mavenProject = manager.findContainingProject(file); - if(mavenProject == null) - { - return false; - } - - Set filteredRoots = getFilteredResourcesRoots(mavenProject); - - if(!filteredRoots.isEmpty()) - { - for(VirtualFile f = file.getParent(); f != null; f = f.getParent()) - { - if(filteredRoots.contains(f)) - { - return true; - } - } - } - - return false; - } - - public static List> collectProjectModels(Project p) - { - return DomService.getInstance().getFileElements(MavenDomProjectModel.class, p, GlobalSearchScope.projectScope(p)); - } - - public static MavenId describe(PsiFile psiFile) - { - MavenDomProjectModel model = getMavenDomModel(psiFile, MavenDomProjectModel.class); - - String groupId = model.getGroupId().getStringValue(); - String artifactId = model.getArtifactId().getStringValue(); - String version = model.getVersion().getStringValue(); - - if(groupId == null) - { - groupId = model.getMavenParent().getGroupId().getStringValue(); - } - - if(version == null) - { - version = model.getMavenParent().getVersion().getStringValue(); - } - - return new MavenId(groupId, artifactId, version); - } - - @Nonnull - public static MavenDomDependency createDomDependency(MavenDomProjectModel model, @Nullable Editor editor, @Nonnull final MavenId id) - { - return createDomDependency(model.getDependencies(), editor, id); - } - - @Nonnull - public static MavenDomDependency createDomDependency(MavenDomDependencies dependencies, @Nullable Editor editor, @Nonnull final MavenId id) - { - MavenDomDependency dep = createDomDependency(dependencies, editor); - - dep.getGroupId().setStringValue(id.getGroupId()); - dep.getArtifactId().setStringValue(id.getArtifactId()); - dep.getVersion().setStringValue(id.getVersion()); - - return dep; - } - - @Nonnull - public static MavenDomDependency createDomDependency(@Nonnull MavenDomProjectModel model, @Nullable Editor editor) - { - return createDomDependency(model.getDependencies(), editor); - } - - @Nonnull - public static MavenDomDependency createDomDependency(@Nonnull MavenDomDependencies dependencies, @Nullable Editor editor) - { - int index = getCollectionIndex(dependencies, editor); - if(index >= 0) - { - DomCollectionChildDescription childDescription = dependencies.getGenericInfo().getCollectionChildDescription("dependency"); - if(childDescription != null) - { - DomElement element = childDescription.addValue(dependencies, index); - if(element instanceof MavenDomDependency) - { - return (MavenDomDependency) element; - } - } - } - return dependencies.addDependency(); - } - - - public static int getCollectionIndex(@Nonnull final MavenDomDependencies dependencies, @Nullable final Editor editor) - { - if(editor != null) - { - int offset = editor.getCaretModel().getOffset(); - - List dependencyList = dependencies.getDependencies(); - - for(int i = 0; i < dependencyList.size(); i++) - { - MavenDomDependency dependency = dependencyList.get(i); - XmlElement xmlElement = dependency.getXmlElement(); - - if(xmlElement != null && xmlElement.getTextRange().getStartOffset() >= offset) - { - return i; - } - } - } - return -1; - } +public class MavenDomUtil { + private static final Key>> FILTERED_RESOURCES_ROOTS_KEY = + Key.create("MavenDomUtil.FILTERED_RESOURCES_ROOTS"); + + // see http://maven.apache.org/settings.html + private static final Set SUBTAGS_IN_SETTINGS_FILE = Set.of( + "localRepository", + "interactiveMode", + "usePluginRegistry", + "offline", + "pluginGroups", + "servers", + "mirrors", + "proxies", + "profiles", + "activeProfiles" + ); + + @RequiredReadAction + public static boolean isMavenFile(PsiFile file) { + return isProjectFile(file) || isProfilesFile(file) || isSettingsFile(file); + } + + @RequiredReadAction + public static boolean isProjectFile(PsiFile file) { + if (!(file instanceof XmlFile)) { + return false; + } + + String name = file.getName(); + return name.equals(MavenConstants.POM_XML) + || name.endsWith(".pom") + || name.equals(MavenConstants.SUPER_POM_XML); + } + + @RequiredReadAction + public static boolean isProfilesFile(PsiFile file) { + return file instanceof XmlFile && MavenConstants.PROFILES_XML.equals(file.getName()); + } + + @RequiredReadAction + public static boolean isSettingsFile(PsiFile file) { + if (!(file instanceof XmlFile)) { + return false; + } + + String name = file.getName(); + if (!name.equals(MavenConstants.SETTINGS_XML)) { + return false; + } + + XmlTag rootTag = ((XmlFile)file).getRootTag(); + if (rootTag == null || !"settings".equals(rootTag.getName())) { + return false; + } + + String xmlns = rootTag.getAttributeValue("xmlns"); + if (xmlns != null) { + return xmlns.contains("maven"); + } + + boolean hasTag = false; + + for (PsiElement e = rootTag.getFirstChild(); e != null; e = e.getNextSibling()) { + if (e instanceof XmlTag tag) { + if (SUBTAGS_IN_SETTINGS_FILE.contains(tag.getName())) { + return true; + } + hasTag = true; + } + } + + return !hasTag; + } + + @RequiredReadAction + public static boolean isMavenFile(PsiElement element) { + return isMavenFile(element.getContainingFile()); + } + + @Nullable + public static Module findContainingMavenizedModule(@Nonnull PsiFile psiFile) { + VirtualFile file = psiFile.getVirtualFile(); + if (file == null) { + return null; + } + + Project project = psiFile.getProject(); + + MavenProjectsManager manager = MavenProjectsManager.getInstance(project); + if (!manager.isMavenizedProject()) { + return null; + } + + ProjectFileIndex index = ProjectRootManager.getInstance(project).getFileIndex(); + + consulo.module.Module module = index.getModuleForFile(file); + if (module == null || !manager.isMavenizedModule(module)) { + return null; + } + return module; + } + + public static boolean isMavenProperty(PsiElement target) { + XmlTag tag = PsiTreeUtil.getParentOfType(target, XmlTag.class, false); + return tag != null && DomUtil.findDomElement(tag, MavenDomProperties.class) != null; + } + + public static String calcRelativePath(VirtualFile parent, VirtualFile child) { + String result = FileUtil.getRelativePath(parent.getPath(), child.getPath(), '/'); + if (result == null) { + MavenLog.LOG.warn("cannot calculate relative path for\nparent: " + parent + "\nchild: " + child); + result = child.getPath(); + } + return FileUtil.toSystemIndependentName(result); + } + + @RequiredWriteAction + public static MavenDomParent updateMavenParent(MavenDomProjectModel mavenModel, MavenProject parentProject) { + MavenDomParent result = mavenModel.getMavenParent(); + + VirtualFile pomFile = DomUtil.getFile(mavenModel).getVirtualFile(); + Project project = mavenModel.getXmlElement().getProject(); + + MavenId parentId = parentProject.getMavenId(); + result.getGroupId().setStringValue(parentId.getGroupId()); + result.getArtifactId().setStringValue(parentId.getArtifactId()); + result.getVersion().setStringValue(parentId.getVersion()); + + if (!Comparing.equal(pomFile.getParent().getParent(), parentProject.getDirectoryFile())) { + result.getRelativePath().setValue(PsiManager.getInstance(project).findFile(parentProject.getFile())); + } + + return result; + } + + @SuppressWarnings("unchecked") + public static T getImmediateParent(ConvertContext context, Class clazz) { + DomElement parentElement = context.getInvocationElement().getParent(); + return clazz.isInstance(parentElement) ? (T)parentElement : null; + } + + @Nullable + public static VirtualFile getVirtualFile(@Nonnull DomElement element) { + PsiFile psiFile = DomUtil.getFile(element); + return getVirtualFile(psiFile); + } + + @Nullable + public static VirtualFile getVirtualFile(@Nonnull PsiElement element) { + PsiFile psiFile = element.getContainingFile(); + return getVirtualFile(psiFile); + } + + @Nullable + private static VirtualFile getVirtualFile(PsiFile psiFile) { + if (psiFile == null) { + return null; + } + psiFile = psiFile.getOriginalFile(); + return psiFile.getVirtualFile(); + } + + @Nullable + public static MavenProject findProject(@Nonnull MavenDomProjectModel projectDom) { + XmlElement element = projectDom.getXmlElement(); + if (element == null) { + return null; + } + + VirtualFile file = getVirtualFile(element); + if (file == null) { + return null; + } + MavenProjectsManager manager = MavenProjectsManager.getInstance(element.getProject()); + return manager.findProject(file); + } + + @Nullable + public static MavenProject findContainingProject(@Nonnull DomElement element) { + PsiElement psi = element.getXmlElement(); + return psi == null ? null : findContainingProject(psi); + } + + @Nullable + public static MavenProject findContainingProject(@Nonnull PsiElement element) { + VirtualFile file = getVirtualFile(element); + if (file == null) { + return null; + } + MavenProjectsManager manager = MavenProjectsManager.getInstance(element.getProject()); + return manager.findContainingProject(file); + } + + @Nullable + @RequiredReadAction + public static MavenDomProjectModel getMavenDomProjectModel(@Nonnull Project project, @Nonnull VirtualFile file) { + return getMavenDomModel(project, file, MavenDomProjectModel.class); + } + + @Nullable + @RequiredReadAction + public static MavenDomProfiles getMavenDomProfilesModel(@Nonnull Project project, @Nonnull VirtualFile file) { + MavenDomProfilesModel model = getMavenDomModel(project, file, MavenDomProfilesModel.class); + if (model != null) { + return model.getProfiles(); + } + return getMavenDomModel(project, file, MavenDomProfiles.class); // try old-style model + } + + @Nullable + @RequiredReadAction + public static T getMavenDomModel( + @Nonnull Project project, + @Nonnull VirtualFile file, + @Nonnull Class clazz + ) { + if (!file.isValid()) { + return null; + } + PsiFile psiFile = PsiManager.getInstance(project).findFile(file); + if (psiFile == null) { + return null; + } + return getMavenDomModel(psiFile, clazz); + } + + @Nullable + public static T getMavenDomModel(@Nonnull PsiFile file, @Nonnull Class clazz) { + DomFileElement fileElement = getMavenDomFile(file, clazz); + return fileElement == null ? null : fileElement.getRootElement(); + } + + @Nullable + private static DomFileElement getMavenDomFile(@Nonnull PsiFile file, @Nonnull Class clazz) { + return file instanceof XmlFile xmlFile ? DomManager.getDomManager(file.getProject()).getFileElement(xmlFile, clazz) : null; + } + + @Nullable + public static XmlTag findTag(@Nonnull DomElement domElement, @Nonnull String path) { + List elements = StringUtil.split(path, "."); + if (elements.isEmpty()) { + return null; + } + + Pair nameAndIndex = translateTagName(elements.get(0)); + String name = nameAndIndex.first; + Integer index = nameAndIndex.second; + + XmlTag result = domElement.getXmlTag(); + if (result == null || !name.equals(result.getName())) { + return null; + } + result = getIndexedTag(result, index); + + for (String each : elements.subList(1, elements.size())) { + nameAndIndex = translateTagName(each); + name = nameAndIndex.first; + index = nameAndIndex.second; + + result = result.findFirstSubTag(name); + if (result == null) { + return null; + } + result = getIndexedTag(result, index); + } + return result; + } + + private static final Pattern XML_TAG_NAME_PATTERN = Pattern.compile("(\\S*)\\[(\\d*)\\]\\z"); + + private static Pair translateTagName(String text) { + String tagName = text.trim(); + Integer index = null; + + Matcher matcher = XML_TAG_NAME_PATTERN.matcher(tagName); + if (matcher.find()) { + tagName = matcher.group(1); + try { + index = Integer.parseInt(matcher.group(2)); + } + catch (NumberFormatException e) { + return null; + } + } + + return Pair.create(tagName, index); + } + + private static XmlTag getIndexedTag(XmlTag parent, Integer index) { + if (index == null) { + return parent; + } + + XmlTag[] children = parent.getSubTags(); + if (index < 0 || index >= children.length) { + return null; + } + return children[index]; + } + + @Nullable + @RequiredReadAction + public static PropertiesFile getPropertiesFile(@Nonnull Project project, @Nonnull VirtualFile file) { + PsiFile psiFile = PsiManager.getInstance(project).findFile(file); + if (!(psiFile instanceof PropertiesFile)) { + return null; + } + return (PropertiesFile)psiFile; + } + + @Nullable + @RequiredReadAction + public static IProperty findProperty(@Nonnull Project project, @Nonnull VirtualFile file, @Nonnull String propName) { + PropertiesFile propertiesFile = getPropertiesFile(project, file); + return propertiesFile == null ? null : propertiesFile.findPropertyByKey(propName); + } + + @Nullable + @RequiredReadAction + public static PsiElement findPropertyValue(@Nonnull Project project, @Nonnull VirtualFile file, @Nonnull String propName) { + IProperty prop = findProperty(project, file, propName); + return prop == null ? null : prop.getPsiElement().getFirstChild().getNextSibling().getNextSibling(); + } + + private static Set getFilteredResourcesRoots(@Nonnull MavenProject mavenProject) { + Pair> cachedValue = mavenProject.getCachedValue(FILTERED_RESOURCES_ROOTS_KEY); + + if (cachedValue == null || cachedValue.first != VirtualFileManager.getInstance().getModificationCount()) { + Set set = null; + + for (MavenResource resource : ContainerUtil.concat(mavenProject.getResources(), mavenProject.getTestResources())) { + if (!resource.isFiltered()) { + continue; + } + + VirtualFile resourceDir = LocalFileSystem.getInstance().findFileByPath(resource.getDirectory()); + if (resourceDir == null) { + continue; + } + + if (set == null) { + set = new HashSet<>(); + } + + set.add(resourceDir); + } + + if (set == null) { + set = Collections.emptySet(); + } + + cachedValue = Pair.create(VirtualFileManager.getInstance().getModificationCount(), set); + mavenProject.putCachedValue(FILTERED_RESOURCES_ROOTS_KEY, cachedValue); + } + + return cachedValue.second; + } + + public static boolean isFilteredResourceFile(PsiElement element) { + VirtualFile file = getVirtualFile(element); + if (file == null) { + return false; + } + + MavenProjectsManager manager = MavenProjectsManager.getInstance(element.getProject()); + MavenProject mavenProject = manager.findContainingProject(file); + if (mavenProject == null) { + return false; + } + + Set filteredRoots = getFilteredResourcesRoots(mavenProject); + + if (!filteredRoots.isEmpty()) { + for (VirtualFile f = file.getParent(); f != null; f = f.getParent()) { + if (filteredRoots.contains(f)) { + return true; + } + } + } + + return false; + } + + public static List> collectProjectModels(Project p) { + return DomService.getInstance().getFileElements(MavenDomProjectModel.class, p, GlobalSearchScope.projectScope(p)); + } + + public static MavenId describe(PsiFile psiFile) { + MavenDomProjectModel model = getMavenDomModel(psiFile, MavenDomProjectModel.class); + + String groupId = model.getGroupId().getStringValue(); + String artifactId = model.getArtifactId().getStringValue(); + String version = model.getVersion().getStringValue(); + + if (groupId == null) { + groupId = model.getMavenParent().getGroupId().getStringValue(); + } + + if (version == null) { + version = model.getMavenParent().getVersion().getStringValue(); + } + + return new MavenId(groupId, artifactId, version); + } + + @Nonnull + public static MavenDomDependency createDomDependency(MavenDomProjectModel model, @Nullable Editor editor, @Nonnull final MavenId id) { + return createDomDependency(model.getDependencies(), editor, id); + } + + @Nonnull + public static MavenDomDependency createDomDependency( + MavenDomDependencies dependencies, + @Nullable Editor editor, + @Nonnull final MavenId id + ) { + MavenDomDependency dep = createDomDependency(dependencies, editor); + + dep.getGroupId().setStringValue(id.getGroupId()); + dep.getArtifactId().setStringValue(id.getArtifactId()); + dep.getVersion().setStringValue(id.getVersion()); + + return dep; + } + + @Nonnull + @RequiredReadAction + public static MavenDomDependency createDomDependency(@Nonnull MavenDomProjectModel model, @Nullable Editor editor) { + return createDomDependency(model.getDependencies(), editor); + } + + @Nonnull + @RequiredReadAction + public static MavenDomDependency createDomDependency(@Nonnull MavenDomDependencies dependencies, @Nullable Editor editor) { + int index = getCollectionIndex(dependencies, editor); + if (index >= 0) { + DomCollectionChildDescription childDescription = dependencies.getGenericInfo().getCollectionChildDescription("dependency"); + if (childDescription != null) { + DomElement element = childDescription.addValue(dependencies, index); + if (element instanceof MavenDomDependency domDependency) { + return domDependency; + } + } + } + return dependencies.addDependency(); + } + + @RequiredReadAction + public static int getCollectionIndex(@Nonnull final MavenDomDependencies dependencies, @Nullable final Editor editor) { + if (editor != null) { + int offset = editor.getCaretModel().getOffset(); + + List dependencyList = dependencies.getDependencies(); + + for (int i = 0; i < dependencyList.size(); i++) { + MavenDomDependency dependency = dependencyList.get(i); + XmlElement xmlElement = dependency.getXmlElement(); + + if (xmlElement != null && xmlElement.getTextRange().getStartOffset() >= offset) { + return i; + } + } + } + return -1; + } } diff --git a/plugin/src/main/java/org/jetbrains/idea/maven/dom/MavenModelDocumentationProvider.java b/plugin/src/main/java/org/jetbrains/idea/maven/dom/MavenModelDocumentationProvider.java index 3b966bda..a507c7c3 100644 --- a/plugin/src/main/java/org/jetbrains/idea/maven/dom/MavenModelDocumentationProvider.java +++ b/plugin/src/main/java/org/jetbrains/idea/maven/dom/MavenModelDocumentationProvider.java @@ -15,6 +15,7 @@ */ package org.jetbrains.idea.maven.dom; +import consulo.annotation.access.RequiredReadAction; import consulo.annotation.component.ExtensionImpl; import consulo.language.Language; import consulo.language.editor.documentation.LanguageDocumentationProvider; @@ -38,143 +39,125 @@ import java.util.List; @ExtensionImpl -public class MavenModelDocumentationProvider implements LanguageDocumentationProvider -{ - public String getQuickNavigateInfo(PsiElement element, PsiElement originalElement) - { - return getDoc(element, false); - } - - public List getUrlFor(PsiElement element, PsiElement originalElement) - { - element = getMavenElement(element); - if(element == null) - { - return null; - } - if(MavenDomUtil.isMavenProperty(element)) - { - return Collections.emptyList(); - } - - // todo hard-coded maven version - // todo add auto-opening the element's doc - //String name = ((PsiNamedElement)element).getName(); - return Collections.singletonList("http://maven.apache.org/ref/2.2.1/maven-model/maven.html"); - } - - public String generateDoc(PsiElement element, PsiElement originalElement) - { - return getDoc(element, true); - } - - @Nullable - private String getDoc(PsiElement element, boolean html) - { - return getMavenElementDescription(element, DescKind.TYPE_NAME_VALUE, html); - } - - public String getElementDescription(@Nonnull PsiElement element, @Nonnull ElementDescriptionLocation location) - { - return getMavenElementDescription(element, location instanceof UsageViewTypeLocation ? DescKind.TYPE : DescKind.NAME, false); - } - - @Nullable - private static String getMavenElementDescription(PsiElement e, DescKind kind, boolean html) - { - e = getMavenElement(e); - if(e == null) - { - return null; - } - - if(e instanceof FakePsiElement) - { - return ((FakePsiElement) e).getPresentableText(); - } - - boolean property = MavenDomUtil.isMavenProperty(e); - - String type = property ? "Property" : "Model Property"; - if(kind == DescKind.TYPE) - { - return type; - } - - String name = buildPropertyName(e, property); - if(kind == DescKind.NAME) - { - return name; - } - - if(kind == DescKind.TYPE_NAME_VALUE) - { - String br = html ? "
" : "\n "; - String[] bold = html ? new String[]{ - "", - "" - } : new String[]{ - "", - "" - }; - String valueSuffix = ""; - if(e instanceof XmlTag) - { - valueSuffix = ": " + bold[0] + ((XmlTag) e).getValue().getTrimmedText() + bold[1]; - } - return type + br + name + valueSuffix; - } - - MavenLog.LOG.error("unexpected desc kind: " + kind); - return null; - } - - private static String buildPropertyName(PsiElement e, boolean property) - { - if(property) - { - return DescriptiveNameUtil.getDescriptiveName(e); - } - - List path = new ArrayList(); - do - { - path.add(DescriptiveNameUtil.getDescriptiveName(e)); - } - while((e = PsiTreeUtil.getParentOfType(e, XmlTag.class)) != null); - Collections.reverse(path); - return StringUtil.join(path, "."); - } - - private static PsiElement getMavenElement(PsiElement e) - { - if(e instanceof MavenPsiElementWrapper) - { - e = ((MavenPsiElementWrapper) e).getWrappee(); - } - - if(!MavenDomUtil.isMavenFile(e)) - { - return null; - } - if(e instanceof PsiFile) - { - return null; - } - return e; - } - - @Nonnull - @Override - public Language getLanguage() - { - return XMLLanguage.INSTANCE; - } - - private enum DescKind - { - TYPE, - NAME, - TYPE_NAME_VALUE - } +public class MavenModelDocumentationProvider implements LanguageDocumentationProvider { + @Override + @RequiredReadAction + public String getQuickNavigateInfo(PsiElement element, PsiElement originalElement) { + return getDoc(element, false); + } + + @Override + @RequiredReadAction + public List getUrlFor(PsiElement element, PsiElement originalElement) { + element = getMavenElement(element); + if (element == null) { + return null; + } + if (MavenDomUtil.isMavenProperty(element)) { + return Collections.emptyList(); + } + + // todo hard-coded maven version + // todo add auto-opening the element's doc + //String name = ((PsiNamedElement)element).getName(); + return Collections.singletonList("http://maven.apache.org/ref/2.2.1/maven-model/maven.html"); + } + + @Override + @RequiredReadAction + public String generateDoc(PsiElement element, PsiElement originalElement) { + return getDoc(element, true); + } + + @Nullable + @RequiredReadAction + private String getDoc(PsiElement element, boolean html) { + return getMavenElementDescription(element, DescKind.TYPE_NAME_VALUE, html); + } + + @RequiredReadAction + public String getElementDescription(@Nonnull PsiElement element, @Nonnull ElementDescriptionLocation location) { + return getMavenElementDescription(element, location instanceof UsageViewTypeLocation ? DescKind.TYPE : DescKind.NAME, false); + } + + @Nullable + @RequiredReadAction + private static String getMavenElementDescription(PsiElement e, DescKind kind, boolean html) { + e = getMavenElement(e); + if (e == null) { + return null; + } + + if (e instanceof FakePsiElement fakePsiElement) { + return fakePsiElement.getPresentableText(); + } + + boolean property = MavenDomUtil.isMavenProperty(e); + + String type = property ? "Property" : "Model Property"; + if (kind == DescKind.TYPE) { + return type; + } + + String name = buildPropertyName(e, property); + if (kind == DescKind.NAME) { + return name; + } + + if (kind == DescKind.TYPE_NAME_VALUE) { + String br = html ? "
" : "\n "; + String[] bold = html ? new String[]{ + "", + "" + } : new String[]{ + "", + "" + }; + String valueSuffix = ""; + if (e instanceof XmlTag tag) { + valueSuffix = ": " + bold[0] + tag.getValue().getTrimmedText() + bold[1]; + } + return type + br + name + valueSuffix; + } + + MavenLog.LOG.error("unexpected desc kind: " + kind); + return null; + } + + @RequiredReadAction + private static String buildPropertyName(PsiElement e, boolean property) { + if (property) { + return DescriptiveNameUtil.getDescriptiveName(e); + } + + List path = new ArrayList<>(); + do { + path.add(DescriptiveNameUtil.getDescriptiveName(e)); + e = PsiTreeUtil.getParentOfType(e, XmlTag.class); + } + while (e != null); + Collections.reverse(path); + return StringUtil.join(path, "."); + } + + @RequiredReadAction + private static PsiElement getMavenElement(PsiElement e) { + if (e instanceof MavenPsiElementWrapper wrapper) { + e = wrapper.getWrappee(); + } + + return !MavenDomUtil.isMavenFile(e) || e instanceof PsiFile ? null : e; + } + + @Nonnull + @Override + public Language getLanguage() { + return XMLLanguage.INSTANCE; + } + + private enum DescKind { + TYPE, + NAME, + TYPE_NAME_VALUE + } } diff --git a/plugin/src/main/java/org/jetbrains/idea/maven/dom/MavenPluginConfigurationDomExtender.java b/plugin/src/main/java/org/jetbrains/idea/maven/dom/MavenPluginConfigurationDomExtender.java index a89f74de..f2760cc7 100644 --- a/plugin/src/main/java/org/jetbrains/idea/maven/dom/MavenPluginConfigurationDomExtender.java +++ b/plugin/src/main/java/org/jetbrains/idea/maven/dom/MavenPluginConfigurationDomExtender.java @@ -15,9 +15,9 @@ */ package org.jetbrains.idea.maven.dom; -import com.intellij.java.language.psi.CommonClassNames; import consulo.annotation.component.ExtensionImpl; import consulo.application.util.matcher.NameUtil; +import consulo.java.language.module.util.JavaClassNames; import consulo.language.psi.PsiElement; import consulo.util.dataholder.Key; import consulo.util.lang.StringUtil; @@ -45,325 +45,270 @@ import java.util.*; @ExtensionImpl -public class MavenPluginConfigurationDomExtender extends DomExtender -{ - public static final Key PLUGIN_PARAMETER_KEY = Key.create("MavenPluginConfigurationDomExtender.PLUGIN_PARAMETER_KEY"); - - private static final Set COLLECTIONS_TYPE_NAMES = Set.of("java.util.Collection", CommonClassNames.JAVA_UTIL_SET, - CommonClassNames.JAVA_UTIL_LIST, - "java.util.ArrayList", "java.util.HashSet", - "java.util.LinkedList"); - - @Nonnull - @Override - public Class getElementClass() - { - return MavenDomConfiguration.class; - } - - @Override - public void registerExtensions(@Nonnull MavenDomConfiguration config, @Nonnull DomExtensionsRegistrar r) - { - MavenDomPluginModel pluginModel = MavenPluginDomUtil.getMavenPluginModel(config); - if(pluginModel == null) - { - r.registerCustomChildrenExtension(MavenDomConfigurationParameter.class); - return; - } - - boolean isInPluginManagement = isInPluginManagement(config); - - for(ParameterData each : collectParameters(pluginModel, config)) - { - registerPluginParameter(isInPluginManagement, r, each); - } - } - - private static boolean isInPluginManagement(MavenDomConfiguration pluginNode) - { - XmlElement xmlElement = pluginNode.getXmlElement(); - if(xmlElement == null) - { - return false; - } - - PsiElement pluginTag = xmlElement.getParent(); - if(pluginTag == null) - { - return false; - } - - PsiElement pluginsTag = pluginTag.getParent(); - if(pluginsTag == null) - { - return false; - } - - PsiElement pluginManagementTag = pluginsTag.getParent(); - - return pluginManagementTag instanceof XmlTag && "pluginManagement".equals(((XmlTag) pluginManagementTag).getName()); - } - - private static Collection collectParameters(MavenDomPluginModel pluginModel, MavenDomConfiguration config) - { - List selectedGoals = null; - - MavenDomPluginExecution executionElement = config.getParentOfType(MavenDomPluginExecution.class, false); - if(executionElement != null) - { - selectedGoals = new ArrayList(); - - String id = executionElement.getId().getStringValue(); - String defaultPrefix = "default-"; - if(id != null && id.startsWith(defaultPrefix)) - { - String goal = id.substring(defaultPrefix.length()); - if(!StringUtil.isEmptyOrSpaces(goal)) - { - selectedGoals.add(goal); - } - } - - for(GenericDomValue goal : executionElement.getGoals().getGoals()) - { - selectedGoals.add(goal.getStringValue()); - } - } - - Map namesWithParameters = new HashMap(); - - for(MavenDomMojo eachMojo : pluginModel.getMojos().getMojos()) - { - String goal = eachMojo.getGoal().getStringValue(); - if(goal == null) - { - continue; - } - - if(selectedGoals == null || selectedGoals.contains(goal)) - { - for(MavenDomParameter eachParameter : eachMojo.getParameters().getParameters()) - { - if(eachParameter.getEditable().getValue() == Boolean.FALSE) - { - continue; - } - - String name = eachParameter.getName().getStringValue(); - if(name == null) - { - continue; - } - - ParameterData data = new ParameterData(eachParameter); - fillParameterData(name, data, eachMojo); - - ParameterData oldParameter = namesWithParameters.get(name); - if(oldParameter == null || hasMorePriority(data, oldParameter, executionElement != null)) - { - namesWithParameters.put(name, data); - } - } - } - } - - return namesWithParameters.values(); - } - - private static boolean hasMorePriority(ParameterData d1, ParameterData d2, boolean isForExecutionSection) - { - if(!isForExecutionSection) - { - if(StringUtil.isEmptyOrSpaces(d1.getMojo().getPhase().getStringValue())) - { - return false; - } - - if(StringUtil.isEmptyOrSpaces(d2.getMojo().getPhase().getStringValue())) - { - return true; - } - } - - return d1.getRequiringLevel() > d2.getRequiringLevel(); - } - - private static void fillParameterData(String name, ParameterData data, MavenDomMojo mojo) - { - XmlTag config = mojo.getConfiguration().getXmlTag(); - if(config == null) - { - return; - } - - for(XmlTag each : config.getSubTags()) - { - if(!name.equals(each.getName())) - { - continue; - } - data.defaultValue = each.getAttributeValue("default-value"); - data.expression = each.getValue().getTrimmedText(); - } - } - - private static void registerPluginParameter(boolean isInPluginManagement, DomExtensionsRegistrar r, final ParameterData parameter) - { - String paramName = parameter.parameter.getName().getStringValue(); - String alias = parameter.parameter.getAlias().getStringValue(); - - registerPluginParameter(isInPluginManagement, r, parameter, paramName); - if(alias != null) - { - registerPluginParameter(isInPluginManagement, r, parameter, alias); - } - } - - private static void registerPluginParameter(boolean isInPluginManagement, DomExtensionsRegistrar r, final ParameterData data, final String parameterName) - { - DomExtension e = r.registerFixedNumberChildExtension(new XmlName(parameterName), MavenDomConfigurationParameter.class); - - if(isCollection(data.parameter)) - { - e.addExtender(new DomExtender() - { - @Nonnull - @Override - public Class getElementClass() - { - return DomElement.class; - } - - public void registerExtensions(@Nonnull DomElement domElement, @Nonnull DomExtensionsRegistrar registrar) - { - for(String each : collectPossibleNameForCollectionParameter(parameterName)) - { - DomExtension inner = registrar.registerCollectionChildrenExtension(new XmlName(each), MavenDomConfigurationParameter.class); - inner.setDeclaringElement(data.parameter); - } - } - }); - } - else - { - addValueConverter(e, data.parameter); - if(!isInPluginManagement) - { - addRequiredAnnotation(e, data); - } - } - - e.setDeclaringElement(data.parameter); - - data.parameter.getXmlElement().putUserData(PLUGIN_PARAMETER_KEY, data); - } - - private static void addValueConverter(DomExtension e, MavenDomParameter parameter) - { - String type = parameter.getType().getStringValue(); - if(!StringUtil.isEmptyOrSpaces(type)) - { - e.setConverter(new MavenPluginCustomParameterValueConverter(type), MavenDomConvertersRegistry.getInstance().isSoft(type)); - } - } - - private static void addRequiredAnnotation(DomExtension e, final ParameterData data) - { - if(Boolean.parseBoolean(data.parameter.getRequired().getStringValue()) - && StringUtil.isEmptyOrSpaces(data.defaultValue) - && StringUtil.isEmptyOrSpaces(data.expression)) - { - e.addCustomAnnotation(new Required() - { - @Override - public boolean value() - { - return true; - } - - @Override - public boolean nonEmpty() - { - return false; - } - - @Override - public boolean identifier() - { - return false; - } - - public Class annotationType() - { - return Required.class; - } - }); - } - } - - public static List collectPossibleNameForCollectionParameter(String parameterName) - { - String singularName = StringUtil.unpluralize(parameterName); - if(singularName == null) - { - singularName = parameterName; - } - - List result = new ArrayList(); - String[] parts = NameUtil.splitNameIntoWords(singularName); - for(int i = 0; i < parts.length; i++) - { - result.add(StringUtil.decapitalize(StringUtil.join(parts, i, parts.length, ""))); - } - return result; - } - - private static boolean isCollection(MavenDomParameter parameter) - { - String type = parameter.getType().getStringValue(); - if(type == null) - { - return false; - } - - return type.endsWith("[]") || COLLECTIONS_TYPE_NAMES.contains(type); - } - - public static class ParameterData - { - public final MavenDomParameter parameter; - public - @Nullable - String defaultValue; - public - @Nullable - String expression; - - private ParameterData(MavenDomParameter parameter) - { - this.parameter = parameter; - } - - @Nonnull - public MavenDomMojo getMojo() - { - return (MavenDomMojo) parameter.getParent().getParent(); - } - - public int getRequiringLevel() - { - if(!Boolean.parseBoolean(parameter.getRequired().getStringValue())) - { - return 0; - } - - if(!StringUtil.isEmptyOrSpaces(defaultValue) || !StringUtil.isEmptyOrSpaces(expression)) - { - return 1; - } - - return 2; - } - } - +public class MavenPluginConfigurationDomExtender extends DomExtender { + public static final Key PLUGIN_PARAMETER_KEY = Key.create("MavenPluginConfigurationDomExtender.PLUGIN_PARAMETER_KEY"); + + private static final Set COLLECTIONS_TYPE_NAMES = Set.of( + "java.util.Collection", + JavaClassNames.JAVA_UTIL_SET, + JavaClassNames.JAVA_UTIL_LIST, + "java.util.ArrayList", + "java.util.HashSet", + "java.util.LinkedList" + ); + + @Nonnull + @Override + public Class getElementClass() { + return MavenDomConfiguration.class; + } + + @Override + public void registerExtensions(@Nonnull MavenDomConfiguration config, @Nonnull DomExtensionsRegistrar r) { + MavenDomPluginModel pluginModel = MavenPluginDomUtil.getMavenPluginModel(config); + if (pluginModel == null) { + r.registerCustomChildrenExtension(MavenDomConfigurationParameter.class); + return; + } + + boolean isInPluginManagement = isInPluginManagement(config); + + for (ParameterData each : collectParameters(pluginModel, config)) { + registerPluginParameter(isInPluginManagement, r, each); + } + } + + private static boolean isInPluginManagement(MavenDomConfiguration pluginNode) { + XmlElement xmlElement = pluginNode.getXmlElement(); + if (xmlElement == null) { + return false; + } + + PsiElement pluginTag = xmlElement.getParent(); + if (pluginTag == null) { + return false; + } + + PsiElement pluginsTag = pluginTag.getParent(); + return pluginsTag != null + && pluginsTag.getParent() instanceof XmlTag pluginManagementTag + && "pluginManagement".equals(pluginManagementTag.getName()); + + } + + private static Collection collectParameters(MavenDomPluginModel pluginModel, MavenDomConfiguration config) { + List selectedGoals = null; + + MavenDomPluginExecution executionElement = config.getParentOfType(MavenDomPluginExecution.class, false); + if (executionElement != null) { + selectedGoals = new ArrayList<>(); + + String id = executionElement.getId().getStringValue(); + String defaultPrefix = "default-"; + if (id != null && id.startsWith(defaultPrefix)) { + String goal = id.substring(defaultPrefix.length()); + if (!StringUtil.isEmptyOrSpaces(goal)) { + selectedGoals.add(goal); + } + } + + for (GenericDomValue goal : executionElement.getGoals().getGoals()) { + selectedGoals.add(goal.getStringValue()); + } + } + + Map namesWithParameters = new HashMap<>(); + + for (MavenDomMojo eachMojo : pluginModel.getMojos().getMojos()) { + String goal = eachMojo.getGoal().getStringValue(); + if (goal == null) { + continue; + } + + if (selectedGoals == null || selectedGoals.contains(goal)) { + for (MavenDomParameter eachParameter : eachMojo.getParameters().getParameters()) { + if (eachParameter.getEditable().getValue() == Boolean.FALSE) { + continue; + } + + String name = eachParameter.getName().getStringValue(); + if (name == null) { + continue; + } + + ParameterData data = new ParameterData(eachParameter); + fillParameterData(name, data, eachMojo); + + ParameterData oldParameter = namesWithParameters.get(name); + if (oldParameter == null || hasMorePriority(data, oldParameter, executionElement != null)) { + namesWithParameters.put(name, data); + } + } + } + } + + return namesWithParameters.values(); + } + + private static boolean hasMorePriority(ParameterData d1, ParameterData d2, boolean isForExecutionSection) { + if (!isForExecutionSection) { + if (StringUtil.isEmptyOrSpaces(d1.getMojo().getPhase().getStringValue())) { + return false; + } + + if (StringUtil.isEmptyOrSpaces(d2.getMojo().getPhase().getStringValue())) { + return true; + } + } + + return d1.getRequiringLevel() > d2.getRequiringLevel(); + } + + private static void fillParameterData(String name, ParameterData data, MavenDomMojo mojo) { + XmlTag config = mojo.getConfiguration().getXmlTag(); + if (config == null) { + return; + } + + for (XmlTag each : config.getSubTags()) { + if (!name.equals(each.getName())) { + continue; + } + data.defaultValue = each.getAttributeValue("default-value"); + data.expression = each.getValue().getTrimmedText(); + } + } + + private static void registerPluginParameter(boolean isInPluginManagement, DomExtensionsRegistrar r, final ParameterData parameter) { + String paramName = parameter.parameter.getName().getStringValue(); + String alias = parameter.parameter.getAlias().getStringValue(); + + registerPluginParameter(isInPluginManagement, r, parameter, paramName); + if (alias != null) { + registerPluginParameter(isInPluginManagement, r, parameter, alias); + } + } + + private static void registerPluginParameter( + boolean isInPluginManagement, + DomExtensionsRegistrar r, + final ParameterData data, + final String parameterName + ) { + DomExtension e = r.registerFixedNumberChildExtension(new XmlName(parameterName), MavenDomConfigurationParameter.class); + + if (isCollection(data.parameter)) { + e.addExtender(new DomExtender() { + @Nonnull + @Override + public Class getElementClass() { + return DomElement.class; + } + + @Override + public void registerExtensions(@Nonnull DomElement domElement, @Nonnull DomExtensionsRegistrar registrar) { + for (String each : collectPossibleNameForCollectionParameter(parameterName)) { + DomExtension inner = + registrar.registerCollectionChildrenExtension(new XmlName(each), MavenDomConfigurationParameter.class); + inner.setDeclaringElement(data.parameter); + } + } + }); + } + else { + addValueConverter(e, data.parameter); + if (!isInPluginManagement) { + addRequiredAnnotation(e, data); + } + } + + e.setDeclaringElement(data.parameter); + + data.parameter.getXmlElement().putUserData(PLUGIN_PARAMETER_KEY, data); + } + + private static void addValueConverter(DomExtension e, MavenDomParameter parameter) { + String type = parameter.getType().getStringValue(); + if (!StringUtil.isEmptyOrSpaces(type)) { + e.setConverter(new MavenPluginCustomParameterValueConverter(type), MavenDomConvertersRegistry.getInstance().isSoft(type)); + } + } + + private static void addRequiredAnnotation(DomExtension e, final ParameterData data) { + if (Boolean.parseBoolean(data.parameter.getRequired().getStringValue()) + && StringUtil.isEmptyOrSpaces(data.defaultValue) + && StringUtil.isEmptyOrSpaces(data.expression)) { + e.addCustomAnnotation(new Required() { + @Override + public boolean value() { + return true; + } + + @Override + public boolean nonEmpty() { + return false; + } + + @Override + public boolean identifier() { + return false; + } + + @Override + public Class annotationType() { + return Required.class; + } + }); + } + } + + public static List collectPossibleNameForCollectionParameter(String parameterName) { + String singularName = StringUtil.unpluralize(parameterName); + if (singularName == null) { + singularName = parameterName; + } + + List result = new ArrayList<>(); + String[] parts = NameUtil.splitNameIntoWords(singularName); + for (int i = 0; i < parts.length; i++) { + result.add(StringUtil.decapitalize(StringUtil.join(parts, i, parts.length, ""))); + } + return result; + } + + private static boolean isCollection(MavenDomParameter parameter) { + String type = parameter.getType().getStringValue(); + return type != null && (type.endsWith("[]") || COLLECTIONS_TYPE_NAMES.contains(type)); + } + + public static class ParameterData { + public final MavenDomParameter parameter; + public + @Nullable + String defaultValue; + public + @Nullable + String expression; + + private ParameterData(MavenDomParameter parameter) { + this.parameter = parameter; + } + + @Nonnull + public MavenDomMojo getMojo() { + return (MavenDomMojo)parameter.getParent().getParent(); + } + + public int getRequiringLevel() { + if (!Boolean.parseBoolean(parameter.getRequired().getStringValue())) { + return 0; + } + + if (!StringUtil.isEmptyOrSpaces(defaultValue) || !StringUtil.isEmptyOrSpaces(expression)) { + return 1; + } + + return 2; + } + } } diff --git a/plugin/src/main/java/org/jetbrains/idea/maven/dom/MavenPluginConfigurationParameterDomExtender.java b/plugin/src/main/java/org/jetbrains/idea/maven/dom/MavenPluginConfigurationParameterDomExtender.java index 4d2b0ca2..a3ad97d2 100644 --- a/plugin/src/main/java/org/jetbrains/idea/maven/dom/MavenPluginConfigurationParameterDomExtender.java +++ b/plugin/src/main/java/org/jetbrains/idea/maven/dom/MavenPluginConfigurationParameterDomExtender.java @@ -26,26 +26,21 @@ import javax.annotation.Nonnull; @ExtensionImpl -public class MavenPluginConfigurationParameterDomExtender extends DomExtender -{ - @Nonnull - @Override - public Class getElementClass() - { - return MavenDomConfigurationParameter.class; - } +public class MavenPluginConfigurationParameterDomExtender extends DomExtender { + @Nonnull + @Override + public Class getElementClass() { + return MavenDomConfigurationParameter.class; + } - @Override - public void registerExtensions(@Nonnull MavenDomConfigurationParameter param, @Nonnull DomExtensionsRegistrar r) - { - for(XmlAttribute each : param.getXmlTag().getAttributes()) - { - String name = each.getName(); - if(CompletionUtilCore.DUMMY_IDENTIFIER_TRIMMED.equals(name)) - { - continue; - } - r.registerGenericAttributeValueChildExtension(new XmlName(name), String.class); - } - } + @Override + public void registerExtensions(@Nonnull MavenDomConfigurationParameter param, @Nonnull DomExtensionsRegistrar r) { + for (XmlAttribute each : param.getXmlTag().getAttributes()) { + String name = each.getName(); + if (CompletionUtilCore.DUMMY_IDENTIFIER_TRIMMED.equals(name)) { + continue; + } + r.registerGenericAttributeValueChildExtension(new XmlName(name), String.class); + } + } } diff --git a/plugin/src/main/java/org/jetbrains/idea/maven/dom/MavenPluginDomUtil.java b/plugin/src/main/java/org/jetbrains/idea/maven/dom/MavenPluginDomUtil.java index 8f098d0f..328f7967 100644 --- a/plugin/src/main/java/org/jetbrains/idea/maven/dom/MavenPluginDomUtil.java +++ b/plugin/src/main/java/org/jetbrains/idea/maven/dom/MavenPluginDomUtil.java @@ -15,6 +15,7 @@ */ package org.jetbrains.idea.maven.dom; +import consulo.annotation.access.RequiredReadAction; import consulo.language.psi.PsiFile; import consulo.maven.rt.server.common.model.MavenId; import consulo.maven.rt.server.common.model.MavenPlugin; @@ -36,122 +37,106 @@ import javax.annotation.Nullable; import java.io.File; -public class MavenPluginDomUtil -{ - @Nullable - public static MavenProject findMavenProject(@Nonnull DomElement domElement) - { - XmlElement xmlElement = domElement.getXmlElement(); - if(xmlElement == null) - { - return null; - } - PsiFile psiFile = xmlElement.getContainingFile(); - if(psiFile == null) - { - return null; - } - VirtualFile file = psiFile.getVirtualFile(); - if(file == null) - { - return null; - } - return MavenProjectsManager.getInstance(psiFile.getProject()).findProject(file); - } - - @Nullable - public static MavenDomPluginModel getMavenPluginModel(DomElement element) - { - Project project = element.getManager().getProject(); - - MavenDomPlugin pluginElement = element.getParentOfType(MavenDomPlugin.class, false); - if(pluginElement == null) - { - return null; - } - - String groupId = pluginElement.getGroupId().getStringValue(); - String artifactId = pluginElement.getArtifactId().getStringValue(); - String version = pluginElement.getVersion().getStringValue(); - if(StringUtil.isEmpty(version)) - { - MavenProject mavenProject = findMavenProject(element); - if(mavenProject != null) - { - for(MavenPlugin plugin : mavenProject.getPlugins()) - { - if(MavenArtifactUtil.isPluginIdEquals(groupId, artifactId, plugin.getGroupId(), plugin.getArtifactId())) - { - MavenId pluginMavenId = plugin.getMavenId(); - version = pluginMavenId.getVersion(); - break; - } - } - } - } - return getMavenPluginModel(project, groupId, artifactId, version); - } - - @Nullable - public static MavenDomPluginModel getMavenPluginModel(Project project, String groupId, String artifactId, String version) - { - VirtualFile pluginXmlFile = getPluginXmlFile(project, groupId, artifactId, version); - if(pluginXmlFile == null) - { - return null; - } - - return MavenDomUtil.getMavenDomModel(project, pluginXmlFile, MavenDomPluginModel.class); - } - - public static boolean isPlugin(@Nonnull MavenDomConfiguration configuration, @Nullable String groupId, @Nonnull String artifactId) - { - MavenDomPlugin domPlugin = configuration.getParentOfType(MavenDomPlugin.class, true); - if(domPlugin == null) - { - return false; - } - - return isPlugin(domPlugin, groupId, artifactId); - } - - public static boolean isPlugin(@Nonnull MavenDomPlugin plugin, @Nullable String groupId, @Nonnull String artifactId) - { - if(!artifactId.equals(plugin.getArtifactId().getStringValue())) - { - return false; - } - - String pluginGroupId = plugin.getGroupId().getStringValue(); - - if(groupId == null) - { - return pluginGroupId == null || (pluginGroupId.equals("org.apache.maven.plugins") || pluginGroupId.equals("org.codehaus.mojo")); - } - - if(pluginGroupId == null && (groupId.equals("org.apache.maven.plugins") || groupId.equals("org.codehaus.mojo"))) - { - return true; - } - - return groupId.equals(pluginGroupId); - } - - @Nullable - private static VirtualFile getPluginXmlFile(Project project, String groupId, String artifactId, String version) - { - File file = MavenArtifactUtil.getArtifactFile(MavenProjectsManager.getInstance(project).getLocalRepository(), groupId, artifactId, version, "jar"); - VirtualFile pluginFile = LocalFileSystem.getInstance().findFileByIoFile(file); - if(pluginFile == null) - { - return null; - } - - VirtualFile pluginJarRoot = ArchiveVfsUtil.getJarRootForLocalFile(pluginFile); - if(pluginJarRoot == null) - { - return null; - } - return pluginJarRoot.findFileByRelativePath(MavenArtifactUtil.MAVEN_PLUGIN_DESCRIPTOR); - } +public class MavenPluginDomUtil { + @Nullable + public static MavenProject findMavenProject(@Nonnull DomElement domElement) { + XmlElement xmlElement = domElement.getXmlElement(); + if (xmlElement == null) { + return null; + } + PsiFile psiFile = xmlElement.getContainingFile(); + if (psiFile == null) { + return null; + } + VirtualFile file = psiFile.getVirtualFile(); + if (file == null) { + return null; + } + return MavenProjectsManager.getInstance(psiFile.getProject()).findProject(file); + } + + @Nullable + @RequiredReadAction + public static MavenDomPluginModel getMavenPluginModel(DomElement element) { + Project project = element.getManager().getProject(); + + MavenDomPlugin pluginElement = element.getParentOfType(MavenDomPlugin.class, false); + if (pluginElement == null) { + return null; + } + + String groupId = pluginElement.getGroupId().getStringValue(); + String artifactId = pluginElement.getArtifactId().getStringValue(); + String version = pluginElement.getVersion().getStringValue(); + if (StringUtil.isEmpty(version)) { + MavenProject mavenProject = findMavenProject(element); + if (mavenProject != null) { + for (MavenPlugin plugin : mavenProject.getPlugins()) { + if (MavenArtifactUtil.isPluginIdEquals(groupId, artifactId, plugin.getGroupId(), plugin.getArtifactId())) { + MavenId pluginMavenId = plugin.getMavenId(); + version = pluginMavenId.getVersion(); + break; + } + } + } + } + return getMavenPluginModel(project, groupId, artifactId, version); + } + + @Nullable + @RequiredReadAction + public static MavenDomPluginModel getMavenPluginModel(Project project, String groupId, String artifactId, String version) { + VirtualFile pluginXmlFile = getPluginXmlFile(project, groupId, artifactId, version); + if (pluginXmlFile == null) { + return null; + } + + return MavenDomUtil.getMavenDomModel(project, pluginXmlFile, MavenDomPluginModel.class); + } + + public static boolean isPlugin(@Nonnull MavenDomConfiguration configuration, @Nullable String groupId, @Nonnull String artifactId) { + MavenDomPlugin domPlugin = configuration.getParentOfType(MavenDomPlugin.class, true); + return domPlugin != null && isPlugin(domPlugin, groupId, artifactId); + } + + public static boolean isPlugin(@Nonnull MavenDomPlugin plugin, @Nullable String groupId, @Nonnull String artifactId) { + if (!artifactId.equals(plugin.getArtifactId().getStringValue())) { + return false; + } + + String pluginGroupId = plugin.getGroupId().getStringValue(); + + if (groupId == null) { + return pluginGroupId == null + || pluginGroupId.equals("org.apache.maven.plugins") + || pluginGroupId.equals("org.codehaus.mojo"); + } + + if (pluginGroupId == null && (groupId.equals("org.apache.maven.plugins") || groupId.equals("org.codehaus.mojo"))) { + return true; + } + + return groupId.equals(pluginGroupId); + } + + @Nullable + private static VirtualFile getPluginXmlFile(Project project, String groupId, String artifactId, String version) { + File file = MavenArtifactUtil.getArtifactFile( + MavenProjectsManager.getInstance(project).getLocalRepository(), + groupId, + artifactId, + version, + "jar" + ); + VirtualFile pluginFile = LocalFileSystem.getInstance().findFileByIoFile(file); + if (pluginFile == null) { + return null; + } + + VirtualFile pluginJarRoot = ArchiveVfsUtil.getJarRootForLocalFile(pluginFile); + if (pluginJarRoot == null) { + return null; + } + return pluginJarRoot.findFileByRelativePath(MavenArtifactUtil.MAVEN_PLUGIN_DESCRIPTOR); + } } diff --git a/plugin/src/main/java/org/jetbrains/idea/maven/dom/MavenPluginModelDocumentationProvider.java b/plugin/src/main/java/org/jetbrains/idea/maven/dom/MavenPluginModelDocumentationProvider.java index 8171205e..e7798876 100644 --- a/plugin/src/main/java/org/jetbrains/idea/maven/dom/MavenPluginModelDocumentationProvider.java +++ b/plugin/src/main/java/org/jetbrains/idea/maven/dom/MavenPluginModelDocumentationProvider.java @@ -24,69 +24,48 @@ import javax.annotation.Nonnull; @ExtensionImpl -public class MavenPluginModelDocumentationProvider implements LanguageDocumentationProvider -{ - @Override - public String getQuickNavigateInfo(PsiElement element, PsiElement originalElement) - { - return getDocForMavenPluginParameter(element, false); - } +public class MavenPluginModelDocumentationProvider implements LanguageDocumentationProvider { + @Override + public String getQuickNavigateInfo(PsiElement element, PsiElement originalElement) { + return getDocForMavenPluginParameter(element, false); + } - @Override - public String generateDoc(PsiElement element, PsiElement originalElement) - { - return getDocForMavenPluginParameter(element, true); - } + @Override + public String generateDoc(PsiElement element, PsiElement originalElement) { + return getDocForMavenPluginParameter(element, true); + } - private String getDocForMavenPluginParameter(PsiElement element, boolean html) - { - MavenPluginConfigurationDomExtender.ParameterData p = element.getUserData(MavenPluginConfigurationDomExtender.PLUGIN_PARAMETER_KEY); - if(p == null) - { - return null; - } + private String getDocForMavenPluginParameter(PsiElement element, boolean html) { + MavenPluginConfigurationDomExtender.ParameterData p = element.getUserData(MavenPluginConfigurationDomExtender.PLUGIN_PARAMETER_KEY); + if (p == null) { + return null; + } - String[] ss = html ? new String[]{ - "
", - "", - "", - "", - "" - } - : new String[]{ - "\n ", - "", - "", - "", - "" - }; + String[] ss = html + ? new String[]{"
", "", "", "", ""} + : new String[]{"\n ", "", "", "", ""}; - String text = ""; - if(html) - { - text += "Type: " + ss[1] + p.parameter.getType().getStringValue() + ss[2] + ss[0]; - if(p.defaultValue != null) - { - text += "Default Value: " + ss[1] + p.defaultValue + ss[2] + ss[0]; - } - if(p.expression != null) - { - text += "Expression: " + ss[1] + p.expression + ss[2] + ss[0]; - } - if(p.parameter.getRequired().getValue() == Boolean.TRUE) - { - text += ss[1] + "Required" + ss[2] + ss[0]; - } - text += ss[0]; - } - text += ss[3] + p.parameter.getDescription().getStringValue() + ss[4]; - return text; - } + String text = ""; + if (html) { + text += "Type: " + ss[1] + p.parameter.getType().getStringValue() + ss[2] + ss[0]; + if (p.defaultValue != null) { + text += "Default Value: " + ss[1] + p.defaultValue + ss[2] + ss[0]; + } + if (p.expression != null) { + text += "Expression: " + ss[1] + p.expression + ss[2] + ss[0]; + } + if (p.parameter.getRequired().getValue() == Boolean.TRUE) { + text += ss[1] + "Required" + ss[2] + ss[0]; + } + text += ss[0]; + } + text += ss[3] + p.parameter.getDescription().getStringValue() + ss[4]; + return text; + } - @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/dom/MavenPomXmlDocumentationProvider.java b/plugin/src/main/java/org/jetbrains/idea/maven/dom/MavenPomXmlDocumentationProvider.java index 5f368f5d..71091190 100644 --- a/plugin/src/main/java/org/jetbrains/idea/maven/dom/MavenPomXmlDocumentationProvider.java +++ b/plugin/src/main/java/org/jetbrains/idea/maven/dom/MavenPomXmlDocumentationProvider.java @@ -16,6 +16,7 @@ package org.jetbrains.idea.maven.dom; import com.intellij.xml.util.documentation.XmlDocumentationProvider; +import consulo.annotation.access.RequiredReadAction; import consulo.annotation.component.ExtensionImpl; import consulo.language.Language; import consulo.language.editor.documentation.DocumentationProvider; @@ -34,86 +35,60 @@ * @author Sergey Evdokimov */ @ExtensionImpl -public class MavenPomXmlDocumentationProvider implements LanguageDocumentationProvider -{ - private final DocumentationProvider myDelegate = new XmlDocumentationProvider() - { - @Override - protected String generateDoc(String str, String name, String typeName, String version) - { - if(str != null) - { - str = StringUtil.unescapeXml(str); - } - - return super.generateDoc(str, name, typeName, version); - } - }; - - - private static boolean isFromPomXml(PsiElement element) - { - if(element == null) - { - return false; - } - - PsiFile containingFile = element.getContainingFile(); - return containingFile != null && containingFile.getName().equals("maven-4.0.0.xsd"); - } - - @Nullable - @Override - public String getQuickNavigateInfo(PsiElement element, PsiElement originalElement) - { - if(!isFromPomXml(element)) - { - return null; - } - - return myDelegate.getQuickNavigateInfo(element, originalElement); - } - - @Nullable - @Override - public List getUrlFor(PsiElement element, PsiElement originalElement) - { - if(!isFromPomXml(element)) - { - return null; - } - - return myDelegate.getUrlFor(element, originalElement); - } - - @Nullable - @Override - public String generateDoc(PsiElement element, @Nullable PsiElement originalElement) - { - if(!isFromPomXml(element)) - { - return null; - } - - return myDelegate.generateDoc(element, originalElement); - } - - @Nullable - @Override - public PsiElement getDocumentationElementForLookupItem(PsiManager psiManager, Object object, PsiElement element) - { - if(!isFromPomXml(element)) - { - return null; - } - - return myDelegate.getDocumentationElementForLookupItem(psiManager, object, element); - } - - @Nonnull - @Override - public Language getLanguage() - { - return XMLLanguage.INSTANCE; - } +public class MavenPomXmlDocumentationProvider implements LanguageDocumentationProvider { + private final DocumentationProvider myDelegate = new XmlDocumentationProvider() { + @Override + protected String generateDoc(String str, String name, String typeName, String version) { + if (str != null) { + str = StringUtil.unescapeXml(str); + } + + return super.generateDoc(str, name, typeName, version); + } + }; + + + @RequiredReadAction + private static boolean isFromPomXml(PsiElement element) { + if (element == null) { + return false; + } + + PsiFile containingFile = element.getContainingFile(); + return containingFile != null && containingFile.getName().equals("maven-4.0.0.xsd"); + } + + @Nullable + @Override + @RequiredReadAction + public String getQuickNavigateInfo(PsiElement element, PsiElement originalElement) { + return isFromPomXml(element) ? myDelegate.getQuickNavigateInfo(element, originalElement) : null; + } + + @Nullable + @Override + @RequiredReadAction + public List getUrlFor(PsiElement element, PsiElement originalElement) { + return isFromPomXml(element) ? myDelegate.getUrlFor(element, originalElement) : null; + } + + @Nullable + @Override + @RequiredReadAction + public String generateDoc(PsiElement element, @Nullable PsiElement originalElement) { + return isFromPomXml(element) ? myDelegate.generateDoc(element, originalElement) : null; + } + + @Nullable + @Override + @RequiredReadAction + public PsiElement getDocumentationElementForLookupItem(PsiManager psiManager, Object object, PsiElement element) { + return isFromPomXml(element) ? myDelegate.getDocumentationElementForLookupItem(psiManager, object, element) : null; + } + + @Nonnull + @Override + public Language getLanguage() { + return XMLLanguage.INSTANCE; + } } diff --git a/plugin/src/main/java/org/jetbrains/idea/maven/dom/MavenPropertyResolver.java b/plugin/src/main/java/org/jetbrains/idea/maven/dom/MavenPropertyResolver.java index dbaa4022..3f842f5e 100644 --- a/plugin/src/main/java/org/jetbrains/idea/maven/dom/MavenPropertyResolver.java +++ b/plugin/src/main/java/org/jetbrains/idea/maven/dom/MavenPropertyResolver.java @@ -44,294 +44,286 @@ import java.util.regex.Matcher; import java.util.regex.Pattern; -public class MavenPropertyResolver -{ - public static final Pattern PATTERN = Pattern.compile("\\$\\{(.+?)\\}|@(.+?)@"); - - public static void doFilterText(Module module, String text, Properties additionalProperties, String propertyEscapeString, Appendable out) throws IOException - { - MavenProjectsManager manager = MavenProjectsManager.getInstance(module.getProject()); - MavenProject mavenProject = manager.findProject(module); - if(mavenProject == null) - { - out.append(text); - return; - } - - Element pluginConfiguration = mavenProject.getPluginConfiguration("org.apache.maven.plugins", "maven-resources-plugin"); - String escapeWindowsPathsStr = MavenJDOMUtil.findChildValueByPath(pluginConfiguration, "escapeWindowsPaths"); - boolean escapeWindowsPath = escapeWindowsPathsStr == null || Boolean.parseBoolean(escapeWindowsPathsStr); - - doFilterText(MavenFilteredPropertyPsiReferenceProvider.getDelimitersPattern(mavenProject), manager, mavenProject, text, additionalProperties, propertyEscapeString, escapeWindowsPath, null, - out); - } - - private static void doFilterText(Pattern pattern, - MavenProjectsManager mavenProjectsManager, - MavenProject mavenProject, - String text, - Properties additionalProperties, - @Nullable String escapeString, - boolean escapeWindowsPath, - @Nullable Map resolvedPropertiesParam, - Appendable out) throws IOException - { - Map resolvedProperties = resolvedPropertiesParam; - - Matcher matcher = pattern.matcher(text); - int groupCount = matcher.groupCount(); - - int last = 0; - while(matcher.find()) - { - if(escapeString != null) - { - int escapeStringStartIndex = matcher.start() - escapeString.length(); - if(escapeStringStartIndex >= last) - { - if(text.startsWith(escapeString, escapeStringStartIndex)) - { - out.append(text, last, escapeStringStartIndex); - out.append(matcher.group()); - last = matcher.end(); - continue; - } - } - } - - out.append(text, last, matcher.start()); - last = matcher.end(); - - String propertyName = null; - - for(int i = 0; i < groupCount; i++) - { - propertyName = matcher.group(i + 1); - if(propertyName != null) - { - break; - } - } - - assert propertyName != null; - - if(resolvedProperties == null) - { - resolvedProperties = new HashMap(); - } - - String propertyValue = resolvedProperties.get(propertyName); - if(propertyValue == null) - { - if(resolvedProperties.containsKey(propertyName)) - { // if cyclic property dependencies - out.append(matcher.group()); - continue; - } - - String resolved = doResolveProperty(propertyName, mavenProjectsManager, mavenProject, additionalProperties); - if(resolved == null) - { - out.append(matcher.group()); - continue; - } - - resolvedProperties.put(propertyName, null); - - StringBuilder sb = new StringBuilder(); - doFilterText(pattern, mavenProjectsManager, mavenProject, resolved, additionalProperties, null, escapeWindowsPath, resolvedProperties, sb); - propertyValue = sb.toString(); - - resolvedProperties.put(propertyName, propertyValue); - } - - if(escapeWindowsPath) - { - MavenEscapeWindowsCharacterUtils.escapeWindowsPath(out, propertyValue); - } - else - { - out.append(propertyValue); - } - } - - out.append(text, last, text.length()); - } - - public static String resolve(String text, MavenDomProjectModel projectDom) - { - XmlElement element = projectDom.getXmlElement(); - if(element == null) - { - return text; - } - - VirtualFile file = MavenDomUtil.getVirtualFile(element); - if(file == null) - { - return text; - } - MavenProjectsManager manager = MavenProjectsManager.getInstance(projectDom.getManager().getProject()); - - MavenProject mavenProject = manager.findProject(file); - if(mavenProject == null) - { - return text; - } - - StringBuilder res = new StringBuilder(); - try - { - doFilterText(PATTERN, manager, mavenProject, text, collectPropertiesFromDOM(mavenProject, projectDom), null, false, null, res); - } - catch(IOException e) - { - throw new RuntimeException(e); // never thrown - } - - return res.toString(); - } - - private static Properties collectPropertiesFromDOM(MavenProject project, MavenDomProjectModel projectDom) - { - Properties result = new Properties(); - - collectPropertiesFromDOM(projectDom.getProperties(), result); - - Collection activeProfiles = project.getActivatedProfilesIds().getEnabledProfiles(); - for(MavenDomProfile each : projectDom.getProfiles().getProfiles()) - { - XmlTag idTag = each.getId().getXmlTag(); - if(idTag == null || !activeProfiles.contains(idTag.getValue().getTrimmedText())) - { - continue; - } - collectPropertiesFromDOM(each.getProperties(), result); - } - - return result; - } - - private static void collectPropertiesFromDOM(MavenDomProperties props, Properties result) - { - XmlTag propsTag = props.getXmlTag(); - if(propsTag != null) - { - for(XmlTag each : propsTag.getSubTags()) - { - result.setProperty(each.getName(), each.getValue().getTrimmedText()); - } - } - } - - @Nullable - private static String doResolveProperty(String propName, MavenProjectsManager projectsManager, MavenProject mavenProject, Properties 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; - } - - MavenProject selectedProject = mavenProject; - - while(unprefixed.startsWith("parent.")) - { - MavenId parentId = selectedProject.getParentId(); - if(parentId == null) - { - return null; - } - - unprefixed = unprefixed.substring("parent.".length()); - - if(unprefixed.equals("groupId")) - { - return parentId.getGroupId(); - } - if(unprefixed.equals("artifactId")) - { - return parentId.getArtifactId(); - } - - selectedProject = projectsManager.findProject(parentId); - if(selectedProject == null) - { - return null; - } - } - - if(unprefixed.equals("basedir") || (hasPrefix && mavenProject == selectedProject && unprefixed.equals("baseUri"))) - { - return selectedProject.getDirectory(); - } - - if("java.home".equals(propName)) - { - Module module = projectsManager.findModule(mavenProject); - if(module != null) - { - Sdk sdk = ModuleUtilCore.getSdk(module, JavaModuleExtensionImpl.class); - if(sdk != null) - { - VirtualFile homeDirectory = sdk.getHomeDirectory(); - if(homeDirectory != null) - { - VirtualFile jreDir = homeDirectory.findChild("jre"); - if(jreDir != null) - { - return jreDir.getPath(); - } - } - } - } - } - - String result; - - result = MavenUtil.getPropertiesFromMavenOpts().get(propName); - if(result != null) - { - return result; - } - - result = MavenServerUtil.collectSystemProperties().getProperty(propName); - if(result != null) - { - return result; - } - - result = selectedProject.getModelMap().get(unprefixed); - if(result != null) - { - return result; - } - - result = additionalProperties.getProperty(propName); - if(result != null) - { - return result; - } - - result = mavenProject.getProperties().getProperty(propName); - if(result != null) - { - return result; - } - - if("settings.localRepository".equals(propName)) - { - return mavenProject.getLocalRepository().getAbsolutePath(); - } - - return null; - } +public class MavenPropertyResolver { + public static final Pattern PATTERN = Pattern.compile("\\$\\{(.+?)\\}|@(.+?)@"); + + public static void doFilterText( + Module module, + String text, + Properties additionalProperties, + String propertyEscapeString, + Appendable out + ) throws IOException { + MavenProjectsManager manager = MavenProjectsManager.getInstance(module.getProject()); + MavenProject mavenProject = manager.findProject(module); + if (mavenProject == null) { + out.append(text); + return; + } + + Element pluginConfiguration = mavenProject.getPluginConfiguration("org.apache.maven.plugins", "maven-resources-plugin"); + String escapeWindowsPathsStr = MavenJDOMUtil.findChildValueByPath(pluginConfiguration, "escapeWindowsPaths"); + boolean escapeWindowsPath = escapeWindowsPathsStr == null || Boolean.parseBoolean(escapeWindowsPathsStr); + + doFilterText( + MavenFilteredPropertyPsiReferenceProvider.getDelimitersPattern(mavenProject), + manager, + mavenProject, + text, + additionalProperties, + propertyEscapeString, + escapeWindowsPath, + null, + out + ); + } + + private static void doFilterText( + Pattern pattern, + MavenProjectsManager mavenProjectsManager, + MavenProject mavenProject, + String text, + Properties additionalProperties, + @Nullable String escapeString, + boolean escapeWindowsPath, + @Nullable Map resolvedPropertiesParam, + Appendable out + ) throws IOException { + Map resolvedProperties = resolvedPropertiesParam; + + Matcher matcher = pattern.matcher(text); + int groupCount = matcher.groupCount(); + + int last = 0; + while (matcher.find()) { + if (escapeString != null) { + int escapeStringStartIndex = matcher.start() - escapeString.length(); + if (escapeStringStartIndex >= last && text.startsWith(escapeString, escapeStringStartIndex)) { + out.append(text, last, escapeStringStartIndex); + out.append(matcher.group()); + last = matcher.end(); + continue; + } + } + + out.append(text, last, matcher.start()); + last = matcher.end(); + + String propertyName = null; + + for (int i = 0; i < groupCount; i++) { + propertyName = matcher.group(i + 1); + if (propertyName != null) { + break; + } + } + + assert propertyName != null; + + if (resolvedProperties == null) { + resolvedProperties = new HashMap<>(); + } + + String propertyValue = resolvedProperties.get(propertyName); + if (propertyValue == null) { + if (resolvedProperties.containsKey(propertyName)) { // if cyclic property dependencies + out.append(matcher.group()); + continue; + } + + String resolved = doResolveProperty(propertyName, mavenProjectsManager, mavenProject, additionalProperties); + if (resolved == null) { + out.append(matcher.group()); + continue; + } + + resolvedProperties.put(propertyName, null); + + StringBuilder sb = new StringBuilder(); + doFilterText( + pattern, + mavenProjectsManager, + mavenProject, + resolved, + additionalProperties, + null, + escapeWindowsPath, + resolvedProperties, + sb + ); + propertyValue = sb.toString(); + + resolvedProperties.put(propertyName, propertyValue); + } + + if (escapeWindowsPath) { + MavenEscapeWindowsCharacterUtils.escapeWindowsPath(out, propertyValue); + } + else { + out.append(propertyValue); + } + } + + out.append(text, last, text.length()); + } + + public static String resolve(String text, MavenDomProjectModel projectDom) { + XmlElement element = projectDom.getXmlElement(); + if (element == null) { + return text; + } + + VirtualFile file = MavenDomUtil.getVirtualFile(element); + if (file == null) { + return text; + } + MavenProjectsManager manager = MavenProjectsManager.getInstance(projectDom.getManager().getProject()); + + MavenProject mavenProject = manager.findProject(file); + if (mavenProject == null) { + return text; + } + + StringBuilder res = new StringBuilder(); + try { + doFilterText( + PATTERN, + manager, + mavenProject, + text, + collectPropertiesFromDOM(mavenProject, projectDom), + null, + false, + null, + res + ); + } + catch (IOException e) { + throw new RuntimeException(e); // never thrown + } + + return res.toString(); + } + + private static Properties collectPropertiesFromDOM(MavenProject project, MavenDomProjectModel projectDom) { + Properties result = new Properties(); + + collectPropertiesFromDOM(projectDom.getProperties(), result); + + Collection activeProfiles = project.getActivatedProfilesIds().getEnabledProfiles(); + for (MavenDomProfile each : projectDom.getProfiles().getProfiles()) { + XmlTag idTag = each.getId().getXmlTag(); + if (idTag == null || !activeProfiles.contains(idTag.getValue().getTrimmedText())) { + continue; + } + collectPropertiesFromDOM(each.getProperties(), result); + } + + return result; + } + + private static void collectPropertiesFromDOM(MavenDomProperties props, Properties result) { + XmlTag propsTag = props.getXmlTag(); + if (propsTag != null) { + for (XmlTag each : propsTag.getSubTags()) { + result.setProperty(each.getName(), each.getValue().getTrimmedText()); + } + } + } + + @Nullable + private static String doResolveProperty( + String propName, + MavenProjectsManager projectsManager, + MavenProject mavenProject, + Properties 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; + } + + MavenProject selectedProject = mavenProject; + + while (unprefixed.startsWith("parent.")) { + MavenId parentId = selectedProject.getParentId(); + if (parentId == null) { + return null; + } + + unprefixed = unprefixed.substring("parent.".length()); + + if (unprefixed.equals("groupId")) { + return parentId.getGroupId(); + } + if (unprefixed.equals("artifactId")) { + return parentId.getArtifactId(); + } + + selectedProject = projectsManager.findProject(parentId); + if (selectedProject == null) { + return null; + } + } + + if (unprefixed.equals("basedir") || (hasPrefix && mavenProject == selectedProject && unprefixed.equals("baseUri"))) { + return selectedProject.getDirectory(); + } + + if ("java.home".equals(propName)) { + Module module = projectsManager.findModule(mavenProject); + if (module != null) { + Sdk sdk = ModuleUtilCore.getSdk(module, JavaModuleExtensionImpl.class); + if (sdk != null) { + VirtualFile homeDirectory = sdk.getHomeDirectory(); + if (homeDirectory != null) { + VirtualFile jreDir = homeDirectory.findChild("jre"); + if (jreDir != null) { + return jreDir.getPath(); + } + } + } + } + } + + String result; + + result = MavenUtil.getPropertiesFromMavenOpts().get(propName); + if (result != null) { + return result; + } + + result = MavenServerUtil.collectSystemProperties().getProperty(propName); + if (result != null) { + return result; + } + + result = selectedProject.getModelMap().get(unprefixed); + if (result != null) { + return result; + } + + result = additionalProperties.getProperty(propName); + if (result != null) { + return result; + } + + result = mavenProject.getProperties().getProperty(propName); + if (result != null) { + return result; + } + + if ("settings.localRepository".equals(propName)) { + return mavenProject.getLocalRepository().getAbsolutePath(); + } + + return null; + } } diff --git a/plugin/src/main/java/org/jetbrains/idea/maven/dom/MavenSchemaProvider.java b/plugin/src/main/java/org/jetbrains/idea/maven/dom/MavenSchemaProvider.java index b11b5eee..3b3a719f 100644 --- a/plugin/src/main/java/org/jetbrains/idea/maven/dom/MavenSchemaProvider.java +++ b/plugin/src/main/java/org/jetbrains/idea/maven/dom/MavenSchemaProvider.java @@ -28,50 +28,47 @@ import java.util.Map; @ExtensionImpl -public class MavenSchemaProvider implements StandardResourceProvider -{ - public static final String MAVEN_PROJECT_SCHEMA_URL = "http://maven.apache.org/xsd/maven-4.0.0.xsd"; - public static final String MAVEN_PROFILES_SCHEMA_URL = "http://maven.apache.org/xsd/profiles-1.0.0.xsd"; - public static final String MAVEN_SETTINGS_SCHEMA_URL = "http://maven.apache.org/xsd/settings-1.0.0.xsd"; - public static final String MAVEN_SETTINGS_SCHEMA_URL_1_1 = "http://maven.apache.org/xsd/settings-1.1.0.xsd"; - public static final String MAVEN_SETTINGS_SCHEMA_URL_1_2 = "http://maven.apache.org/xsd/settings-1.2.0.xsd"; +public class MavenSchemaProvider implements StandardResourceProvider { + public static final String MAVEN_PROJECT_SCHEMA_URL = "http://maven.apache.org/xsd/maven-4.0.0.xsd"; + public static final String MAVEN_PROFILES_SCHEMA_URL = "http://maven.apache.org/xsd/profiles-1.0.0.xsd"; + public static final String MAVEN_SETTINGS_SCHEMA_URL = "http://maven.apache.org/xsd/settings-1.0.0.xsd"; + public static final String MAVEN_SETTINGS_SCHEMA_URL_1_1 = "http://maven.apache.org/xsd/settings-1.1.0.xsd"; + public static final String MAVEN_SETTINGS_SCHEMA_URL_1_2 = "http://maven.apache.org/xsd/settings-1.2.0.xsd"; - public static final List MAVEN_SETTINGS_SCHEMAS = List.of(MAVEN_SETTINGS_SCHEMA_URL, - MAVEN_SETTINGS_SCHEMA_URL_1_1, - MAVEN_SETTINGS_SCHEMA_URL_1_2); + public static final List MAVEN_SETTINGS_SCHEMAS = List.of( + MAVEN_SETTINGS_SCHEMA_URL, + MAVEN_SETTINGS_SCHEMA_URL_1_1, + MAVEN_SETTINGS_SCHEMA_URL_1_2 + ); - @Override - public void registerResources(ResourceRegistrar registrar) - { - Map.of( - MAVEN_PROJECT_SCHEMA_URL, "/schemas/maven-4.0.0.xsd", - "http://maven.apache.org/maven-v4_0_0.xsd", "/schemas/maven-4.0.0.xsd", - MAVEN_PROFILES_SCHEMA_URL, "/schemas/profiles-1.0.0.xsd", - MAVEN_SETTINGS_SCHEMA_URL, "/schemas/settings-1.0.0.xsd", - MAVEN_SETTINGS_SCHEMA_URL_1_1, "/schemas/settings-1.1.0.xsd", - MAVEN_SETTINGS_SCHEMA_URL_1_2, "/schemas/settings-1.2.0.xsd" - ).forEach((schemaUrl, schemaPath) -> addStdResource(registrar, schemaUrl, schemaPath)); - } + @Override + public void registerResources(ResourceRegistrar registrar) { + Map.of( + MAVEN_PROJECT_SCHEMA_URL, "/schemas/maven-4.0.0.xsd", + "http://maven.apache.org/maven-v4_0_0.xsd", "/schemas/maven-4.0.0.xsd", + MAVEN_PROFILES_SCHEMA_URL, "/schemas/profiles-1.0.0.xsd", + MAVEN_SETTINGS_SCHEMA_URL, "/schemas/settings-1.0.0.xsd", + MAVEN_SETTINGS_SCHEMA_URL_1_1, "/schemas/settings-1.1.0.xsd", + MAVEN_SETTINGS_SCHEMA_URL_1_2, "/schemas/settings-1.2.0.xsd" + ).forEach((schemaUrl, schemaPath) -> addStdResource(registrar, schemaUrl, schemaPath)); + } - private void addStdResource(ResourceRegistrar registrar, String schemaUrl, String schemaPath) - { - registrar.addStdResource(schemaUrl, schemaPath); - if(schemaUrl.startsWith("http://")) - { - String schemaUrlHttps = schemaUrl.replace("http://", "https://"); - registrar.addStdResource(schemaUrlHttps, schemaPath); - } - } + private void addStdResource(ResourceRegistrar registrar, String schemaUrl, String schemaPath) { + registrar.addStdResource(schemaUrl, schemaPath); + if (schemaUrl.startsWith("http://")) { + String schemaUrlHttps = schemaUrl.replace("http://", "https://"); + registrar.addStdResource(schemaUrlHttps, schemaPath); + } + } - @Nonnull - public static VirtualFile getSchemaFile(@Nonnull String url) - { - String location = ((ExternalResourceManagerEx) ExternalResourceManager.getInstance()).getStdResource(url, null); - assert location != null : "cannot find a standard resource for " + url; + @Nonnull + public static VirtualFile getSchemaFile(@Nonnull String url) { + String location = ((ExternalResourceManagerEx)ExternalResourceManager.getInstance()).getStdResource(url, null); + assert location != null : "cannot find a standard resource for " + url; - VirtualFile result = VirtualFileUtil.findRelativeFile(location, null); - assert result != null : "cannot find a schema file for URL: " + url + " location: " + location; + VirtualFile result = VirtualFileUtil.findRelativeFile(location, null); + assert result != null : "cannot find a schema file for URL: " + url + " location: " + location; - return result; - } + return result; + } } \ No newline at end of file diff --git a/plugin/src/main/java/org/jetbrains/idea/maven/dom/MavenVersionComparable.java b/plugin/src/main/java/org/jetbrains/idea/maven/dom/MavenVersionComparable.java index 90a2efdd..58a2606e 100644 --- a/plugin/src/main/java/org/jetbrains/idea/maven/dom/MavenVersionComparable.java +++ b/plugin/src/main/java/org/jetbrains/idea/maven/dom/MavenVersionComparable.java @@ -9,349 +9,363 @@ * @author Sergey Evdokimov */ public class MavenVersionComparable implements Comparable { - private String value; - - private String canonical; - - private ListItem items; - - private interface Item { - int INTEGER_ITEM = 0; - int STRING_ITEM = 1; - int LIST_ITEM = 2; - - int compareTo(Item item); + private String value; - int getType(); + private String canonical; - boolean isNull(); - } + private ListItem items; - /** - * Represents a numeric item in the version item list. - */ - private static class IntegerItem - implements Item { - private static final BigInteger BigInteger_ZERO = new BigInteger("0"); + private interface Item { + int INTEGER_ITEM = 0; + int STRING_ITEM = 1; + int LIST_ITEM = 2; - private final BigInteger value; + int compareTo(Item item); - public static final IntegerItem ZERO = new IntegerItem(); + int getType(); - private IntegerItem() { - this.value = BigInteger_ZERO; + boolean isNull(); } - public IntegerItem(String str) { - this.value = new BigInteger(str); - } + /** + * Represents a numeric item in the version item list. + */ + private static class IntegerItem + implements Item { + private static final BigInteger BigInteger_ZERO = new BigInteger("0"); - public int getType() { - return INTEGER_ITEM; - } + private final BigInteger value; - public boolean isNull() { - return BigInteger_ZERO.equals(value); - } + public static final IntegerItem ZERO = new IntegerItem(); - public int compareTo(Item item) { - if (item == null) { - return BigInteger_ZERO.equals(value) ? 0 : 1; // 1.0 == 1, 1.1 > 1 - } + private IntegerItem() { + this.value = BigInteger_ZERO; + } - switch (item.getType()) { - case INTEGER_ITEM: - return value.compareTo(((IntegerItem)item).value); + public IntegerItem(String str) { + this.value = new BigInteger(str); + } - case STRING_ITEM: - return 1; // 1.1 > 1-sp + @Override + public int getType() { + return INTEGER_ITEM; + } - case LIST_ITEM: - return 1; // 1.1 > 1-1 + @Override + public boolean isNull() { + return BigInteger_ZERO.equals(value); + } - default: - throw new RuntimeException("invalid item: " + item.getClass()); - } - } + @Override + public int compareTo(Item item) { + if (item == null) { + return BigInteger_ZERO.equals(value) ? 0 : 1; // 1.0 == 1, 1.1 > 1 + } - public String toString() { - return value.toString(); - } - } + switch (item.getType()) { + case INTEGER_ITEM: + return value.compareTo(((IntegerItem)item).value); - /** - * Represents a string in the version item list, usually a qualifier. - */ - private static class StringItem - implements Item { - private static final String[] QUALIFIERS = {"alpha", "beta", "milestone", "rc", "snapshot", "", "sp"}; + case STRING_ITEM: + return 1; // 1.1 > 1-sp - private static final List _QUALIFIERS = Arrays.asList(QUALIFIERS); + case LIST_ITEM: + return 1; // 1.1 > 1-1 - private static final Properties ALIASES = new Properties(); + default: + throw new RuntimeException("invalid item: " + item.getClass()); + } + } - static { - ALIASES.setProperty("ga", ""); - ALIASES.setProperty("final", ""); - ALIASES.setProperty("cr", "rc"); + @Override + public String toString() { + return value.toString(); + } } /** - * A comparable value for the empty-string qualifier. This one is used to determine if a given qualifier makes - * the version older than one without a qualifier, or more recent. + * Represents a string in the version item list, usually a qualifier. */ - private static final String RELEASE_VERSION_INDEX = String.valueOf(_QUALIFIERS.indexOf("")); + private static class StringItem + implements Item { + private static final String[] QUALIFIERS = {"alpha", "beta", "milestone", "rc", "snapshot", "", "sp"}; - private String value; + private static final List _QUALIFIERS = Arrays.asList(QUALIFIERS); - public StringItem(String value, boolean followedByDigit) { - if (followedByDigit && value.length() == 1) { - // a1 = alpha-1, b1 = beta-1, m1 = milestone-1 - switch (value.charAt(0)) { - case 'a': - value = "alpha"; - break; - case 'b': - value = "beta"; - break; - case 'm': - value = "milestone"; - break; - } - } - this.value = ALIASES.getProperty(value, value); - } + private static final Properties ALIASES = new Properties(); - public int getType() { - return STRING_ITEM; - } + static { + ALIASES.setProperty("ga", ""); + ALIASES.setProperty("final", ""); + ALIASES.setProperty("cr", "rc"); + } - public boolean isNull() { - return (comparableQualifier(value).compareTo(RELEASE_VERSION_INDEX) == 0); - } + /** + * A comparable value for the empty-string qualifier. This one is used to determine if a given qualifier makes + * the version older than one without a qualifier, or more recent. + */ + private static final String RELEASE_VERSION_INDEX = String.valueOf(_QUALIFIERS.indexOf("")); + + private String value; + + public StringItem(String value, boolean followedByDigit) { + if (followedByDigit && value.length() == 1) { + // a1 = alpha-1, b1 = beta-1, m1 = milestone-1 + switch (value.charAt(0)) { + case 'a': + value = "alpha"; + break; + case 'b': + value = "beta"; + break; + case 'm': + value = "milestone"; + break; + } + } + this.value = ALIASES.getProperty(value, value); + } - /** - * Returns a comparable value for a qualifier. - *

- * This method both takes into account the ordering of known qualifiers as well as lexical ordering for unknown - * qualifiers. - *

- * just returning an Integer with the index here is faster, but requires a lot of if/then/else to check for -1 - * or QUALIFIERS.size and then resort to lexical ordering. Most comparisons are decided by the first character, - * so this is still fast. If more characters are needed then it requires a lexical sort anyway. - * - * @param qualifier - * @return an equivalent value that can be used with lexical comparison - */ - public static String comparableQualifier(String qualifier) { - int i = _QUALIFIERS.indexOf(qualifier); + @Override + public int getType() { + return STRING_ITEM; + } - return i == -1 ? _QUALIFIERS.size() + "-" + qualifier : String.valueOf(i); - } + @Override + public boolean isNull() { + return (comparableQualifier(value).compareTo(RELEASE_VERSION_INDEX) == 0); + } - public int compareTo(Item item) { - if (item == null) { - // 1-rc < 1, 1-ga > 1 - return comparableQualifier(value).compareTo(RELEASE_VERSION_INDEX); - } - switch (item.getType()) { - case INTEGER_ITEM: - return -1; // 1.any < 1.1 ? + /** + * Returns a comparable value for a qualifier. + *

+ * This method both takes into account the ordering of known qualifiers as well as lexical ordering for unknown + * qualifiers. + *

+ * just returning an Integer with the index here is faster, but requires a lot of if/then/else to check for -1 + * or QUALIFIERS.size and then resort to lexical ordering. Most comparisons are decided by the first character, + * so this is still fast. If more characters are needed then it requires a lexical sort anyway. + * + * @param qualifier + * @return an equivalent value that can be used with lexical comparison + */ + public static String comparableQualifier(String qualifier) { + int i = _QUALIFIERS.indexOf(qualifier); + + return i == -1 ? _QUALIFIERS.size() + "-" + qualifier : String.valueOf(i); + } - case STRING_ITEM: - return comparableQualifier(value).compareTo(comparableQualifier(((StringItem)item).value)); + @Override + public int compareTo(Item item) { + if (item == null) { + // 1-rc < 1, 1-ga > 1 + return comparableQualifier(value).compareTo(RELEASE_VERSION_INDEX); + } + switch (item.getType()) { + case INTEGER_ITEM: + return -1; // 1.any < 1.1 ? - case LIST_ITEM: - return -1; // 1.any < 1-1 + case STRING_ITEM: + return comparableQualifier(value).compareTo(comparableQualifier(((StringItem)item).value)); - default: - throw new RuntimeException("invalid item: " + item.getClass()); - } - } + case LIST_ITEM: + return -1; // 1.any < 1-1 - public String toString() { - return value; - } - } - - /** - * Represents a version list item. This class is used both for the global item list and for sub-lists (which start - * with '-(number)' in the version specification). - */ - private static class ListItem - extends ArrayList - implements Item { - public int getType() { - return LIST_ITEM; - } + default: + throw new RuntimeException("invalid item: " + item.getClass()); + } + } - public boolean isNull() { - return (size() == 0); + @Override + public String toString() { + return value; + } } - void normalize() { - for (ListIterator iterator = listIterator(size()); iterator.hasPrevious(); ) { - Item item = iterator.previous(); - if (item.isNull()) { - iterator.remove(); // remove null trailing items: 0, "", empty list + /** + * Represents a version list item. This class is used both for the global item list and for sub-lists (which start + * with '-(number)' in the version specification). + */ + private static class ListItem extends ArrayList implements Item { + @Override + public int getType() { + return LIST_ITEM; } - else { - break; + + @Override + public boolean isNull() { + return (size() == 0); } - } - } - public int compareTo(Item item) { - if (item == null) { - if (size() == 0) { - return 0; // 1-0 = 1- (normalize) = 1 + void normalize() { + for (ListIterator iterator = listIterator(size()); iterator.hasPrevious(); ) { + Item item = iterator.previous(); + if (item.isNull()) { + iterator.remove(); // remove null trailing items: 0, "", empty list + } + else { + break; + } + } } - Item first = get(0); - return first.compareTo(null); - } - switch (item.getType()) { - case INTEGER_ITEM: - return -1; // 1-1 < 1.0.x - case STRING_ITEM: - return 1; // 1-1 > 1-sp + @Override + public int compareTo(Item item) { + if (item == null) { + if (size() == 0) { + return 0; // 1-0 = 1- (normalize) = 1 + } + Item first = get(0); + return first.compareTo(null); + } + switch (item.getType()) { + case INTEGER_ITEM: + return -1; // 1-1 < 1.0.x - case LIST_ITEM: - Iterator left = iterator(); - Iterator right = ((ListItem)item).iterator(); + case STRING_ITEM: + return 1; // 1-1 > 1-sp - while (left.hasNext() || right.hasNext()) { - Item l = left.hasNext() ? left.next() : null; - Item r = right.hasNext() ? right.next() : null; + case LIST_ITEM: + Iterator left = iterator(); + Iterator right = ((ListItem)item).iterator(); - // if this is shorter, then invert the compare and mul with -1 - int result = l == null ? -1 * r.compareTo(l) : l.compareTo(r); + while (left.hasNext() || right.hasNext()) { + Item l = left.hasNext() ? left.next() : null; + Item r = right.hasNext() ? right.next() : null; - if (result != 0) { - return result; - } - } + // if this is shorter, then invert the compare and mul with -1 + int result = l == null ? -1 * r.compareTo(l) : l.compareTo(r); - return 0; + if (result != 0) { + return result; + } + } - default: - throw new RuntimeException("invalid item: " + item.getClass()); - } - } + return 0; - public String toString() { - StringBuilder buffer = new StringBuilder("("); - for (Iterator iter = iterator(); iter.hasNext(); ) { - buffer.append(iter.next()); - if (iter.hasNext()) { - buffer.append(','); + default: + throw new RuntimeException("invalid item: " + item.getClass()); + } } - } - buffer.append(')'); - return buffer.toString(); - } - } - public MavenVersionComparable(String version) { - parseVersion(version); - } + @Override + public String toString() { + StringBuilder buffer = new StringBuilder("("); + for (Iterator iter = iterator(); iter.hasNext(); ) { + buffer.append(iter.next()); + if (iter.hasNext()) { + buffer.append(','); + } + } + buffer.append(')'); + return buffer.toString(); + } + } - public final void parseVersion(String version) { - this.value = version; + public MavenVersionComparable(String version) { + parseVersion(version); + } - items = new ListItem(); + public final void parseVersion(String version) { + this.value = version; - version = version.toLowerCase(Locale.ENGLISH); + items = new ListItem(); - ListItem list = items; + version = version.toLowerCase(Locale.ENGLISH); - Stack stack = new Stack(); - stack.push(list); + ListItem list = items; - boolean isDigit = false; + Stack stack = new Stack<>(); + stack.push(list); - int startIndex = 0; + boolean isDigit = false; - for (int i = 0; i < version.length(); i++) { - char c = version.charAt(i); + int startIndex = 0; - if (c == '.') { - if (i == startIndex) { - list.add(IntegerItem.ZERO); - } - else { - list.add(parseItem(isDigit, version.substring(startIndex, i))); - } - startIndex = i + 1; - } - else if (c == '-') { - if (i == startIndex) { - list.add(IntegerItem.ZERO); - } - else { - list.add(parseItem(isDigit, version.substring(startIndex, i))); - } - startIndex = i + 1; + for (int i = 0; i < version.length(); i++) { + char c = version.charAt(i); - if (isDigit) { - list.normalize(); // 1.0-* = 1-* + if (c == '.') { + if (i == startIndex) { + list.add(IntegerItem.ZERO); + } + else { + list.add(parseItem(isDigit, version.substring(startIndex, i))); + } + startIndex = i + 1; + } + else if (c == '-') { + if (i == startIndex) { + list.add(IntegerItem.ZERO); + } + else { + list.add(parseItem(isDigit, version.substring(startIndex, i))); + } + startIndex = i + 1; + + if (isDigit) { + list.normalize(); // 1.0-* = 1-* + + if ((i + 1 < version.length()) && Character.isDigit(version.charAt(i + 1))) { + // new ListItem only if previous were digits and new char is a digit, + // ie need to differentiate only 1.1 from 1-1 + list.add(list = new ListItem()); + + stack.push(list); + } + } + } + else if (Character.isDigit(c)) { + if (!isDigit && i > startIndex) { + list.add(new StringItem(version.substring(startIndex, i), true)); + startIndex = i; + } - if ((i + 1 < version.length()) && Character.isDigit(version.charAt(i + 1))) { - // new ListItem only if previous were digits and new char is a digit, - // ie need to differentiate only 1.1 from 1-1 - list.add(list = new ListItem()); + isDigit = true; + } + else { + if (isDigit && i > startIndex) { + list.add(parseItem(true, version.substring(startIndex, i))); + startIndex = i; + } - stack.push(list); - } + isDigit = false; + } } - } - else if (Character.isDigit(c)) { - if (!isDigit && i > startIndex) { - list.add(new StringItem(version.substring(startIndex, i), true)); - startIndex = i; + + if (version.length() > startIndex) { + list.add(parseItem(isDigit, version.substring(startIndex))); } - isDigit = true; - } - else { - if (isDigit && i > startIndex) { - list.add(parseItem(true, version.substring(startIndex, i))); - startIndex = i; + while (!stack.isEmpty()) { + list = (ListItem)stack.pop(); + list.normalize(); } - isDigit = false; - } + canonical = items.toString(); } - if (version.length() > startIndex) { - list.add(parseItem(isDigit, version.substring(startIndex))); + private static Item parseItem(boolean isDigit, String buf) { + return isDigit ? new IntegerItem(buf) : new StringItem(buf, false); } - while (!stack.isEmpty()) { - list = (ListItem)stack.pop(); - list.normalize(); + @Override + public int compareTo(MavenVersionComparable o) { + return items.compareTo(o.items); } - canonical = items.toString(); - } - - private static Item parseItem(boolean isDigit, String buf) { - return isDigit ? new IntegerItem(buf) : new StringItem(buf, false); - } - - public int compareTo(MavenVersionComparable o) { - return items.compareTo(o.items); - } - - public String toString() { - return value; - } + @Override + public String toString() { + return value; + } - public boolean equals(Object o) { - return (o instanceof MavenVersionComparable) && canonical.equals(((MavenVersionComparable)o).canonical); - } + @Override + public boolean equals(Object o) { + return o instanceof MavenVersionComparable versionComparable && canonical.equals(versionComparable.canonical); + } - public int hashCode() { - return canonical.hashCode(); - } + @Override + public int hashCode() { + return canonical.hashCode(); + } } diff --git a/plugin/src/main/java/org/jetbrains/idea/maven/dom/converters/repositories/MavenRepositoryConverter.java b/plugin/src/main/java/org/jetbrains/idea/maven/dom/converters/repositories/MavenRepositoryConverter.java index fa3c50da..86a53f7e 100644 --- a/plugin/src/main/java/org/jetbrains/idea/maven/dom/converters/repositories/MavenRepositoryConverter.java +++ b/plugin/src/main/java/org/jetbrains/idea/maven/dom/converters/repositories/MavenRepositoryConverter.java @@ -15,6 +15,7 @@ */ package org.jetbrains.idea.maven.dom.converters.repositories; +import consulo.annotation.access.RequiredReadAction; import consulo.language.psi.PsiElement; import consulo.language.psi.PsiReference; import consulo.maven.icon.MavenIconGroup; @@ -27,7 +28,6 @@ import consulo.xml.util.xml.ConvertContext; import consulo.xml.util.xml.GenericDomValue; import consulo.xml.util.xml.ResolvingConverter; -import org.jetbrains.annotations.NonNls; import javax.annotation.Nonnull; import javax.annotation.Nullable; @@ -88,6 +88,7 @@ public PsiReference[] createReferences(GenericDomValue value, final PsiElement e @Nonnull @Override + @RequiredReadAction public Object[] getVariants() { consulo.module.Module module = context.getModule(); diff --git a/plugin/src/main/java/org/jetbrains/idea/maven/dom/generate/GenerateDependencyAction.java b/plugin/src/main/java/org/jetbrains/idea/maven/dom/generate/GenerateDependencyAction.java index f8b1f569..4dba3313 100644 --- a/plugin/src/main/java/org/jetbrains/idea/maven/dom/generate/GenerateDependencyAction.java +++ b/plugin/src/main/java/org/jetbrains/idea/maven/dom/generate/GenerateDependencyAction.java @@ -15,6 +15,7 @@ */ package org.jetbrains.idea.maven.dom.generate; +import consulo.annotation.access.RequiredReadAction; import consulo.application.AllIcons; import consulo.application.Result; import consulo.codeEditor.Editor; @@ -28,97 +29,78 @@ import consulo.xml.util.xml.DomUtil; import consulo.xml.util.xml.ui.actions.generate.GenerateDomElementAction; import org.jetbrains.idea.maven.dom.DependencyConflictId; -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.MavenDomDependencyManagement; import org.jetbrains.idea.maven.dom.model.MavenDomProjectModel; import org.jetbrains.idea.maven.indices.MavenArtifactSearchDialog; +import org.jetbrains.idea.maven.localize.MavenDomLocalize; import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.util.List; import java.util.Map; -public class GenerateDependencyAction extends GenerateDomElementAction -{ - public GenerateDependencyAction() - { - super(new MavenGenerateProvider(MavenDomBundle.message("generate.dependency"), MavenDomDependency.class) - { - @Nullable - @Override - protected MavenDomDependency doGenerate(@Nonnull final MavenDomProjectModel mavenModel, final Editor editor) - { - Project project = mavenModel.getManager().getProject(); +public class GenerateDependencyAction extends GenerateDomElementAction { + public GenerateDependencyAction() { + super(new MavenGenerateProvider<>(MavenDomLocalize.generateDependency().get(), MavenDomDependency.class) { + @Nullable + @Override + protected MavenDomDependency doGenerate(@Nonnull final MavenDomProjectModel mavenModel, final Editor editor) { + Project project = mavenModel.getManager().getProject(); - final Map managedDependencies = GenerateManagedDependencyAction - .collectManagingDependencies(mavenModel); + final Map managedDependencies = GenerateManagedDependencyAction + .collectManagingDependencies(mavenModel); - final List ids = MavenArtifactSearchDialog.searchForArtifact(project, managedDependencies.values()); - if(ids.isEmpty()) - { - return null; - } + final List ids = MavenArtifactSearchDialog.searchForArtifact(project, managedDependencies.values()); + if (ids.isEmpty()) { + return null; + } - PsiDocumentManager.getInstance(project).commitAllDocuments(); + PsiDocumentManager.getInstance(project).commitAllDocuments(); - XmlFile psiFile = DomUtil.getFile(mavenModel); - return new WriteCommandAction(psiFile.getProject(), "Generate Dependency", psiFile) - { - @Override - protected void run(Result result) throws Throwable - { - boolean isInsideManagedDependencies; + XmlFile psiFile = DomUtil.getFile(mavenModel); + return new WriteCommandAction(psiFile.getProject(), "Generate Dependency", psiFile) { + @Override + @RequiredReadAction + protected void run(Result result) throws Throwable { + MavenDomDependencyManagement dependencyManagement = mavenModel.getDependencyManagement(); + XmlElement managedDependencyXml = dependencyManagement.getXmlElement(); + boolean isInsideManagedDependencies = managedDependencyXml != null + && managedDependencyXml.getTextRange().contains(editor.getCaretModel().getOffset()); - MavenDomDependencyManagement dependencyManagement = mavenModel.getDependencyManagement(); - XmlElement managedDependencyXml = dependencyManagement.getXmlElement(); - if(managedDependencyXml != null && managedDependencyXml.getTextRange().contains(editor.getCaretModel().getOffset())) - { - isInsideManagedDependencies = true; - } - else - { - isInsideManagedDependencies = false; - } + for (MavenId each : ids) { + MavenDomDependency res; + if (isInsideManagedDependencies) { + res = MavenDomUtil.createDomDependency(dependencyManagement.getDependencies(), editor, each); + } + else { + DependencyConflictId conflictId = + new DependencyConflictId(each.getGroupId(), each.getArtifactId(), null, null); + MavenDomDependency managedDependenciesDom = managedDependencies.get(conflictId); - for(MavenId each : ids) - { - MavenDomDependency res; - if(isInsideManagedDependencies) - { - res = MavenDomUtil.createDomDependency(dependencyManagement.getDependencies(), editor, each); - } - else - { - DependencyConflictId conflictId = new DependencyConflictId(each.getGroupId(), each.getArtifactId(), null, null); - MavenDomDependency managedDependenciesDom = managedDependencies.get(conflictId); + if (managedDependenciesDom != null + && Comparing.equal(each.getVersion(), managedDependenciesDom.getVersion().getStringValue())) { + // Generate dependency without tag + res = MavenDomUtil.createDomDependency(mavenModel.getDependencies(), editor); - if(managedDependenciesDom != null && Comparing.equal(each.getVersion(), managedDependenciesDom.getVersion() - .getStringValue())) - { - // Generate dependency without tag - res = MavenDomUtil.createDomDependency(mavenModel.getDependencies(), editor); + res.getGroupId().setStringValue(conflictId.getGroupId()); + res.getArtifactId().setStringValue(conflictId.getArtifactId()); + } + else { + res = MavenDomUtil.createDomDependency(mavenModel.getDependencies(), editor, each); + } + } + result.setResult(res); + } + } + }.execute().getResultObject(); + } + }, AllIcons.Nodes.PpLib); + } - res.getGroupId().setStringValue(conflictId.getGroupId()); - res.getArtifactId().setStringValue(conflictId.getArtifactId()); - } - else - { - res = MavenDomUtil.createDomDependency(mavenModel.getDependencies(), editor, each); - } - } - result.setResult(res); - } - } - }.execute().getResultObject(); - } - }, AllIcons.Nodes.PpLib); - } - - @Override - protected boolean startInWriteAction() - { - return false; - } + @Override + protected boolean startInWriteAction() { + return false; + } } diff --git a/plugin/src/main/java/org/jetbrains/idea/maven/dom/generate/GenerateDependencyUtil.java b/plugin/src/main/java/org/jetbrains/idea/maven/dom/generate/GenerateDependencyUtil.java index 5e6ec39c..eced4996 100644 --- a/plugin/src/main/java/org/jetbrains/idea/maven/dom/generate/GenerateDependencyUtil.java +++ b/plugin/src/main/java/org/jetbrains/idea/maven/dom/generate/GenerateDependencyUtil.java @@ -15,6 +15,7 @@ */ package org.jetbrains.idea.maven.dom.generate; +import consulo.annotation.access.RequiredReadAction; import consulo.application.AllIcons; import consulo.ide.impl.idea.ide.util.MemberChooser; import consulo.language.editor.generation.ClassMember; @@ -22,11 +23,11 @@ import consulo.language.editor.generation.MemberChooserObjectBase; import consulo.language.editor.generation.PsiElementMemberChooserObject; import consulo.language.psi.PsiFile; +import consulo.maven.icon.MavenIconGroup; import consulo.project.Project; +import consulo.ui.annotation.RequiredUIAccess; import consulo.util.collection.ContainerUtil; import consulo.util.lang.StringUtil; -import org.jetbrains.idea.maven.MavenIcons; -import org.jetbrains.idea.maven.dom.MavenDomBundle; import org.jetbrains.idea.maven.dom.model.MavenDomDependency; import org.jetbrains.idea.maven.dom.model.MavenDomProjectModel; import org.jetbrains.idea.maven.localize.MavenDomLocalize; @@ -40,118 +41,104 @@ /** * @author Serega.Vasiliev */ -public class GenerateDependencyUtil -{ - private GenerateDependencyUtil() - { - } - - @Nonnull - public static List chooseDependencies(Collection candidates, final Project project) - { - List dependencies = new ArrayList(); - - MavenDomProjectModelMember[] memberCandidates = - ContainerUtil.map2Array(candidates, MavenDomProjectModelMember.class, dependency -> new MavenDomProjectModelMember(dependency)); - MemberChooser chooser = - new MemberChooser(memberCandidates, true, true, project) - { - protected ShowContainersAction getShowContainersAction() - { - return new ShowContainersAction(MavenDomLocalize.chooserShowProjectFiles(), MavenIcons.MavenProject); - } - - protected String getAllContainersNodeName() - { - return MavenDomBundle.message("all.dependencies"); - } - }; - - chooser.setTitle(MavenDomBundle.message("dependencies.chooser.title")); - chooser.setCopyJavadocVisible(false); - chooser.show(); - - if(chooser.getExitCode() == MemberChooser.OK_EXIT_CODE) - { - final MavenDomProjectModelMember[] members = chooser.getSelectedElements(new MavenDomProjectModelMember[0]); - if(members != null) - { - dependencies.addAll(ContainerUtil.mapNotNull(members, mavenDomProjectModelMember -> mavenDomProjectModelMember.getDependency())); - } - } - - return dependencies; - } - - private static class MavenDomProjectModelMember extends MemberChooserObjectBase implements ClassMember - { - private final MavenDomDependency myDependency; - - public MavenDomProjectModelMember(final MavenDomDependency dependency) - { - super(dependency.toString(), AllIcons.Nodes.PpLib); - myDependency = dependency; - } - - @Override - public String getText() - { - StringBuffer sb = new StringBuffer(); - - append(sb, myDependency.getGroupId().getStringValue()); - append(sb, myDependency.getArtifactId().getStringValue()); - append(sb, myDependency.getVersion().getStringValue()); - - return sb.toString(); - } - - private static void append(StringBuffer sb, String str) - { - if(!StringUtil.isEmptyOrSpaces(str)) - { - if(sb.length() > 0) - { - sb.append(": "); - } - sb.append(str); - } - } - - public MemberChooserObject getParentNodeDelegate() - { - MavenDomDependency dependency = getDependency(); - - return new MavenDomProjectModelFileMemberChooserObjectBase(dependency.getXmlTag().getContainingFile(), - getProjectName(dependency)); - } - - @Nullable - private static String getProjectName(@Nullable MavenDomDependency dependency) - { - if(dependency != null) - { - MavenDomProjectModel model = dependency.getParentOfType(MavenDomProjectModel.class, false); - if(model != null) - { - String name = model.getName().getStringValue(); - return StringUtil.isEmptyOrSpaces(name) ? model.getArtifactId().getStringValue() : name; - } - } - return null; - } - - public MavenDomDependency getDependency() - { - return myDependency; - } - - private static class MavenDomProjectModelFileMemberChooserObjectBase extends PsiElementMemberChooserObject - { - - public MavenDomProjectModelFileMemberChooserObjectBase(@Nonnull final PsiFile psiFile, @Nullable String projectName) - { - super(psiFile, StringUtil.isEmptyOrSpaces(projectName) ? psiFile.getName() : projectName, MavenIcons.MavenProject); - } - } - } +public class GenerateDependencyUtil { + private GenerateDependencyUtil() { + } + + @Nonnull + @RequiredUIAccess + public static List chooseDependencies(Collection candidates, final Project project) { + List dependencies = new ArrayList<>(); + + MavenDomProjectModelMember[] memberCandidates = + ContainerUtil.map2Array(candidates, MavenDomProjectModelMember.class, MavenDomProjectModelMember::new); + MemberChooser chooser = + new MemberChooser<>(memberCandidates, true, true, project) { + @Override + protected ShowContainersAction getShowContainersAction() { + return new ShowContainersAction(MavenDomLocalize.chooserShowProjectFiles(), MavenIconGroup.mavenlogo()); + } + + @Override + protected String getAllContainersNodeName() { + return MavenDomLocalize.allDependencies().get(); + } + }; + + chooser.setTitle(MavenDomLocalize.dependenciesChooserTitle()); + chooser.setCopyJavadocVisible(false); + chooser.show(); + + if (chooser.getExitCode() == MemberChooser.OK_EXIT_CODE) { + final MavenDomProjectModelMember[] members = chooser.getSelectedElements(new MavenDomProjectModelMember[0]); + if (members != null) { + dependencies.addAll(ContainerUtil.mapNotNull(members, MavenDomProjectModelMember::getDependency)); + } + } + + return dependencies; + } + + private static class MavenDomProjectModelMember extends MemberChooserObjectBase implements ClassMember { + private final MavenDomDependency myDependency; + + public MavenDomProjectModelMember(final MavenDomDependency dependency) { + super(dependency.toString(), AllIcons.Nodes.PpLib); + myDependency = dependency; + } + + @Override + public String getText() { + StringBuffer sb = new StringBuffer(); + + append(sb, myDependency.getGroupId().getStringValue()); + append(sb, myDependency.getArtifactId().getStringValue()); + append(sb, myDependency.getVersion().getStringValue()); + + return sb.toString(); + } + + private static void append(StringBuffer sb, String str) { + if (!StringUtil.isEmptyOrSpaces(str)) { + if (sb.length() > 0) { + sb.append(": "); + } + sb.append(str); + } + } + + @Override + @RequiredReadAction + public MemberChooserObject getParentNodeDelegate() { + MavenDomDependency dependency = getDependency(); + + return new MavenDomProjectModelFileMemberChooserObjectBase( + dependency.getXmlTag().getContainingFile(), + getProjectName(dependency) + ); + } + + @Nullable + private static String getProjectName(@Nullable MavenDomDependency dependency) { + if (dependency != null) { + MavenDomProjectModel model = dependency.getParentOfType(MavenDomProjectModel.class, false); + if (model != null) { + String name = model.getName().getStringValue(); + return StringUtil.isEmptyOrSpaces(name) ? model.getArtifactId().getStringValue() : name; + } + } + return null; + } + + public MavenDomDependency getDependency() { + return myDependency; + } + + private static class MavenDomProjectModelFileMemberChooserObjectBase extends PsiElementMemberChooserObject { + @RequiredReadAction + public MavenDomProjectModelFileMemberChooserObjectBase(@Nonnull final PsiFile psiFile, @Nullable String projectName) { + super(psiFile, StringUtil.isEmptyOrSpaces(projectName) ? psiFile.getName() : projectName, MavenIconGroup.mavenlogo()); + } + } + } } diff --git a/plugin/src/main/java/org/jetbrains/idea/maven/dom/generate/GenerateManagedDependencyAction.java b/plugin/src/main/java/org/jetbrains/idea/maven/dom/generate/GenerateManagedDependencyAction.java index c325dd55..47540764 100644 --- a/plugin/src/main/java/org/jetbrains/idea/maven/dom/generate/GenerateManagedDependencyAction.java +++ b/plugin/src/main/java/org/jetbrains/idea/maven/dom/generate/GenerateManagedDependencyAction.java @@ -19,124 +19,107 @@ import com.google.common.collect.Maps; import consulo.application.AllIcons; import consulo.application.Result; +import consulo.application.util.function.Processor; import consulo.codeEditor.Editor; import consulo.language.editor.WriteCommandAction; -import consulo.application.util.function.Processor; +import consulo.ui.annotation.RequiredUIAccess; import consulo.util.lang.StringUtil; import consulo.xml.util.xml.ui.actions.generate.GenerateDomElementAction; import org.jetbrains.idea.maven.dom.DependencyConflictId; -import org.jetbrains.idea.maven.dom.MavenDomBundle; import org.jetbrains.idea.maven.dom.MavenDomProjectProcessorUtils; 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 javax.annotation.Nonnull; import java.util.*; -public class GenerateManagedDependencyAction extends GenerateDomElementAction -{ - public GenerateManagedDependencyAction() - { - super(new MavenOverridingDependencyGenerateProvider(), AllIcons.Nodes.PpLib); - } - - @Override - protected boolean startInWriteAction() - { - return false; - } - - private static class MavenOverridingDependencyGenerateProvider extends MavenGenerateProvider - { - public MavenOverridingDependencyGenerateProvider() - { - super(MavenDomBundle.message("generate.managed.dependency"), MavenDomDependency.class); - } - - @Override - protected MavenDomDependency doGenerate(@Nonnull final MavenDomProjectModel mavenModel, final Editor editor) - { - Set existingDependencies = collectExistingDependencies(mavenModel); - Map managingDependencies = collectManagingDependencies(mavenModel); - - Map unexistManagingDeps = Maps.filterKeys(managingDependencies, - Predicates.not(Predicates.in(existingDependencies))); - - final List dependenciesToOverride = GenerateDependencyUtil.chooseDependencies(unexistManagingDeps.values(), - mavenModel.getManager().getProject()); - - if(!dependenciesToOverride.isEmpty()) - { - return new WriteCommandAction(editor.getProject(), mavenModel.getXmlTag().getContainingFile()) - { - @Override - protected void run(Result result) throws Throwable - { - for(MavenDomDependency parentDependency : dependenciesToOverride) - { - String groupId = parentDependency.getGroupId().getStringValue(); - String artifactId = parentDependency.getArtifactId().getStringValue(); - - if(!StringUtil.isEmptyOrSpaces(groupId) && !StringUtil.isEmptyOrSpaces(artifactId)) - { - MavenDomDependency dependency = MavenDomUtil.createDomDependency(mavenModel, editor); - - dependency.getGroupId().setStringValue(groupId); - dependency.getArtifactId().setStringValue(artifactId); - String typeValue = parentDependency.getType().getStringValue(); - - if(!StringUtil.isEmptyOrSpaces(typeValue)) - { - dependency.getType().setStringValue(typeValue); - } - dependency.getVersion().undefine(); - } - } - } - }.execute().getResultObject(); - } - - return null; - } - } - - private static Set collectExistingDependencies(@Nonnull final MavenDomProjectModel model) - { - final Set existingDependencies = new HashSet(); - for(MavenDomDependency dependency : model.getDependencies().getDependencies()) - { - DependencyConflictId id = DependencyConflictId.create(dependency); - if(id != null) - { - existingDependencies.add(id); - } - } - - return existingDependencies; - } - - @Nonnull - public static Map collectManagingDependencies(@Nonnull final MavenDomProjectModel model) - { - final Map dependencies = new HashMap(); - - Processor collectProcessor = new Processor() - { - public boolean process(MavenDomDependency dependency) - { - DependencyConflictId id = DependencyConflictId.create(dependency); - if(id != null && !dependencies.containsKey(id)) - { - dependencies.put(id, dependency); - } - - return false; - } - }; - - MavenDomProjectProcessorUtils.processDependenciesInDependencyManagement(model, collectProcessor, model.getManager().getProject()); - - return dependencies; - } +public class GenerateManagedDependencyAction extends GenerateDomElementAction { + public GenerateManagedDependencyAction() { + super(new MavenOverridingDependencyGenerateProvider(), AllIcons.Nodes.PpLib); + } + + @Override + protected boolean startInWriteAction() { + return false; + } + + private static class MavenOverridingDependencyGenerateProvider extends MavenGenerateProvider { + public MavenOverridingDependencyGenerateProvider() { + super(MavenDomLocalize.generateManagedDependency().get(), MavenDomDependency.class); + } + + @Override + @RequiredUIAccess + protected MavenDomDependency doGenerate(@Nonnull final MavenDomProjectModel mavenModel, final Editor editor) { + Set existingDependencies = collectExistingDependencies(mavenModel); + Map managingDependencies = collectManagingDependencies(mavenModel); + + Map unexistManagingDeps = Maps.filterKeys( + managingDependencies, + Predicates.not(Predicates.in(existingDependencies)) + ); + + final List dependenciesToOverride = + GenerateDependencyUtil.chooseDependencies(unexistManagingDeps.values(), mavenModel.getManager().getProject()); + + if (!dependenciesToOverride.isEmpty()) { + return new WriteCommandAction(editor.getProject(), mavenModel.getXmlTag().getContainingFile()) { + @Override + protected void run(Result result) throws Throwable { + for (MavenDomDependency parentDependency : dependenciesToOverride) { + String groupId = parentDependency.getGroupId().getStringValue(); + String artifactId = parentDependency.getArtifactId().getStringValue(); + + if (!StringUtil.isEmptyOrSpaces(groupId) && !StringUtil.isEmptyOrSpaces(artifactId)) { + MavenDomDependency dependency = MavenDomUtil.createDomDependency(mavenModel, editor); + + dependency.getGroupId().setStringValue(groupId); + dependency.getArtifactId().setStringValue(artifactId); + String typeValue = parentDependency.getType().getStringValue(); + + if (!StringUtil.isEmptyOrSpaces(typeValue)) { + dependency.getType().setStringValue(typeValue); + } + dependency.getVersion().undefine(); + } + } + } + }.execute().getResultObject(); + } + + return null; + } + } + + private static Set collectExistingDependencies(@Nonnull final MavenDomProjectModel model) { + final Set existingDependencies = new HashSet<>(); + for (MavenDomDependency dependency : model.getDependencies().getDependencies()) { + DependencyConflictId id = DependencyConflictId.create(dependency); + if (id != null) { + existingDependencies.add(id); + } + } + + return existingDependencies; + } + + @Nonnull + public static Map collectManagingDependencies(@Nonnull final MavenDomProjectModel model) { + final Map dependencies = new HashMap<>(); + + Processor collectProcessor = dependency -> { + DependencyConflictId id = DependencyConflictId.create(dependency); + if (id != null && !dependencies.containsKey(id)) { + dependencies.put(id, dependency); + } + + return false; + }; + + MavenDomProjectProcessorUtils.processDependenciesInDependencyManagement(model, collectProcessor, model.getManager().getProject()); + + return dependencies; + } } diff --git a/plugin/src/main/java/org/jetbrains/idea/maven/dom/generate/GenerateParentAction.java b/plugin/src/main/java/org/jetbrains/idea/maven/dom/generate/GenerateParentAction.java index 92dfa70f..51e7e5e0 100644 --- a/plugin/src/main/java/org/jetbrains/idea/maven/dom/generate/GenerateParentAction.java +++ b/plugin/src/main/java/org/jetbrains/idea/maven/dom/generate/GenerateParentAction.java @@ -15,47 +15,60 @@ */ package org.jetbrains.idea.maven.dom.generate; +import consulo.annotation.access.RequiredWriteAction; import consulo.application.Result; import consulo.codeEditor.Editor; import consulo.language.editor.WriteCommandAction; +import consulo.maven.icon.MavenIconGroup; +import consulo.ui.annotation.RequiredUIAccess; import consulo.xml.util.xml.DomUtil; import consulo.xml.util.xml.ui.actions.generate.GenerateDomElementAction; -import org.jetbrains.idea.maven.MavenIcons; -import org.jetbrains.idea.maven.dom.MavenDomBundle; import org.jetbrains.idea.maven.dom.MavenDomUtil; import org.jetbrains.idea.maven.dom.model.MavenDomParent; import org.jetbrains.idea.maven.dom.model.MavenDomProjectModel; +import org.jetbrains.idea.maven.localize.MavenDomLocalize; import org.jetbrains.idea.maven.navigator.SelectMavenProjectDialog; import org.jetbrains.idea.maven.project.MavenProject; import javax.annotation.Nonnull; public class GenerateParentAction extends GenerateDomElementAction { - public GenerateParentAction() { - super(new MavenGenerateProvider(MavenDomBundle.message("generate.parent"), MavenDomParent.class) { - protected MavenDomParent doGenerate(@Nonnull final MavenDomProjectModel mavenModel, Editor editor) { - SelectMavenProjectDialog d = new SelectMavenProjectDialog(editor.getProject(), null); - d.show(); - if (!d.isOK()) return null; - final MavenProject parentProject = d.getResult(); - if (parentProject == null) return null; + public GenerateParentAction() { + super( + new MavenGenerateProvider<>(MavenDomLocalize.generateParent().get(), MavenDomParent.class) { + @Override + @RequiredUIAccess + protected MavenDomParent doGenerate(@Nonnull final MavenDomProjectModel mavenModel, Editor editor) { + SelectMavenProjectDialog d = new SelectMavenProjectDialog(editor.getProject(), null); + d.show(); + if (!d.isOK()) { + return null; + } + final MavenProject parentProject = d.getResult(); + if (parentProject == null) { + return null; + } - return new WriteCommandAction(editor.getProject(), getDescription()) { - protected void run(Result result) throws Throwable { - result.setResult(MavenDomUtil.updateMavenParent(mavenModel, parentProject)); - } - }.execute().getResultObject(); - } + return new WriteCommandAction(editor.getProject(), getDescription()) { + @Override + @RequiredWriteAction + protected void run(Result result) throws Throwable { + result.setResult(MavenDomUtil.updateMavenParent(mavenModel, parentProject)); + } + }.execute().getResultObject(); + } - @Override - protected boolean isAvailableForModel(MavenDomProjectModel mavenModel) { - return !DomUtil.hasXml(mavenModel.getMavenParent()); - } - }, MavenIcons.MavenProject); - } + @Override + protected boolean isAvailableForModel(MavenDomProjectModel mavenModel) { + return !DomUtil.hasXml(mavenModel.getMavenParent()); + } + }, + MavenIconGroup.mavenlogo() + ); + } - @Override - protected boolean startInWriteAction() { - return false; - } + @Override + protected boolean startInWriteAction() { + return false; + } } diff --git a/plugin/src/main/java/org/jetbrains/idea/maven/dom/generate/MavenGenerateDomActionGroup.java b/plugin/src/main/java/org/jetbrains/idea/maven/dom/generate/MavenGenerateDomActionGroup.java index a99ae40b..79d4ffb1 100644 --- a/plugin/src/main/java/org/jetbrains/idea/maven/dom/generate/MavenGenerateDomActionGroup.java +++ b/plugin/src/main/java/org/jetbrains/idea/maven/dom/generate/MavenGenerateDomActionGroup.java @@ -17,42 +17,49 @@ import consulo.ui.ex.action.DefaultActionGroup; import consulo.xml.util.xml.DomElement; -import org.jetbrains.annotations.NonNls; -import org.jetbrains.idea.maven.dom.MavenDomBundle; -import org.jetbrains.idea.maven.dom.model.MavenDomDependency; -import org.jetbrains.idea.maven.dom.model.MavenDomPlugin; -import org.jetbrains.idea.maven.dom.model.MavenDomProjectModel; -import org.jetbrains.idea.maven.dom.model.MavenDomRepository; +import org.jetbrains.idea.maven.dom.model.*; +import org.jetbrains.idea.maven.localize.MavenDomLocalize; import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.util.function.Function; -public class MavenGenerateDomActionGroup extends DefaultActionGroup -{ - public MavenGenerateDomActionGroup() - { - add(new GenerateDependencyAction()); - add(new GenerateManagedDependencyAction()); +public class MavenGenerateDomActionGroup extends DefaultActionGroup { + public MavenGenerateDomActionGroup() { + addAction(new GenerateDependencyAction()); + addAction(new GenerateManagedDependencyAction()); - addSeparator(); - add(createAction(MavenDomBundle.message("generate.dependency.template"), MavenDomDependency.class, "maven-dependency", - mavenDomProjectModel -> mavenDomProjectModel.getDependencies())); - add(createAction(MavenDomBundle.message("generate.plugin.template"), MavenDomPlugin.class, "maven-plugin", - mavenDomProjectModel -> mavenDomProjectModel.getBuild().getPlugins())); + addSeparator(); + addAction(createAction( + MavenDomLocalize.generateDependencyTemplate().get(), + MavenDomDependency.class, + "maven-dependency", + MavenDomProjectModelBase::getDependencies + )); + addAction(createAction( + MavenDomLocalize.generatePluginTemplate().get(), + MavenDomPlugin.class, + "maven-plugin", + mavenDomProjectModel -> mavenDomProjectModel.getBuild().getPlugins() + )); - add(createAction(MavenDomBundle.message("generate.repository.template"), MavenDomRepository.class, "maven-repository", - mavenDomProjectModel -> mavenDomProjectModel.getRepositories())); + addAction(createAction( + MavenDomLocalize.generateRepositoryTemplate().get(), + MavenDomRepository.class, + "maven-repository", + MavenDomProjectModelBase::getRepositories + )); - addSeparator(); - add(new GenerateParentAction()); - } + addSeparator(); + addAction(new GenerateParentAction()); + } - private static MavenGenerateTemplateAction createAction(String actionDescription, - final Class aClass, - @NonNls @Nullable String mappingId, - @Nonnull Function parentFunction) - { - return new MavenGenerateTemplateAction(actionDescription, aClass, mappingId, parentFunction); - } + private static MavenGenerateTemplateAction createAction( + String actionDescription, + final Class aClass, + @Nullable String mappingId, + @Nonnull Function parentFunction + ) { + return new MavenGenerateTemplateAction(actionDescription, aClass, mappingId, parentFunction); + } } \ No newline at end of file diff --git a/plugin/src/main/java/org/jetbrains/idea/maven/dom/generate/MavenGenerateDomElementProvider.java b/plugin/src/main/java/org/jetbrains/idea/maven/dom/generate/MavenGenerateDomElementProvider.java index fb893069..2f8c577d 100644 --- a/plugin/src/main/java/org/jetbrains/idea/maven/dom/generate/MavenGenerateDomElementProvider.java +++ b/plugin/src/main/java/org/jetbrains/idea/maven/dom/generate/MavenGenerateDomElementProvider.java @@ -29,19 +29,22 @@ * User: Sergey.Vasiliev */ public class MavenGenerateDomElementProvider extends AbstractDomGenerateProvider { - private final Function myParentFunction; + private final Function myParentFunction; - public MavenGenerateDomElementProvider(final String description, - final Class childElementClass, - String mappingId, - Function parentFunction) { - super(description, childElementClass, mappingId); - myParentFunction = parentFunction; - } + public MavenGenerateDomElementProvider( + final String description, + final Class childElementClass, + String mappingId, + Function parentFunction + ) { + super(description, childElementClass, mappingId); + myParentFunction = parentFunction; + } - protected DomElement getParentDomElement(final Project project, final Editor editor, final PsiFile file) { - MavenDomProjectModel domProjectModel = MavenDomUtil.getMavenDomModel(file, MavenDomProjectModel.class); + @Override + protected DomElement getParentDomElement(final Project project, final Editor editor, final PsiFile file) { + MavenDomProjectModel domProjectModel = MavenDomUtil.getMavenDomModel(file, MavenDomProjectModel.class); - return domProjectModel == null ? null : myParentFunction.apply(domProjectModel); - } + return domProjectModel == null ? null : myParentFunction.apply(domProjectModel); + } } \ No newline at end of file diff --git a/plugin/src/main/java/org/jetbrains/idea/maven/dom/generate/MavenGenerateProvider.java b/plugin/src/main/java/org/jetbrains/idea/maven/dom/generate/MavenGenerateProvider.java index 43c0bf96..201a9df1 100644 --- a/plugin/src/main/java/org/jetbrains/idea/maven/dom/generate/MavenGenerateProvider.java +++ b/plugin/src/main/java/org/jetbrains/idea/maven/dom/generate/MavenGenerateProvider.java @@ -27,33 +27,36 @@ import org.jetbrains.idea.maven.dom.model.MavenDomProjectModel; public abstract class MavenGenerateProvider extends AbstractDomGenerateProvider { - public MavenGenerateProvider(String description, Class clazz) { - super(description, clazz); - } - - protected DomElement getParentDomElement(Project project, Editor editor, PsiFile file) { - DomElement el = DomUtil.getContextElement(editor); - return DomUtil.getFileElement(el).getRootElement(); - } - - @Override - public ELEMENT_TYPE generate(@Nullable DomElement parent, Editor editor) { - if (parent == null) return null; - return doGenerate((MavenDomProjectModel)parent, editor); - } - - @Nullable - protected abstract ELEMENT_TYPE doGenerate(@Nonnull MavenDomProjectModel mavenModel, Editor editor); - - @Override - public boolean isAvailableForElement(@Nonnull DomElement el) { - DomElement root = DomUtil.getFileElement(el).getRootElement(); - return root.getModule() != null - && root instanceof MavenDomProjectModel - && isAvailableForModel((MavenDomProjectModel)root); - } - - protected boolean isAvailableForModel(MavenDomProjectModel mavenModel) { - return true; - } + public MavenGenerateProvider(String description, Class clazz) { + super(description, clazz); + } + + @Override + protected DomElement getParentDomElement(Project project, Editor editor, PsiFile file) { + DomElement el = DomUtil.getContextElement(editor); + return DomUtil.getFileElement(el).getRootElement(); + } + + @Override + public ELEMENT_TYPE generate(@Nullable DomElement parent, Editor editor) { + if (parent == null) { + return null; + } + return doGenerate((MavenDomProjectModel)parent, editor); + } + + @Nullable + protected abstract ELEMENT_TYPE doGenerate(@Nonnull MavenDomProjectModel mavenModel, Editor editor); + + @Override + public boolean isAvailableForElement(@Nonnull DomElement el) { + DomElement root = DomUtil.getFileElement(el).getRootElement(); + return root.getModule() != null + && root instanceof MavenDomProjectModel domProjectModel + && isAvailableForModel(domProjectModel); + } + + protected boolean isAvailableForModel(MavenDomProjectModel mavenModel) { + return true; + } } diff --git a/plugin/src/main/java/org/jetbrains/idea/maven/dom/generate/MavenGenerateTemplateAction.java b/plugin/src/main/java/org/jetbrains/idea/maven/dom/generate/MavenGenerateTemplateAction.java index f2452f99..98c39ad2 100644 --- a/plugin/src/main/java/org/jetbrains/idea/maven/dom/generate/MavenGenerateTemplateAction.java +++ b/plugin/src/main/java/org/jetbrains/idea/maven/dom/generate/MavenGenerateTemplateAction.java @@ -18,16 +18,19 @@ * User: Sergey.Vasiliev */ public class MavenGenerateTemplateAction extends GenerateDomElementAction { - public MavenGenerateTemplateAction(@Nonnull final String description, - @Nonnull final Class childElementClass, - @Nullable final String mappingId, - @Nonnull Function parentFunction) { - super(new MavenGenerateDomElementProvider(description, childElementClass, mappingId, parentFunction)); + public MavenGenerateTemplateAction( + @Nonnull final String description, + @Nonnull final Class childElementClass, + @Nullable final String mappingId, + @Nonnull Function parentFunction + ) { + super(new MavenGenerateDomElementProvider(description, childElementClass, mappingId, parentFunction)); - getTemplatePresentation().setIcon(ElementPresentationManager.getIconForClass(childElementClass)); - } + getTemplatePresentation().setIcon(ElementPresentationManager.getIconForClass(childElementClass)); + } - protected boolean isValidForFile(@Nonnull Project project, @Nonnull Editor editor, @Nonnull PsiFile file) { - return file instanceof XmlFile && MavenDomUtil.getMavenDomModel(file, MavenDomProjectModel.class) != null; - } + @Override + protected boolean isValidForFile(@Nonnull Project project, @Nonnull Editor editor, @Nonnull PsiFile file) { + return file instanceof XmlFile && MavenDomUtil.getMavenDomModel(file, MavenDomProjectModel.class) != null; + } } \ No newline at end of file diff --git a/plugin/src/main/java/org/jetbrains/idea/maven/dom/inspections/MavenDuplicateDependenciesInspection.java b/plugin/src/main/java/org/jetbrains/idea/maven/dom/inspections/MavenDuplicateDependenciesInspection.java index 29eb4e40..825a0a97 100644 --- a/plugin/src/main/java/org/jetbrains/idea/maven/dom/inspections/MavenDuplicateDependenciesInspection.java +++ b/plugin/src/main/java/org/jetbrains/idea/maven/dom/inspections/MavenDuplicateDependenciesInspection.java @@ -15,6 +15,7 @@ */ package org.jetbrains.idea.maven.dom.inspections; +import consulo.annotation.access.RequiredReadAction; import consulo.annotation.component.ExtensionImpl; import consulo.application.util.function.Processor; import consulo.language.editor.annotation.HighlightSeverity; @@ -26,11 +27,11 @@ import consulo.xml.util.xml.DomFileElement; import consulo.xml.util.xml.highlighting.BasicDomElementsInspection; import consulo.xml.util.xml.highlighting.DomElementAnnotationHolder; -import org.jetbrains.idea.maven.dom.MavenDomBundle; import org.jetbrains.idea.maven.dom.MavenDomProjectProcessorUtils; 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 javax.annotation.Nonnull; @@ -39,174 +40,204 @@ @ExtensionImpl public class MavenDuplicateDependenciesInspection extends BasicDomElementsInspection { - public MavenDuplicateDependenciesInspection() { - super(MavenDomProjectModel.class); - } - - @Override - public void checkFileElement(DomFileElement domFileElement, - DomElementAnnotationHolder holder, - Object state) { - MavenDomProjectModel projectModel = domFileElement.getRootElement(); + public MavenDuplicateDependenciesInspection() { + super(MavenDomProjectModel.class); + } - checkMavenProjectModel(projectModel, holder); - } + @Override + @RequiredReadAction + public void checkFileElement( + DomFileElement domFileElement, + DomElementAnnotationHolder holder, + Object state + ) { + MavenDomProjectModel projectModel = domFileElement.getRootElement(); - private static void checkMavenProjectModel(@Nonnull MavenDomProjectModel projectModel, - @Nonnull DomElementAnnotationHolder holder) { - final Map> allDuplicates = getDuplicateDependenciesMap(projectModel); + checkMavenProjectModel(projectModel, holder); + } - for (MavenDomDependency dependency : projectModel.getDependencies().getDependencies()) { - String id = createId(dependency); - if (id != null) { - Set dependencies = allDuplicates.get(id); - if (dependencies != null && dependencies.size() > 1) { + @RequiredReadAction + private static void checkMavenProjectModel( + @Nonnull MavenDomProjectModel projectModel, + @Nonnull DomElementAnnotationHolder holder + ) { + final Map> allDuplicates = getDuplicateDependenciesMap(projectModel); + + for (MavenDomDependency dependency : projectModel.getDependencies().getDependencies()) { + String id = createId(dependency); + if (id != null) { + Set dependencies = allDuplicates.get(id); + if (dependencies != null && dependencies.size() > 1) { + + List duplicatedDependencies = new ArrayList<>(); + + for (MavenDomDependency d : dependencies) { + if (d == dependency) { + continue; + } + + if (d.getParent() == dependency.getParent()) { + duplicatedDependencies.add(d); // Dependencies in same file must be unique by groupId:artifactId:type:classifier + } + else { + if (scope(d).equals(scope(dependency)) + && Comparing.equal(d.getVersion().getStringValue(), dependency.getVersion().getStringValue())) { + // Dependencies in same file must be unique by groupId:artifactId:VERSION:type:classifier:SCOPE + duplicatedDependencies.add(d); + } + } + } + + if (duplicatedDependencies.size() > 0) { + addProblem(dependency, duplicatedDependencies, holder); + } + } + } + } + } - List duplicatedDependencies = new ArrayList(); + private static String scope(MavenDomDependency dependency) { + String res = dependency.getScope().getRawText(); + if (StringUtil.isEmpty(res)) { + return "compile"; + } - for (MavenDomDependency d : dependencies) { - if (d == dependency) continue; + return res; + } - if (d.getParent() == dependency.getParent()) { - duplicatedDependencies.add(d); // Dependencies in same file must be unique by groupId:artifactId:type:classifier + @RequiredReadAction + private static void addProblem( + @Nonnull MavenDomDependency dependency, + @Nonnull Collection dependencies, + @Nonnull DomElementAnnotationHolder holder + ) { + StringBuilder sb = new StringBuilder(); + Set processed = new HashSet<>(); + for (MavenDomDependency domDependency : dependencies) { + if (dependency.equals(domDependency)) { + continue; } - else { - if (scope(d).equals(scope(dependency)) - && Comparing.equal(d.getVersion().getStringValue(), dependency.getVersion().getStringValue())) { - duplicatedDependencies.add(d); // Dependencies in same file must be unique by groupId:artifactId:VERSION:type:classifier:SCOPE - } + MavenDomProjectModel model = domDependency.getParentOfType(MavenDomProjectModel.class, false); + if (model != null && !processed.contains(model)) { + if (processed.size() > 0) { + sb.append(", "); + } + sb.append(createLinkText(model, domDependency)); + + processed.add(model); } - } - - if (duplicatedDependencies.size() > 0) { - addProblem(dependency, duplicatedDependencies, holder); - } } - } - } - } - - private static String scope(MavenDomDependency dependency) { - String res = dependency.getScope().getRawText(); - if (StringUtil.isEmpty(res)) return "compile"; - - return res; - } - - private static void addProblem(@Nonnull MavenDomDependency dependency, - @Nonnull Collection dependencies, - @Nonnull DomElementAnnotationHolder holder) { - StringBuilder sb = new StringBuilder(); - Set processed = new HashSet(); - for (MavenDomDependency domDependency : dependencies) { - if (dependency.equals(domDependency)) continue; - MavenDomProjectModel model = domDependency.getParentOfType(MavenDomProjectModel.class, false); - if (model != null && !processed.contains(model)) { - if (processed.size() > 0) sb.append(", "); - sb.append(createLinkText(model, domDependency)); - - processed.add(model); - } - } - holder.createProblem(dependency, HighlightSeverity.WARNING, - MavenDomBundle.message("MavenDuplicateDependenciesInspection.has.duplicates", sb.toString())); - } - - private static String createLinkText(@Nonnull MavenDomProjectModel model, @Nonnull MavenDomDependency dependency) { - StringBuilder sb = new StringBuilder(); - - XmlTag tag = dependency.getXmlTag(); - if (tag == null) return getProjectName(model); - VirtualFile file = tag.getContainingFile().getVirtualFile(); - if (file == null) return getProjectName(model); - - sb.append(""); - sb.append(getProjectName(model)); - sb.append(""); - - return sb.toString(); - } - - @Nonnull - private static String getProjectName(MavenDomProjectModel model) { - MavenProject mavenProject = MavenDomUtil.findProject(model); - if (mavenProject != null) { - return mavenProject.getDisplayName(); + holder.createProblem( + dependency, + HighlightSeverity.WARNING, + MavenDomLocalize.mavenduplicatedependenciesinspectionHasDuplicates(sb.toString()).get() + ); } - else { - String name = model.getName().getStringValue(); - if (!StringUtil.isEmptyOrSpaces(name)) { - return name; - } - else { - return "pom.xml"; // ? - } + + @RequiredReadAction + private static String createLinkText(@Nonnull MavenDomProjectModel model, @Nonnull MavenDomDependency dependency) { + StringBuilder sb = new StringBuilder(); + + XmlTag tag = dependency.getXmlTag(); + if (tag == null) { + return getProjectName(model); + } + VirtualFile file = tag.getContainingFile().getVirtualFile(); + if (file == null) { + return getProjectName(model); + } + + sb.append(""); + sb.append(getProjectName(model)); + sb.append(""); + + return sb.toString(); } - } - - @Nonnull - private static Map> getDuplicateDependenciesMap(MavenDomProjectModel projectModel) { - final Map> allDependencies = new HashMap>(); - - Processor collectProcessor = new Processor() { - public boolean process(MavenDomProjectModel model) { - for (MavenDomDependency dependency : model.getDependencies().getDependencies()) { - String mavenId = createId(dependency); - if (mavenId != null) { - if (allDependencies.containsKey(mavenId)) { - allDependencies.get(mavenId).add(dependency); + + @Nonnull + private static String getProjectName(MavenDomProjectModel model) { + MavenProject mavenProject = MavenDomUtil.findProject(model); + if (mavenProject != null) { + return mavenProject.getDisplayName(); + } + else { + String name = model.getName().getStringValue(); + if (!StringUtil.isEmptyOrSpaces(name)) { + return name; } else { - Set dependencies = new HashSet(); - dependencies.add(dependency); - allDependencies.put(mavenId, dependencies); + return "pom.xml"; // ? } - } } - return false; - } - }; + } - MavenDomProjectProcessorUtils.processChildrenRecursively(projectModel, collectProcessor, true); - MavenDomProjectProcessorUtils.processParentProjects(projectModel, collectProcessor); + @Nonnull + private static Map> getDuplicateDependenciesMap(MavenDomProjectModel projectModel) { + final Map> allDependencies = new HashMap<>(); + + Processor collectProcessor = model -> { + for (MavenDomDependency dependency : model.getDependencies().getDependencies()) { + String mavenId = createId(dependency); + if (mavenId != null) { + if (allDependencies.containsKey(mavenId)) { + allDependencies.get(mavenId).add(dependency); + } + else { + Set dependencies = new HashSet<>(); + dependencies.add(dependency); + allDependencies.put(mavenId, dependencies); + } + } + } + return false; + }; - return allDependencies; - } + MavenDomProjectProcessorUtils.processChildrenRecursively(projectModel, collectProcessor, true); + MavenDomProjectProcessorUtils.processParentProjects(projectModel, collectProcessor); - @Nullable - private static String createId(MavenDomDependency coordinates) { - String groupId = coordinates.getGroupId().getStringValue(); - String artifactId = coordinates.getArtifactId().getStringValue(); + return allDependencies; + } - if (StringUtil.isEmptyOrSpaces(groupId) || StringUtil.isEmptyOrSpaces(artifactId)) return null; + @Nullable + private static String createId(MavenDomDependency coordinates) { + String groupId = coordinates.getGroupId().getStringValue(); + String artifactId = coordinates.getArtifactId().getStringValue(); - String type = coordinates.getType().getStringValue(); - String classifier = coordinates.getClassifier().getStringValue(); + if (StringUtil.isEmptyOrSpaces(groupId) || StringUtil.isEmptyOrSpaces(artifactId)) { + return null; + } - return groupId + ":" + artifactId + ":" + type + ":" + classifier; - } + String type = coordinates.getType().getStringValue(); + String classifier = coordinates.getClassifier().getStringValue(); - @Nonnull - public String getGroupDisplayName() { - return MavenDomBundle.message("inspection.group"); - } + return groupId + ":" + artifactId + ":" + type + ":" + classifier; + } - @Nonnull - public String getDisplayName() { - return MavenDomBundle.message("inspection.duplicate.dependencies.name"); - } + @Nonnull + @Override + public String getGroupDisplayName() { + return MavenDomLocalize.inspectionGroup().get(); + } - @Nonnull - public String getShortName() { - return "MavenDuplicateDependenciesInspection"; - } + @Nonnull + @Override + public String getDisplayName() { + return MavenDomLocalize.inspectionDuplicateDependenciesName().get(); + } - @Nonnull - public HighlightDisplayLevel getDefaultLevel() { - return HighlightDisplayLevel.WARNING; - } + @Nonnull + @Override + public String getShortName() { + return "MavenDuplicateDependenciesInspection"; + } + + @Nonnull + @Override + public HighlightDisplayLevel getDefaultLevel() { + return HighlightDisplayLevel.WARNING; + } } \ No newline at end of file diff --git a/plugin/src/main/java/org/jetbrains/idea/maven/dom/inspections/MavenModelInspection.java b/plugin/src/main/java/org/jetbrains/idea/maven/dom/inspections/MavenModelInspection.java index c01dc1a8..f25fec3d 100644 --- a/plugin/src/main/java/org/jetbrains/idea/maven/dom/inspections/MavenModelInspection.java +++ b/plugin/src/main/java/org/jetbrains/idea/maven/dom/inspections/MavenModelInspection.java @@ -17,60 +17,54 @@ import consulo.annotation.component.ExtensionImpl; import consulo.virtualFileSystem.VirtualFile; -import consulo.xml.util.xml.Converter; import consulo.xml.util.xml.DomUtil; import consulo.xml.util.xml.GenericDomValue; import consulo.xml.util.xml.highlighting.BasicDomElementsInspection; -import org.jetbrains.idea.maven.dom.MavenDomBundle; import org.jetbrains.idea.maven.dom.converters.MavenDomSoftAwareConverter; import org.jetbrains.idea.maven.dom.model.MavenDomProjectModel; +import org.jetbrains.idea.maven.localize.MavenDomLocalize; import org.jetbrains.idea.maven.project.MavenProjectsManager; import javax.annotation.Nonnull; @ExtensionImpl public class MavenModelInspection extends BasicDomElementsInspection { - public MavenModelInspection() { - super(MavenDomProjectModel.class); - } - - @Nonnull - public String getGroupDisplayName() { - return MavenDomBundle.message("inspection.group"); - } + public MavenModelInspection() { + super(MavenDomProjectModel.class); + } - @Nonnull - public String getDisplayName() { - return MavenDomBundle.message("inspection.name"); - } + @Nonnull + @Override + public String getGroupDisplayName() { + return MavenDomLocalize.inspectionGroup().get(); + } - @Nonnull - public String getShortName() { - return "MavenModelInspection"; - } + @Nonnull + @Override + public String getDisplayName() { + return MavenDomLocalize.inspectionName().get(); + } - private static boolean isElementInsideManagedFile(GenericDomValue value) { - VirtualFile virtualFile = DomUtil.getFile(value).getVirtualFile(); - if (virtualFile == null) { - return false; + @Nonnull + @Override + public String getShortName() { + return "MavenModelInspection"; } - MavenProjectsManager projectsManager = MavenProjectsManager.getInstance(value.getManager().getProject()); + private static boolean isElementInsideManagedFile(GenericDomValue value) { + VirtualFile virtualFile = DomUtil.getFile(value).getVirtualFile(); + if (virtualFile == null) { + return false; + } - return projectsManager.findProject(virtualFile) != null; - } + MavenProjectsManager projectsManager = MavenProjectsManager.getInstance(value.getManager().getProject()); - @Override - protected boolean shouldCheckResolveProblems(GenericDomValue value) { - if (!isElementInsideManagedFile(value)) { - return false; + return projectsManager.findProject(virtualFile) != null; } - Converter converter = value.getConverter(); - if (converter instanceof MavenDomSoftAwareConverter) { - return !((MavenDomSoftAwareConverter)converter).isSoft(value); + @Override + protected boolean shouldCheckResolveProblems(GenericDomValue value) { + return isElementInsideManagedFile(value) + && !(value.getConverter() instanceof MavenDomSoftAwareConverter domSoftAwareConverter && domSoftAwareConverter.isSoft(value)); } - - return true; - } } \ No newline at end of file diff --git a/plugin/src/main/java/org/jetbrains/idea/maven/dom/inspections/MavenRedundantGroupIdInspection.java b/plugin/src/main/java/org/jetbrains/idea/maven/dom/inspections/MavenRedundantGroupIdInspection.java index bf478a68..3dd097cf 100644 --- a/plugin/src/main/java/org/jetbrains/idea/maven/dom/inspections/MavenRedundantGroupIdInspection.java +++ b/plugin/src/main/java/org/jetbrains/idea/maven/dom/inspections/MavenRedundantGroupIdInspection.java @@ -1,7 +1,7 @@ package org.jetbrains.idea.maven.dom.inspections; +import consulo.annotation.access.RequiredReadAction; import consulo.annotation.component.ExtensionImpl; -import consulo.application.ApplicationManager; import consulo.language.editor.FileModificationService; import consulo.language.editor.inspection.LocalQuickFix; import consulo.language.editor.inspection.LocalQuickFixBase; @@ -17,9 +17,9 @@ import consulo.xml.psi.xml.XmlTag; import consulo.xml.util.xml.DomFileElement; import consulo.xml.util.xml.DomManager; -import org.jetbrains.idea.maven.dom.MavenDomBundle; import org.jetbrains.idea.maven.dom.model.MavenDomParent; import org.jetbrains.idea.maven.dom.model.MavenDomProjectModel; +import org.jetbrains.idea.maven.localize.MavenDomLocalize; import javax.annotation.Nonnull; import javax.annotation.Nullable; @@ -28,80 +28,73 @@ * @author Sergey Evdokimov */ @ExtensionImpl -public class MavenRedundantGroupIdInspection extends XmlSuppressableInspectionTool -{ - @Nonnull - public String getGroupDisplayName() - { - return MavenDomBundle.message("inspection.group"); - } - - @Nonnull - public String getDisplayName() - { - return MavenDomBundle.message("inspection.redundant.groupId.name"); - } - - @Nonnull - public String getShortName() - { - return "MavenRedundantGroupId"; - } - - @Nonnull - public HighlightDisplayLevel getDefaultLevel() - { - return HighlightDisplayLevel.WARNING; - } - - @Nullable - public ProblemDescriptor[] checkFile(@Nonnull PsiFile file, @Nonnull InspectionManager manager, boolean isOnTheFly) - { - if(file instanceof XmlFile && (file.isPhysical() || ApplicationManager.getApplication().isUnitTestMode())) - { - DomFileElement model = - DomManager.getDomManager(file.getProject()).getFileElement((XmlFile) file, MavenDomProjectModel.class); - - if(model != null) - { - MavenDomProjectModel projectModel = model.getRootElement(); - - String groupId = projectModel.getGroupId().getStringValue(); - if(groupId != null && groupId.length() > 0) - { - MavenDomParent parent = projectModel.getMavenParent(); - - String parentGroupId = parent.getGroupId().getStringValue(); - - if(groupId.equals(parentGroupId)) - { - XmlTag xmlTag = projectModel.getGroupId().getXmlTag(); - - LocalQuickFix fix = new LocalQuickFixBase("Remove unnecessary ") - { - @Override - public void applyFix(@Nonnull Project project, @Nonnull ProblemDescriptor descriptor) - { - PsiElement xmlTag = descriptor.getPsiElement(); - - if(xmlTag.isValid() && FileModificationService.getInstance().preparePsiElementForWrite(xmlTag)) - { - xmlTag.delete(); - } - } - }; - - return new ProblemDescriptor[]{ - manager.createProblemDescriptor(xmlTag, - "Definition of groupId is redundant, because it's inherited from the parent", - fix, ProblemHighlightType.GENERIC_ERROR_OR_WARNING, isOnTheFly) - }; - } - } - - } - } - - return null; - } +public class MavenRedundantGroupIdInspection extends XmlSuppressableInspectionTool { + @Nonnull + @Override + public String getGroupDisplayName() { + return MavenDomLocalize.inspectionGroup().get(); + } + + @Nonnull + @Override + public String getDisplayName() { + return MavenDomLocalize.inspectionRedundantGroupidName().get(); + } + + @Nonnull + @Override + public String getShortName() { + return "MavenRedundantGroupId"; + } + + @Nonnull + @Override + public HighlightDisplayLevel getDefaultLevel() { + return HighlightDisplayLevel.WARNING; + } + + @Nullable + @Override + public ProblemDescriptor[] checkFile(@Nonnull PsiFile file, @Nonnull InspectionManager manager, boolean isOnTheFly) { + if (file instanceof XmlFile xmlFile && (xmlFile.isPhysical() || xmlFile.getApplication().isUnitTestMode())) { + DomFileElement model = + DomManager.getDomManager(xmlFile.getProject()).getFileElement(xmlFile, MavenDomProjectModel.class); + + if (model != null) { + MavenDomProjectModel projectModel = model.getRootElement(); + + String groupId = projectModel.getGroupId().getStringValue(); + if (groupId != null && groupId.length() > 0) { + MavenDomParent parent = projectModel.getMavenParent(); + + String parentGroupId = parent.getGroupId().getStringValue(); + + if (groupId.equals(parentGroupId)) { + XmlTag xmlTag = projectModel.getGroupId().getXmlTag(); + + LocalQuickFix fix = new LocalQuickFixBase("Remove unnecessary ") { + @Override + @RequiredReadAction + public void applyFix(@Nonnull Project project, @Nonnull ProblemDescriptor descriptor) { + PsiElement xmlTag = descriptor.getPsiElement(); + + if (xmlTag.isValid() && FileModificationService.getInstance().preparePsiElementForWrite(xmlTag)) { + xmlTag.delete(); + } + } + }; + + return new ProblemDescriptor[]{ + manager.createProblemDescriptor(xmlTag, + "Definition of groupId is redundant, because it's inherited from the parent", + fix, ProblemHighlightType.GENERIC_ERROR_OR_WARNING, isOnTheFly + ) + }; + } + } + } + } + + return null; + } } diff --git a/plugin/src/main/java/org/jetbrains/idea/maven/dom/intentions/AddMavenDependencyQuickFix.java b/plugin/src/main/java/org/jetbrains/idea/maven/dom/intentions/AddMavenDependencyQuickFix.java index 968fb363..a14bab53 100644 --- a/plugin/src/main/java/org/jetbrains/idea/maven/dom/intentions/AddMavenDependencyQuickFix.java +++ b/plugin/src/main/java/org/jetbrains/idea/maven/dom/intentions/AddMavenDependencyQuickFix.java @@ -19,7 +19,6 @@ import consulo.application.Result; import consulo.codeEditor.Editor; import consulo.language.editor.WriteCommandAction; -import consulo.language.editor.intention.IntentionAction; import consulo.language.editor.intention.LowPriorityAction; import consulo.language.editor.intention.SyntheticIntentionAction; import consulo.language.psi.PsiElement; @@ -28,7 +27,6 @@ import consulo.maven.rt.server.common.model.MavenId; import consulo.project.Project; import consulo.xml.util.xml.DomUtil; -import org.jetbrains.idea.maven.dom.MavenDomBundle; import org.jetbrains.idea.maven.dom.MavenDomUtil; import org.jetbrains.idea.maven.dom.model.MavenDomProjectModel; import org.jetbrains.idea.maven.indices.MavenArtifactSearchDialog; @@ -40,68 +38,79 @@ import java.util.regex.Pattern; public class AddMavenDependencyQuickFix implements SyntheticIntentionAction, LowPriorityAction { + private static final Pattern CLASSNAME_PATTERN = + Pattern.compile("(\\p{javaJavaIdentifierStart}\\p{javaJavaIdentifierPart}*\\.)*\\p{Lu}\\p{javaJavaIdentifierPart}+"); - private static final Pattern CLASSNAME_PATTERN = Pattern.compile("(\\p{javaJavaIdentifierStart}\\p{javaJavaIdentifierPart}*\\.)*\\p{Lu}\\p{javaJavaIdentifierPart}+"); + private final PsiJavaCodeReferenceElement myRef; - private final PsiJavaCodeReferenceElement myRef; + public AddMavenDependencyQuickFix(PsiJavaCodeReferenceElement ref) { + myRef = ref; + } - public AddMavenDependencyQuickFix(PsiJavaCodeReferenceElement ref) { - myRef = ref; - } + @Nonnull + @Override + public String getText() { + return "Add Maven Dependency..."; + } - @Nonnull - public String getText() { - return "Add Maven Dependency..."; - } + @Override + public boolean isAvailable(@Nonnull Project project, Editor editor, PsiFile file) { + return myRef.isValid() && MavenDomUtil.findContainingProject(file) != null && looksLikeClassName(getReferenceText()); + } - public boolean isAvailable(@Nonnull Project project, Editor editor, PsiFile file) { - return myRef.isValid() && MavenDomUtil.findContainingProject(file) != null && looksLikeClassName(getReferenceText()); - } + private static boolean looksLikeClassName(@Nullable String text) { + if (text == null) { + return false; + } + //if (true) return true; + return CLASSNAME_PATTERN.matcher(text).matches(); + } - private static boolean looksLikeClassName(@Nullable String text) { - if (text == null) return false; - //if (true) return true; - return CLASSNAME_PATTERN.matcher(text).matches(); - } + @Override + public void invoke(@Nonnull final Project project, Editor editor, final PsiFile file) throws IncorrectOperationException { + if (!myRef.isValid()) { + return; + } - public void invoke(@Nonnull final Project project, Editor editor, final PsiFile file) throws IncorrectOperationException - { - if (!myRef.isValid()) return; + MavenProject mavenProject = MavenDomUtil.findContainingProject(file); + if (mavenProject == null) { + return; + } - MavenProject mavenProject = MavenDomUtil.findContainingProject(file); - if (mavenProject == null) return; + final List ids = MavenArtifactSearchDialog.searchForClass(project, getReferenceText()); + if (ids.isEmpty()) { + return; + } - final List ids = MavenArtifactSearchDialog.searchForClass(project, getReferenceText()); - if (ids.isEmpty()) return; + final MavenDomProjectModel model = MavenDomUtil.getMavenDomProjectModel(project, mavenProject.getFile()); + if (model == null) { + return; + } - final MavenDomProjectModel model = MavenDomUtil.getMavenDomProjectModel(project, mavenProject.getFile()); - if (model == null) return; + new WriteCommandAction(project, "Add Maven Dependency", DomUtil.getFile(model)) { + @Override + protected void run(Result result) throws Throwable { + for (MavenId each : ids) { + MavenDomUtil.createDomDependency(model, null, each); + } + } + }.execute(); + } - new WriteCommandAction(project, "Add Maven Dependency", DomUtil.getFile(model)) { - @Override - protected void run(Result result) throws Throwable { - for (MavenId each : ids) { - MavenDomUtil.createDomDependency(model, null, each); + public String getReferenceText() { + PsiJavaCodeReferenceElement result = myRef; + while (true) { + if (!(result.getParent() instanceof PsiJavaCodeReferenceElement javaCodeReferenceElement)) { + break; + } + result = javaCodeReferenceElement; } - } - }.execute(); - } - - public String getReferenceText() { - PsiJavaCodeReferenceElement result = myRef; - while (true) { - PsiElement parent = result.getParent(); - if (!(parent instanceof PsiJavaCodeReferenceElement)) { - break; - } - - result = (PsiJavaCodeReferenceElement)parent; - } - return result.getQualifiedName(); - } + return result.getQualifiedName(); + } - public boolean startInWriteAction() { - return false; - } + @Override + public boolean startInWriteAction() { + return false; + } } diff --git a/plugin/src/main/java/org/jetbrains/idea/maven/dom/intentions/ChooseFileIntentionAction.java b/plugin/src/main/java/org/jetbrains/idea/maven/dom/intentions/ChooseFileIntentionAction.java index 8ae88eea..8feb4367 100644 --- a/plugin/src/main/java/org/jetbrains/idea/maven/dom/intentions/ChooseFileIntentionAction.java +++ b/plugin/src/main/java/org/jetbrains/idea/maven/dom/intentions/ChooseFileIntentionAction.java @@ -30,14 +30,15 @@ import consulo.language.psi.util.PsiTreeUtil; import consulo.language.util.IncorrectOperationException; import consulo.project.Project; +import consulo.ui.annotation.RequiredUIAccess; import consulo.virtualFileSystem.VirtualFile; import consulo.xml.psi.xml.XmlTag; import consulo.xml.util.xml.DomElement; import consulo.xml.util.xml.DomManager; import org.jetbrains.annotations.TestOnly; -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.localize.MavenDomLocalize; import javax.annotation.Nonnull; import javax.annotation.Nullable; @@ -46,65 +47,81 @@ @ExtensionImpl @IntentionMetaData(ignoreId = "maven.choose.file.intention", categories = {"Java", "Maven"}, fileExtensions = "xml") public class ChooseFileIntentionAction implements IntentionAction { - private Supplier myFileChooser = null; + private Supplier myFileChooser = null; - @Nonnull - public String getText() { - return MavenDomBundle.message("intention.choose.file"); - } + @Nonnull + @Override + public String getText() { + return MavenDomLocalize.intentionChooseFile().get(); + } - public boolean startInWriteAction() { - return false; - } + @Override + public boolean startInWriteAction() { + return false; + } - public boolean isAvailable(@Nonnull Project project, Editor editor, PsiFile file) { - if (!MavenDomUtil.isMavenFile(file)) return false; - MavenDomDependency dep = getDependency(file, editor); - return dep != null && "system".equals(dep.getScope().getStringValue()); - } + @Override + public boolean isAvailable(@Nonnull Project project, Editor editor, PsiFile file) { + if (!MavenDomUtil.isMavenFile(file)) { + return false; + } + MavenDomDependency dep = getDependency(file, editor); + return dep != null && "system".equals(dep.getScope().getStringValue()); + } - public void invoke(@Nonnull Project project, Editor editor, PsiFile file) throws IncorrectOperationException { - final MavenDomDependency dep = getDependency(file, editor); + @Override + @RequiredUIAccess + public void invoke(@Nonnull Project project, Editor editor, PsiFile file) throws IncorrectOperationException { + final MavenDomDependency dep = getDependency(file, editor); - final VirtualFile[] files; - if (myFileChooser == null) { - final FileChooserDescriptor descriptor = new FileChooserDescriptor(true, false, true, true, false, false); - final PsiFile currentValue = dep != null ? dep.getSystemPath().getValue() : null; - final VirtualFile toSelect = currentValue == null ? null : currentValue.getVirtualFile(); - files = IdeaFileChooser.chooseFiles(descriptor, project, toSelect); - } - else { - files = myFileChooser.get(); - } - if (files == null || files.length == 0) return; + final VirtualFile[] files; + if (myFileChooser == null) { + final FileChooserDescriptor descriptor = new FileChooserDescriptor(true, false, true, true, false, false); + final PsiFile currentValue = dep != null ? dep.getSystemPath().getValue() : null; + final VirtualFile toSelect = currentValue == null ? null : currentValue.getVirtualFile(); + files = IdeaFileChooser.chooseFiles(descriptor, project, toSelect); + } + else { + files = myFileChooser.get(); + } + if (files == null || files.length == 0) { + return; + } - final PsiFile selectedFile = PsiManager.getInstance(project).findFile(files[0]); - if (selectedFile == null) return; + final PsiFile selectedFile = PsiManager.getInstance(project).findFile(files[0]); + if (selectedFile == null) { + return; + } - if (dep != null) { - new WriteCommandAction(project) { - protected void run(Result result) throws Throwable { - dep.getSystemPath().setValue(selectedFile); + if (dep != null) { + new WriteCommandAction(project) { + @Override + protected void run(Result result) throws Throwable { + dep.getSystemPath().setValue(selectedFile); + } + }.execute(); } - }.execute(); } - } - @TestOnly - public void setFileChooser(@Nullable final Supplier fileChooser) { - myFileChooser = fileChooser; - } + @TestOnly + public void setFileChooser(@Nullable final Supplier fileChooser) { + myFileChooser = fileChooser; + } - @Nullable - private static MavenDomDependency getDependency(PsiFile file, Editor editor) { - PsiElement el = PsiUtilCore.getElementAtOffset(file, editor.getCaretModel().getOffset()); + @Nullable + private static MavenDomDependency getDependency(PsiFile file, Editor editor) { + PsiElement el = PsiUtilCore.getElementAtOffset(file, editor.getCaretModel().getOffset()); - XmlTag tag = PsiTreeUtil.getParentOfType(el, XmlTag.class, false); - if (tag == null) return null; + XmlTag tag = PsiTreeUtil.getParentOfType(el, XmlTag.class, false); + if (tag == null) { + return null; + } - DomElement dom = DomManager.getDomManager(el.getProject()).getDomElement(tag); - if (dom == null) return null; + DomElement dom = DomManager.getDomManager(el.getProject()).getDomElement(tag); + if (dom == null) { + return null; + } - return dom.getParentOfType(MavenDomDependency.class, false); - } + return dom.getParentOfType(MavenDomDependency.class, false); + } } diff --git a/plugin/src/main/java/org/jetbrains/idea/maven/dom/intentions/ResolveReferenceQuickFixProvider.java b/plugin/src/main/java/org/jetbrains/idea/maven/dom/intentions/ResolveReferenceQuickFixProvider.java index cebf6122..783a645c 100644 --- a/plugin/src/main/java/org/jetbrains/idea/maven/dom/intentions/ResolveReferenceQuickFixProvider.java +++ b/plugin/src/main/java/org/jetbrains/idea/maven/dom/intentions/ResolveReferenceQuickFixProvider.java @@ -23,16 +23,15 @@ import javax.annotation.Nonnull; @ExtensionImpl -public class ResolveReferenceQuickFixProvider extends UnresolvedReferenceQuickFixProvider -{ - public void registerFixes(PsiJavaCodeReferenceElement ref, QuickFixActionRegistrar registrar) - { - registrar.register(new AddMavenDependencyQuickFix(ref)); - } +public class ResolveReferenceQuickFixProvider extends UnresolvedReferenceQuickFixProvider { + @Override + public void registerFixes(PsiJavaCodeReferenceElement ref, QuickFixActionRegistrar registrar) { + registrar.register(new AddMavenDependencyQuickFix(ref)); + } - @Nonnull - public Class getReferenceClass() - { - return PsiJavaCodeReferenceElement.class; - } + @Nonnull + @Override + public Class getReferenceClass() { + return PsiJavaCodeReferenceElement.class; + } } diff --git a/plugin/src/main/java/org/jetbrains/idea/maven/dom/refactorings/MavenPropertyRenameHandler.java b/plugin/src/main/java/org/jetbrains/idea/maven/dom/refactorings/MavenPropertyRenameHandler.java index 360cd406..25ebd01d 100644 --- a/plugin/src/main/java/org/jetbrains/idea/maven/dom/refactorings/MavenPropertyRenameHandler.java +++ b/plugin/src/main/java/org/jetbrains/idea/maven/dom/refactorings/MavenPropertyRenameHandler.java @@ -32,44 +32,36 @@ import javax.annotation.Nonnull; @ExtensionImpl -public class MavenPropertyRenameHandler extends PsiElementRenameHandler -{ - @Override - public boolean isAvailableOnDataContext(DataContext context) - { - return findTarget(context) != null; - } +public class MavenPropertyRenameHandler extends PsiElementRenameHandler { + @Override + public boolean isAvailableOnDataContext(DataContext context) { + return findTarget(context) != null; + } - @Override - public void invoke(@Nonnull Project project, Editor editor, PsiFile file, DataContext dataContext) - { - invoke(project, PsiElement.EMPTY_ARRAY, dataContext); - } + @Override + public void invoke(@Nonnull Project project, Editor editor, PsiFile file, DataContext dataContext) { + invoke(project, PsiElement.EMPTY_ARRAY, dataContext); + } - @Override - public void invoke(@Nonnull Project project, @Nonnull PsiElement[] elements, DataContext dataContext) - { - PsiElement element = elements.length == 1 ? elements[0] : null; - if(element == null) - { - element = findTarget(dataContext); - } + @Override + public void invoke(@Nonnull Project project, @Nonnull PsiElement[] elements, DataContext dataContext) { + PsiElement element = elements.length == 1 ? elements[0] : null; + if (element == null) { + element = findTarget(dataContext); + } - RenameDialog dialog = new RenameDialog(project, element, null, dataContext.getData(PlatformDataKeys.EDITOR)); - if(ApplicationManager.getApplication().isUnitTestMode()) - { - String name = dataContext.getData(DEFAULT_NAME); - dialog.performRename(name); - dialog.close(DialogWrapper.OK_EXIT_CODE); - } - else - { - dialog.show(); - } - } + RenameDialog dialog = new RenameDialog(project, element, null, dataContext.getData(PlatformDataKeys.EDITOR)); + if (ApplicationManager.getApplication().isUnitTestMode()) { + String name = dataContext.getData(DEFAULT_NAME); + dialog.performRename(name); + dialog.close(DialogWrapper.OK_EXIT_CODE); + } + else { + dialog.show(); + } + } - private static PsiElement findTarget(DataContext context) - { - return MavenTargetUtil.getRefactorTarget(context.getData(PlatformDataKeys.EDITOR), context.getData(LangDataKeys.PSI_FILE)); - } + private static PsiElement findTarget(DataContext context) { + return MavenTargetUtil.getRefactorTarget(context.getData(PlatformDataKeys.EDITOR), context.getData(LangDataKeys.PSI_FILE)); + } } diff --git a/plugin/src/main/java/org/jetbrains/idea/maven/dom/refactorings/MavenVetoModelRenameCondition.java b/plugin/src/main/java/org/jetbrains/idea/maven/dom/refactorings/MavenVetoModelRenameCondition.java index 36f0a13a..7651b11b 100644 --- a/plugin/src/main/java/org/jetbrains/idea/maven/dom/refactorings/MavenVetoModelRenameCondition.java +++ b/plugin/src/main/java/org/jetbrains/idea/maven/dom/refactorings/MavenVetoModelRenameCondition.java @@ -23,12 +23,10 @@ import org.jetbrains.idea.maven.dom.references.MavenPsiElementWrapper; @ExtensionImpl -public class MavenVetoModelRenameCondition implements VetoRenameCondition -{ - @RequiredReadAction - @Override - public boolean isVetoed(PsiElement target) - { - return target instanceof MavenPsiElementWrapper || MavenDomUtil.isMavenFile(target); - } +public class MavenVetoModelRenameCondition implements VetoRenameCondition { + @RequiredReadAction + @Override + public boolean isVetoed(PsiElement target) { + return target instanceof MavenPsiElementWrapper || MavenDomUtil.isMavenFile(target); + } } diff --git a/plugin/src/main/java/org/jetbrains/idea/maven/dom/refactorings/extract/ExtractManagedDependenciesAction.java b/plugin/src/main/java/org/jetbrains/idea/maven/dom/refactorings/extract/ExtractManagedDependenciesAction.java index aae10f4c..0d6e5b90 100644 --- a/plugin/src/main/java/org/jetbrains/idea/maven/dom/refactorings/extract/ExtractManagedDependenciesAction.java +++ b/plugin/src/main/java/org/jetbrains/idea/maven/dom/refactorings/extract/ExtractManagedDependenciesAction.java @@ -15,6 +15,7 @@ */ package org.jetbrains.idea.maven.dom.refactorings.extract; +import consulo.annotation.access.RequiredReadAction; import consulo.application.Result; import consulo.codeEditor.Editor; import consulo.dataContext.DataContext; @@ -45,274 +46,244 @@ import java.util.Set; import java.util.function.Function; -public class ExtractManagedDependenciesAction extends BaseRefactoringAction -{ - public ExtractManagedDependenciesAction() - { - setInjectedContext(true); - } - - protected boolean isAvailableInEditorOnly() - { - return true; - } - - protected boolean isEnabledOnElements(@Nonnull PsiElement[] elements) - { - return false; - } - - @Override - protected boolean isAvailableForLanguage(Language language) - { - return true; - } - - protected RefactoringActionHandler getHandler(@Nonnull DataContext dataContext) - { - return new MyRefactoringActionHandler(); - } - - @Override - protected boolean isAvailableForFile(PsiFile file) - { - return MavenDomUtil.isMavenFile(file); - } - - @Override - protected boolean isAvailableOnElementInEditorAndFile(@Nonnull PsiElement element, @Nonnull Editor editor, @Nonnull PsiFile file, - @Nonnull DataContext context) - { - if(!super.isAvailableOnElementInEditorAndFile(element, editor, file, context)) - { - return false; - } - return findDependencyAndParent(file, editor) != null; - } - - private static Pair> findDependencyAndParent(PsiFile file, Editor editor) - { - final MavenDomDependency dependency = DomUtil.findDomElement(file.findElementAt(editor.getCaretModel().getOffset()), - MavenDomDependency.class); - if(dependency == null || isManagedDependency(dependency)) - { - return null; - } - - Set parents = getParentProjects(file); - if(parents.isEmpty()) - { - return null; - } - - return Pair.create(dependency, parents); - } - - @Nonnull - private static Set getParentProjects(@Nonnull PsiFile file) - { - final MavenDomProjectModel model = MavenDomUtil.getMavenDomModel(file, MavenDomProjectModel.class); - - if(model == null) - { - return Collections.emptySet(); - } - return MavenDomProjectProcessorUtils.collectParentProjects(model); - } - - private static boolean isManagedDependency(@Nonnull MavenDomDependency dependency) - { - return MavenDomProjectProcessorUtils.searchManagingDependency(dependency) != null; - } - - private static class MyRefactoringActionHandler implements RefactoringActionHandler - { - public void invoke(@Nonnull final Project project, final Editor editor, PsiFile file, DataContext dataContext) - { - Pair> depAndParents = findDependencyAndParent(file, editor); - if(depAndParents == null) - { - return; - } - - final MavenDomDependency dependency = depAndParents.first; - Set parent = depAndParents.second; - - Function> funOccurrences = getOccurencesFunction(dependency); - final ProcessData processData = getProcessData(project, parent, funOccurrences, dependency.getExclusions().getXmlElement() != null); - if(processData == null) - { - return; - } - - final MavenDomProjectModel model = processData.getModel(); - final Set usages = processData.getUsages(); - final boolean extractExclusions = processData.isExtractExclusions(); - - - assert model != null; - assert usages != null; - - new WriteCommandAction(project, getFiles(file, model, usages)) - { - @Override - protected void run(Result result) throws Throwable - { - MavenDomDependency addedDependency = model.getDependencyManagement().getDependencies().addDependency(); - addedDependency.getGroupId().setStringValue(dependency.getGroupId().getStringValue()); - addedDependency.getArtifactId().setStringValue(dependency.getArtifactId().getStringValue()); - addedDependency.getVersion().setStringValue(dependency.getVersion().getStringValue()); - String typeValue = dependency.getType().getStringValue(); - - dependency.getVersion().undefine(); - - if(typeValue != null) - { - addedDependency.getType().setStringValue(typeValue); - } - - String classifier = dependency.getClassifier().getStringValue(); - if(classifier != null) - { - addedDependency.getClassifier().setStringValue(classifier); - } - - String systemPath = dependency.getSystemPath().getStringValue(); - if(systemPath != null) - { - addedDependency.getSystemPath().setStringValue(systemPath); - dependency.getSystemPath().undefine(); - } - - - if(extractExclusions) - { - MavenDomExclusions addedExclusions = addedDependency.getExclusions(); - for(MavenDomExclusion exclusion : dependency.getExclusions().getExclusions()) - { - MavenDomExclusion domExclusion = addedExclusions.addExclusion(); - - domExclusion.getGroupId().setStringValue(exclusion.getGroupId().getStringValue()); - domExclusion.getArtifactId().setStringValue(exclusion.getArtifactId().getStringValue()); - } - - dependency.getExclusions().undefine(); - } - - for(MavenDomDependency usage : usages) - { - usage.getVersion().undefine(); - } - } - }.execute(); - } - - private static PsiFile[] getFiles(@Nonnull PsiFile file, @Nonnull MavenDomProjectModel model, @Nonnull Set usages) - { - Set files = new HashSet(); - - files.add(file); - XmlElement xmlElement = model.getXmlElement(); - if(xmlElement != null) - { - files.add(xmlElement.getContainingFile()); - } - for(MavenDomDependency usage : usages) - { - XmlElement element = usage.getXmlElement(); - if(element != null) - { - files.add(element.getContainingFile()); - } - } - - return PsiUtilCore.toPsiFileArray(files); - } - - - @Nullable - private static ProcessData getProcessData(@Nonnull Project project, - - @Nonnull Set models, @Nonnull Function> funOccurrences, - boolean hasExclusions) - { - if(models.size() == 0) - { - return null; - } - - if(models.size() == 1 && !hasExclusions) - { - MavenDomProjectModel model = models.iterator().next(); - if(funOccurrences.apply(model).size() == 0) - { - return new ProcessData(model, Collections.emptySet(), false); - } - } - - SelectMavenProjectDialog dialog = new SelectMavenProjectDialog(project, models, funOccurrences, hasExclusions); - dialog.show(); - - if(dialog.getExitCode() == DialogWrapper.OK_EXIT_CODE) - { - MavenDomProjectModel model = dialog.getSelectedProject(); - - return new ProcessData(model, dialog.isReplaceAllOccurrences() ? funOccurrences.apply(model) : Collections - .emptySet(), dialog.isExtractExclusions()); - } - - return null; - } - - private static Function> getOccurencesFunction(final MavenDomDependency dependency) - { - - return new Function>() - { - public Set apply(MavenDomProjectModel model) - { - DependencyConflictId dependencyId = DependencyConflictId.create(dependency); - if(dependencyId == null) - { - return Collections.emptySet(); - } - - return MavenDomProjectProcessorUtils.searchDependencyUsages(model, dependencyId, Collections.singleton(dependency)); - } - }; - } - - public void invoke(@Nonnull Project project, @Nonnull PsiElement[] elements, DataContext dataContext) - { - } - } - - private static class ProcessData - { - private final MavenDomProjectModel myModel; - private final Set myUsages; - private final boolean myExtractExclusions; - - public MavenDomProjectModel getModel() - { - return myModel; - } - - public Set getUsages() - { - return myUsages; - } - - public boolean isExtractExclusions() - { - return myExtractExclusions; - } - - public ProcessData(MavenDomProjectModel model, Set usages, boolean extractExclusions) - { - myModel = model; - myUsages = usages; - myExtractExclusions = extractExclusions; - } - } +public class ExtractManagedDependenciesAction extends BaseRefactoringAction { + public ExtractManagedDependenciesAction() { + setInjectedContext(true); + } + + @Override + protected boolean isAvailableInEditorOnly() { + return true; + } + + @Override + protected boolean isEnabledOnElements(@Nonnull PsiElement[] elements) { + return false; + } + + @Override + protected boolean isAvailableForLanguage(Language language) { + return true; + } + + @Override + protected RefactoringActionHandler getHandler(@Nonnull DataContext dataContext) { + return new MyRefactoringActionHandler(); + } + + @Override + @RequiredReadAction + protected boolean isAvailableForFile(PsiFile file) { + return MavenDomUtil.isMavenFile(file); + } + + @Override + @RequiredReadAction + protected boolean isAvailableOnElementInEditorAndFile( + @Nonnull PsiElement element, + @Nonnull Editor editor, + @Nonnull PsiFile file, + @Nonnull DataContext context + ) { + return super.isAvailableOnElementInEditorAndFile(element, editor, file, context) && findDependencyAndParent(file, editor) != null; + } + + @RequiredReadAction + private static Pair> findDependencyAndParent(PsiFile file, Editor editor) { + final MavenDomDependency dependency = DomUtil.findDomElement( + file.findElementAt(editor.getCaretModel().getOffset()), + MavenDomDependency.class + ); + if (dependency == null || isManagedDependency(dependency)) { + return null; + } + + Set parents = getParentProjects(file); + if (parents.isEmpty()) { + return null; + } + + return Pair.create(dependency, parents); + } + + @Nonnull + private static Set getParentProjects(@Nonnull PsiFile file) { + final MavenDomProjectModel model = MavenDomUtil.getMavenDomModel(file, MavenDomProjectModel.class); + + if (model == null) { + return Collections.emptySet(); + } + return MavenDomProjectProcessorUtils.collectParentProjects(model); + } + + private static boolean isManagedDependency(@Nonnull MavenDomDependency dependency) { + return MavenDomProjectProcessorUtils.searchManagingDependency(dependency) != null; + } + + private static class MyRefactoringActionHandler implements RefactoringActionHandler { + public void invoke(@Nonnull final Project project, final Editor editor, PsiFile file, DataContext dataContext) { + Pair> depAndParents = findDependencyAndParent(file, editor); + if (depAndParents == null) { + return; + } + + final MavenDomDependency dependency = depAndParents.first; + Set parent = depAndParents.second; + + Function> funOccurrences = getOccurencesFunction(dependency); + final ProcessData processData = + getProcessData(project, parent, funOccurrences, dependency.getExclusions().getXmlElement() != null); + if (processData == null) { + return; + } + + final MavenDomProjectModel model = processData.getModel(); + final Set usages = processData.getUsages(); + final boolean extractExclusions = processData.isExtractExclusions(); + + + assert model != null; + assert usages != null; + + new WriteCommandAction(project, getFiles(file, model, usages)) { + @Override + protected void run(Result result) throws Throwable { + MavenDomDependency addedDependency = model.getDependencyManagement().getDependencies().addDependency(); + addedDependency.getGroupId().setStringValue(dependency.getGroupId().getStringValue()); + addedDependency.getArtifactId().setStringValue(dependency.getArtifactId().getStringValue()); + addedDependency.getVersion().setStringValue(dependency.getVersion().getStringValue()); + String typeValue = dependency.getType().getStringValue(); + + dependency.getVersion().undefine(); + + if (typeValue != null) { + addedDependency.getType().setStringValue(typeValue); + } + + String classifier = dependency.getClassifier().getStringValue(); + if (classifier != null) { + addedDependency.getClassifier().setStringValue(classifier); + } + + String systemPath = dependency.getSystemPath().getStringValue(); + if (systemPath != null) { + addedDependency.getSystemPath().setStringValue(systemPath); + dependency.getSystemPath().undefine(); + } + + + if (extractExclusions) { + MavenDomExclusions addedExclusions = addedDependency.getExclusions(); + for (MavenDomExclusion exclusion : dependency.getExclusions().getExclusions()) { + MavenDomExclusion domExclusion = addedExclusions.addExclusion(); + + domExclusion.getGroupId().setStringValue(exclusion.getGroupId().getStringValue()); + domExclusion.getArtifactId().setStringValue(exclusion.getArtifactId().getStringValue()); + } + + dependency.getExclusions().undefine(); + } + + for (MavenDomDependency usage : usages) { + usage.getVersion().undefine(); + } + } + }.execute(); + } + + private static PsiFile[] getFiles( + @Nonnull PsiFile file, + @Nonnull MavenDomProjectModel model, + @Nonnull Set usages + ) { + Set files = new HashSet<>(); + + files.add(file); + XmlElement xmlElement = model.getXmlElement(); + if (xmlElement != null) { + files.add(xmlElement.getContainingFile()); + } + for (MavenDomDependency usage : usages) { + XmlElement element = usage.getXmlElement(); + if (element != null) { + files.add(element.getContainingFile()); + } + } + + return PsiUtilCore.toPsiFileArray(files); + } + + + @Nullable + private static ProcessData getProcessData( + @Nonnull Project project, + @Nonnull Set models, + @Nonnull Function> funOccurrences, + boolean hasExclusions + ) { + if (models.size() == 0) { + return null; + } + + if (models.size() == 1 && !hasExclusions) { + MavenDomProjectModel model = models.iterator().next(); + if (funOccurrences.apply(model).size() == 0) { + return new ProcessData(model, Collections.emptySet(), false); + } + } + + SelectMavenProjectDialog dialog = new SelectMavenProjectDialog(project, models, funOccurrences, hasExclusions); + dialog.show(); + + if (dialog.getExitCode() == DialogWrapper.OK_EXIT_CODE) { + MavenDomProjectModel model = dialog.getSelectedProject(); + + return new ProcessData(model, dialog.isReplaceAllOccurrences() + ? funOccurrences.apply(model) + : Collections.emptySet(), dialog.isExtractExclusions()); + } + + return null; + } + + private static Function> getOccurencesFunction(final MavenDomDependency dependency) { + return new Function<>() { + public Set apply(MavenDomProjectModel model) { + DependencyConflictId dependencyId = DependencyConflictId.create(dependency); + if (dependencyId == null) { + return Collections.emptySet(); + } + + return MavenDomProjectProcessorUtils.searchDependencyUsages(model, dependencyId, Collections.singleton(dependency)); + } + }; + } + + public void invoke(@Nonnull Project project, @Nonnull PsiElement[] elements, DataContext dataContext) { + } + } + + private static class ProcessData { + private final MavenDomProjectModel myModel; + private final Set myUsages; + private final boolean myExtractExclusions; + + public MavenDomProjectModel getModel() { + return myModel; + } + + public Set getUsages() { + return myUsages; + } + + public boolean isExtractExclusions() { + return myExtractExclusions; + } + + public ProcessData(MavenDomProjectModel model, Set usages, boolean extractExclusions) { + myModel = model; + myUsages = usages; + myExtractExclusions = extractExclusions; + } + } } 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 45990e96..1f6952bc 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 @@ -35,137 +35,121 @@ import java.util.Set; import java.util.function.Function; -public class SelectMavenProjectDialog extends DialogWrapper -{ - private final Set myMavenDomProjectModels; - private final boolean myHasExclusions; - - private JComboBox myMavenProjectsComboBox; - private JPanel myMainPanel; - private JCheckBox myReplaceAllCheckBox; - private JCheckBox myExtractExclusions; - private boolean myHasUsagesInProjects = false; - - private ItemListener myReplaceAllListener; - private final Function> myOccurrencesCountFunction; - - public SelectMavenProjectDialog(@Nonnull Project project, - @Nonnull Set mavenDomProjectModels, - @Nonnull Function> funOccurrences, - @Nonnull boolean hasExclusions) - { - super(project, true); - myMavenDomProjectModels = mavenDomProjectModels; - myHasExclusions = hasExclusions; - - setTitle(MavenDomBundle.message("choose.project")); - - myOccurrencesCountFunction = funOccurrences; - for(MavenDomProjectModel model : myMavenDomProjectModels) - { - if(myOccurrencesCountFunction.apply(model).size() > 0) - { - myHasUsagesInProjects = true; - break; - } - } - - init(); - } - - @Nonnull - protected Action[] createActions() - { - return new Action[]{ - getOKAction(), - getCancelAction() - }; - } - - protected void init() - { - super.init(); - - updateOkStatus(); - } - - @Override - protected void dispose() - { - super.dispose(); - if(myReplaceAllCheckBox != null) - { - myReplaceAllCheckBox.removeItemListener(myReplaceAllListener); - } - } - - @Nullable - public MavenDomProjectModel getSelectedProject() - { - return (MavenDomProjectModel) ComboBoxUtil.getSelectedValue((DefaultComboBoxModel) myMavenProjectsComboBox.getModel()); - } - - public boolean isReplaceAllOccurrences() - { - return myReplaceAllCheckBox.isSelected(); - } - - public boolean isExtractExclusions() - { - return myExtractExclusions.isSelected(); - } - - protected JComponent createCenterPanel() - { - ComboBoxUtil.setModel(myMavenProjectsComboBox, new DefaultComboBoxModel(), myMavenDomProjectModels, - model -> { - String projectName = model.getName().getStringValue(); - MavenProject mavenProject = MavenDomUtil.findProject(model); - if(mavenProject != null) - { - projectName = mavenProject.getDisplayName(); - } - if(StringUtil.isEmptyOrSpaces(projectName)) - { - projectName = "pom.xml"; - } - return Pair.create(projectName, model); - }); - - myReplaceAllListener = new ItemListener() - { - public void itemStateChanged(ItemEvent e) - { - updateControls(); - } - }; - - myMavenProjectsComboBox.addItemListener(myReplaceAllListener); - myMavenProjectsComboBox.setSelectedItem(0); - myReplaceAllCheckBox.setVisible(myHasUsagesInProjects); - myExtractExclusions.setVisible(myHasExclusions); - - updateControls(); - - return myMainPanel; - } - - private void updateControls() - { - MavenDomProjectModel project = getSelectedProject(); - Integer count = myOccurrencesCountFunction.apply(project).size(); - myReplaceAllCheckBox.setText(RefactoringBundle.message("replace.all.occurences", count)); - - myReplaceAllCheckBox.setEnabled(count != 0); - } - - private void updateOkStatus() - { - setOKActionEnabled(getSelectedProject() != null); - } - - public JComponent getPreferredFocusedComponent() - { - return myMavenProjectsComboBox; - } +public class SelectMavenProjectDialog extends DialogWrapper { + private final Set myMavenDomProjectModels; + private final boolean myHasExclusions; + + private JComboBox myMavenProjectsComboBox; + private JPanel myMainPanel; + private JCheckBox myReplaceAllCheckBox; + private JCheckBox myExtractExclusions; + private boolean myHasUsagesInProjects = false; + + private ItemListener myReplaceAllListener; + private final Function> myOccurrencesCountFunction; + + public SelectMavenProjectDialog( + @Nonnull Project project, + @Nonnull Set mavenDomProjectModels, + @Nonnull Function> funOccurrences, + boolean hasExclusions + ) { + super(project, true); + myMavenDomProjectModels = mavenDomProjectModels; + myHasExclusions = hasExclusions; + + setTitle(MavenDomBundle.message("choose.project")); + + myOccurrencesCountFunction = funOccurrences; + for (MavenDomProjectModel model : myMavenDomProjectModels) { + if (myOccurrencesCountFunction.apply(model).size() > 0) { + myHasUsagesInProjects = true; + break; + } + } + + init(); + } + + @Nonnull + protected Action[] createActions() { + return new Action[]{ + getOKAction(), + getCancelAction() + }; + } + + protected void init() { + super.init(); + + updateOkStatus(); + } + + @Override + protected void dispose() { + super.dispose(); + if (myReplaceAllCheckBox != null) { + myReplaceAllCheckBox.removeItemListener(myReplaceAllListener); + } + } + + @Nullable + public MavenDomProjectModel getSelectedProject() { + return (MavenDomProjectModel)ComboBoxUtil.getSelectedValue((DefaultComboBoxModel)myMavenProjectsComboBox.getModel()); + } + + public boolean isReplaceAllOccurrences() { + return myReplaceAllCheckBox.isSelected(); + } + + public boolean isExtractExclusions() { + return myExtractExclusions.isSelected(); + } + + protected JComponent createCenterPanel() { + ComboBoxUtil.setModel(myMavenProjectsComboBox, new DefaultComboBoxModel(), myMavenDomProjectModels, + model -> { + String projectName = model.getName().getStringValue(); + MavenProject mavenProject = MavenDomUtil.findProject(model); + if (mavenProject != null) { + projectName = mavenProject.getDisplayName(); + } + if (StringUtil.isEmptyOrSpaces(projectName)) { + projectName = "pom.xml"; + } + return Pair.create(projectName, model); + } + ); + + myReplaceAllListener = new ItemListener() { + public void itemStateChanged(ItemEvent e) { + updateControls(); + } + }; + + myMavenProjectsComboBox.addItemListener(myReplaceAllListener); + myMavenProjectsComboBox.setSelectedItem(0); + myReplaceAllCheckBox.setVisible(myHasUsagesInProjects); + myExtractExclusions.setVisible(myHasExclusions); + + updateControls(); + + return myMainPanel; + } + + private void updateControls() { + MavenDomProjectModel project = getSelectedProject(); + Integer count = myOccurrencesCountFunction.apply(project).size(); + myReplaceAllCheckBox.setText(RefactoringBundle.message("replace.all.occurences", count)); + + myReplaceAllCheckBox.setEnabled(count != 0); + } + + private void updateOkStatus() { + setOKActionEnabled(getSelectedProject() != null); + } + + public JComponent getPreferredFocusedComponent() { + return myMavenProjectsComboBox; + } } \ No newline at end of file diff --git a/plugin/src/main/java/org/jetbrains/idea/maven/dom/refactorings/introduce/IntroducePropertyAction.java b/plugin/src/main/java/org/jetbrains/idea/maven/dom/refactorings/introduce/IntroducePropertyAction.java index e8ab3ba4..aafd0690 100644 --- a/plugin/src/main/java/org/jetbrains/idea/maven/dom/refactorings/introduce/IntroducePropertyAction.java +++ b/plugin/src/main/java/org/jetbrains/idea/maven/dom/refactorings/introduce/IntroducePropertyAction.java @@ -39,413 +39,364 @@ import java.util.*; import java.util.function.Supplier; -public class IntroducePropertyAction extends BaseRefactoringAction -{ - private static String PREFIX = "${"; - private static String SUFFIX = "}"; - - public IntroducePropertyAction() - { - setInjectedContext(true); - } - - @Override - protected boolean isAvailableInEditorOnly() - { - return true; - } - - @Override - protected boolean isEnabledOnElements(@Nonnull PsiElement[] elements) - { - return false; - } - - @Override - protected boolean isAvailableForLanguage(Language language) - { - return true; - } - - @Override - protected RefactoringActionHandler getHandler(@Nonnull DataContext dataContext) - { - return new MyRefactoringActionHandler(); - } - - @Override - protected boolean isAvailableForFile(PsiFile file) - { - VirtualFile virtualFile = file.getVirtualFile(); - return MavenDomUtil.isMavenFile(file) - && virtualFile != null - && !(virtualFile.getFileSystem() instanceof ArchiveFileSystem); - } - - @Override - protected boolean isAvailableOnElementInEditorAndFile(@Nonnull PsiElement element, @Nonnull Editor editor, @Nonnull PsiFile file, @Nonnull DataContext context) - { - if(!super.isAvailableOnElementInEditorAndFile(element, editor, file, context)) - { - return false; - } - return getSelectedElementAndTextRange(editor, file) != null; - } - - @Nullable - public static Pair getSelectedElementAndTextRange(Editor editor, final PsiFile file) - { - final int startOffset = editor.getSelectionModel().getSelectionStart(); - final int endOffset = editor.getSelectionModel().getSelectionEnd(); - - final PsiElement elementAtStart = file.findElementAt(startOffset); - if(elementAtStart == null) - { - return null; - } - final PsiElement elementAtEnd = file.findElementAt(endOffset == startOffset ? endOffset : endOffset - 1); - if(elementAtEnd == null) - { - return null; - } - - PsiElement elementAt = PsiTreeUtil.findCommonParent(elementAtStart, elementAtEnd); - if(elementAt instanceof XmlToken) - { - elementAt = elementAt.getParent(); - } - - if(elementAt instanceof XmlText || elementAt instanceof XmlAttributeValue) - { - TextRange range; - - if(editor.getSelectionModel().hasSelection()) - { - range = new TextRange(startOffset, endOffset); - } - else - { - range = elementAt.getTextRange(); - } - - return Pair.create((XmlElement) elementAt, range); - } - - return null; - } - - private static class MyRefactoringActionHandler implements RefactoringActionHandler - { - @Override - public void invoke(@Nonnull final Project project, final Editor editor, PsiFile file, DataContext dataContext) - { - PsiDocumentManager.getInstance(project).commitAllDocuments(); - - Pair elementAndRange = getSelectedElementAndTextRange(editor, file); - if(elementAndRange == null) - { - return; - } - - XmlElement selectedElement = elementAndRange.first; - final TextRange range = elementAndRange.second; - - String stringValue = selectedElement.getText(); - if(stringValue == null) - { - return; - } - - final MavenDomProjectModel model = MavenDomUtil.getMavenDomModel(file, MavenDomProjectModel.class); - final String selectedString = editor.getDocument().getText(range); - - List ranges = getPropertiesTextRanges(stringValue); - int offsetInElement = range.getStartOffset() - selectedElement.getTextOffset(); - - if(model == null || - StringUtil.isEmptyOrSpaces(selectedString) || - isInsideTextRanges(ranges, offsetInElement, offsetInElement + selectedString.length())) - { - return; - } - - editor.getSelectionModel().setSelection(range.getStartOffset(), range.getEndOffset()); - - IntroducePropertyDialog dialog = new IntroducePropertyDialog(project, selectedElement, model, selectedString); - dialog.show(); - if(dialog.getExitCode() != DialogWrapper.OK_EXIT_CODE) - { - return; - } - - final String propertyName = dialog.getEnteredName(); - final String replaceWith = PREFIX + propertyName + SUFFIX; - final MavenDomProjectModel selectedProject = dialog.getSelectedProject(); - - if(ReadonlyStatusHandler.getInstance(project).ensureFilesWritable(getFiles(file, selectedProject)).hasReadonlyFiles()) - { - return; - } - - new WriteCommandAction(project) - { - @Override - protected void run(Result result) throws Throwable - { - editor.getDocument().replaceString(range.getStartOffset(), range.getEndOffset(), replaceWith); - PsiDocumentManager.getInstance(project).commitAllDocuments(); - - createMavenProperty(selectedProject, propertyName, selectedString); - - PsiDocumentManager.getInstance(project).commitAllDocuments(); - } - }.execute(); - - showFindUsages(project, propertyName, selectedString, replaceWith, selectedProject); - } - - private static VirtualFile[] getFiles(PsiFile file, MavenDomProjectModel model) - { - Set virtualFiles = new HashSet(); - VirtualFile virtualFile = file.getVirtualFile(); - if(virtualFile != null) - { - virtualFiles.add(virtualFile); - } - - XmlElement xmlElement = model.getXmlElement(); - if(xmlElement != null) - { - VirtualFile vf = xmlElement.getContainingFile().getVirtualFile(); - if(vf != null) - { - virtualFiles.add(vf); - } - } - - return VirtualFileUtil.toVirtualFileArray(virtualFiles); - } - - private static void createMavenProperty(@Nonnull MavenDomProjectModel model, - @Nonnull String enteredName, - @Nonnull String selectedString) - { - MavenDomProperties mavenDomProperties = model.getProperties(); - XmlTag xmlTag = mavenDomProperties.ensureTagExists(); - - XmlTag propertyTag = xmlTag.createChildTag(enteredName, xmlTag.getNamespace(), selectedString, false); - - xmlTag.add(propertyTag); - } - - private static void showFindUsages(@Nonnull Project project, - @Nonnull String propertyName, - @Nonnull String selectedString, - @Nonnull String replaceWith, - @Nonnull MavenDomProjectModel model) - { - UsageViewManager manager = UsageViewManager.getInstance(project); - if(manager == null) - { - return; - } - - assureFindToolWindowRegistered(project); - - FindManager findManager = FindManager.getInstance(project); - FindModel findModel = createFindModel(findManager, selectedString, replaceWith); - - final UsageViewPresentation presentation = FindInProjectUtil.setupViewPresentation(true, findModel); - final FindUsagesProcessPresentation processPresentation = FindInProjectUtil.setupProcessPresentation(project, true, presentation); - - findManager.getFindInProjectModel().copyFrom(findModel); - final FindModel findModelCopy = findModel.clone(); - - ReplaceInProjectManager.getInstance(project) - .searchAndShowUsages(manager, new MyUsageSearcherFactory(model, propertyName, selectedString), findModelCopy, presentation, processPresentation); - } - - //IDEA-54113 - private static void assureFindToolWindowRegistered(@Nonnull Project project) - { - UsageViewManager uvm = UsageViewManager.getInstance(project); - } - - private static FindModel createFindModel(FindManager findManager, String selectedString, String replaceWith) - { - FindModel findModel = (FindModel) findManager.getFindInProjectModel().clone(); - - findModel.setStringToFind(selectedString); - findModel.setStringToReplace(replaceWith); - findModel.setReplaceState(true); - findModel.setPromptOnReplace(true); - findModel.setCaseSensitive(true); - findModel.setRegularExpressions(false); - - return findModel; - } - - @Override - public void invoke(@Nonnull Project project, @Nonnull PsiElement[] elements, DataContext dataContext) - { - } - - private static class MyUsageSearcherFactory implements Supplier - { - private final MavenDomProjectModel myModel; - private final String myPropertyName; - private final String mySelectedString; - - public MyUsageSearcherFactory(MavenDomProjectModel model, String propertyName, String selectedString) - { - myModel = model; - myPropertyName = propertyName; - mySelectedString = selectedString; - } - - @Override - public UsageSearcher get() - { - return new UsageSearcher() - { - Set usages = new HashSet(); - - @Override - public void generate(final Processor processor) - { - ReadAction.run(() -> { - collectUsages(myModel); - for(MavenDomProjectModel model : MavenDomProjectProcessorUtils.getChildrenProjects(myModel)) - { - collectUsages(model); - } - - for(UsageInfo usage : usages) - { - processor.process(UsageInfo2UsageAdapter.CONVERTER.apply(usage)); - } - }); - } - - private void collectUsages(@Nonnull MavenDomProjectModel model) - { - if(model.isValid()) - { - final XmlElement root = model.getXmlElement(); - if(root != null) - { - root.acceptChildren(new XmlElementVisitor() - { - - @Override - public void visitXmlText(XmlText text) - { - XmlTag xmlTag = PsiTreeUtil.getParentOfType(text, XmlTag.class); - if(xmlTag != null && !xmlTag.getName().equals(myPropertyName)) - { - usages.addAll(getUsages(text)); - } - } - - @Override - public void visitXmlAttributeValue(XmlAttributeValue value) - { - XmlTag xmlTag = PsiTreeUtil.getParentOfType(value, XmlTag.class); - if(xmlTag != null && !xmlTag.equals(root)) - { - usages.addAll(getUsages(value)); - } - } - - @Override - public void visitXmlElement(XmlElement element) - { - element.acceptChildren(this); - } - }); - } - } - } - - @Nonnull - private Set getUsages(@Nonnull XmlElement xmlElement) - { - String s = xmlElement.getText(); - if(StringUtil.isEmptyOrSpaces(s)) - { - return Collections.emptySet(); - } - - int start = s.indexOf(mySelectedString); - if(start == -1) - { - return Collections.emptySet(); - } - - Set usages = new HashSet(); - - List ranges = getPropertiesTextRanges(s); - TextRange elementTextRange = xmlElement.getTextRange(); - PsiFile containingFile = xmlElement.getContainingFile(); - - do - { - int end = start + mySelectedString.length(); - boolean isInsideProperty = isInsideTextRanges(ranges, start, end); - if(!isInsideProperty) - { - usages - .add(new UsageInfo(containingFile, elementTextRange.getStartOffset() + start, elementTextRange.getStartOffset() + end)); - } - start = s.indexOf(mySelectedString, end); - } - while(start != -1); - - return usages; - } - }; - } - } - } - - private static List getPropertiesTextRanges(String s) - { - List ranges = new ArrayList(); - int startOffset = s.indexOf(PREFIX); - while(startOffset >= 0) - { - int endOffset = s.indexOf(SUFFIX, startOffset); - if(endOffset > startOffset) - { - if(s.substring(startOffset + PREFIX.length(), endOffset).contains(PREFIX)) - { - startOffset = s.indexOf(PREFIX, startOffset + 1); - } - else - { - ranges.add(new TextRange(startOffset, endOffset)); - startOffset = s.indexOf(PREFIX, endOffset); - } - } - else - { - break; - } - } - - return ranges; - } - - private static boolean isInsideTextRanges(@Nonnull Collection ranges, int start, int end) - { - for(TextRange range : ranges) - { - if((start >= range.getStartOffset() && (end <= range.getEndOffset() || start <= range.getEndOffset())) || - (end <= range.getEndOffset() && (end > range.getStartOffset()))) - { - return true; - } - } - return false; - } +public class IntroducePropertyAction extends BaseRefactoringAction { + private static String PREFIX = "${"; + private static String SUFFIX = "}"; + + public IntroducePropertyAction() { + setInjectedContext(true); + } + + @Override + protected boolean isAvailableInEditorOnly() { + return true; + } + + @Override + protected boolean isEnabledOnElements(@Nonnull PsiElement[] elements) { + return false; + } + + @Override + protected boolean isAvailableForLanguage(Language language) { + return true; + } + + @Override + protected RefactoringActionHandler getHandler(@Nonnull DataContext dataContext) { + return new MyRefactoringActionHandler(); + } + + @Override + protected boolean isAvailableForFile(PsiFile file) { + VirtualFile virtualFile = file.getVirtualFile(); + return MavenDomUtil.isMavenFile(file) + && virtualFile != null + && !(virtualFile.getFileSystem() instanceof ArchiveFileSystem); + } + + @Override + protected boolean isAvailableOnElementInEditorAndFile( + @Nonnull PsiElement element, + @Nonnull Editor editor, + @Nonnull PsiFile file, + @Nonnull DataContext context + ) { + return super.isAvailableOnElementInEditorAndFile(element, editor, file, context) + && getSelectedElementAndTextRange(editor, file) != null; + } + + @Nullable + public static Pair getSelectedElementAndTextRange(Editor editor, final PsiFile file) { + final int startOffset = editor.getSelectionModel().getSelectionStart(); + final int endOffset = editor.getSelectionModel().getSelectionEnd(); + + final PsiElement elementAtStart = file.findElementAt(startOffset); + if (elementAtStart == null) { + return null; + } + final PsiElement elementAtEnd = file.findElementAt(endOffset == startOffset ? endOffset : endOffset - 1); + if (elementAtEnd == null) { + return null; + } + + PsiElement elementAt = PsiTreeUtil.findCommonParent(elementAtStart, elementAtEnd); + if (elementAt instanceof XmlToken) { + elementAt = elementAt.getParent(); + } + + if (elementAt instanceof XmlText || elementAt instanceof XmlAttributeValue) { + TextRange range; + + if (editor.getSelectionModel().hasSelection()) { + range = new TextRange(startOffset, endOffset); + } + else { + range = elementAt.getTextRange(); + } + + return Pair.create((XmlElement)elementAt, range); + } + + return null; + } + + private static class MyRefactoringActionHandler implements RefactoringActionHandler { + @Override + public void invoke(@Nonnull final Project project, final Editor editor, PsiFile file, DataContext dataContext) { + PsiDocumentManager.getInstance(project).commitAllDocuments(); + + Pair elementAndRange = getSelectedElementAndTextRange(editor, file); + if (elementAndRange == null) { + return; + } + + XmlElement selectedElement = elementAndRange.first; + final TextRange range = elementAndRange.second; + + String stringValue = selectedElement.getText(); + if (stringValue == null) { + return; + } + + final MavenDomProjectModel model = MavenDomUtil.getMavenDomModel(file, MavenDomProjectModel.class); + final String selectedString = editor.getDocument().getText(range); + + List ranges = getPropertiesTextRanges(stringValue); + int offsetInElement = range.getStartOffset() - selectedElement.getTextOffset(); + + if (model == null || + StringUtil.isEmptyOrSpaces(selectedString) || + isInsideTextRanges(ranges, offsetInElement, offsetInElement + selectedString.length())) { + return; + } + + editor.getSelectionModel().setSelection(range.getStartOffset(), range.getEndOffset()); + + IntroducePropertyDialog dialog = new IntroducePropertyDialog(project, selectedElement, model, selectedString); + dialog.show(); + if (dialog.getExitCode() != DialogWrapper.OK_EXIT_CODE) { + return; + } + + final String propertyName = dialog.getEnteredName(); + final String replaceWith = PREFIX + propertyName + SUFFIX; + final MavenDomProjectModel selectedProject = dialog.getSelectedProject(); + + if (ReadonlyStatusHandler.getInstance(project).ensureFilesWritable(getFiles(file, selectedProject)).hasReadonlyFiles()) { + return; + } + + new WriteCommandAction(project) { + @Override + protected void run(Result result) throws Throwable { + editor.getDocument().replaceString(range.getStartOffset(), range.getEndOffset(), replaceWith); + PsiDocumentManager.getInstance(project).commitAllDocuments(); + + createMavenProperty(selectedProject, propertyName, selectedString); + + PsiDocumentManager.getInstance(project).commitAllDocuments(); + } + }.execute(); + + showFindUsages(project, propertyName, selectedString, replaceWith, selectedProject); + } + + private static VirtualFile[] getFiles(PsiFile file, MavenDomProjectModel model) { + Set virtualFiles = new HashSet(); + VirtualFile virtualFile = file.getVirtualFile(); + if (virtualFile != null) { + virtualFiles.add(virtualFile); + } + + XmlElement xmlElement = model.getXmlElement(); + if (xmlElement != null) { + VirtualFile vf = xmlElement.getContainingFile().getVirtualFile(); + if (vf != null) { + virtualFiles.add(vf); + } + } + + return VirtualFileUtil.toVirtualFileArray(virtualFiles); + } + + private static void createMavenProperty( + @Nonnull MavenDomProjectModel model, + @Nonnull String enteredName, + @Nonnull String selectedString + ) { + MavenDomProperties mavenDomProperties = model.getProperties(); + XmlTag xmlTag = mavenDomProperties.ensureTagExists(); + + XmlTag propertyTag = xmlTag.createChildTag(enteredName, xmlTag.getNamespace(), selectedString, false); + + xmlTag.add(propertyTag); + } + + private static void showFindUsages( + @Nonnull Project project, + @Nonnull String propertyName, + @Nonnull String selectedString, + @Nonnull String replaceWith, + @Nonnull MavenDomProjectModel model + ) { + UsageViewManager manager = UsageViewManager.getInstance(project); + if (manager == null) { + return; + } + + assureFindToolWindowRegistered(project); + + FindManager findManager = FindManager.getInstance(project); + FindModel findModel = createFindModel(findManager, selectedString, replaceWith); + + final UsageViewPresentation presentation = FindInProjectUtil.setupViewPresentation(true, findModel); + final FindUsagesProcessPresentation processPresentation = + FindInProjectUtil.setupProcessPresentation(project, true, presentation); + + findManager.getFindInProjectModel().copyFrom(findModel); + final FindModel findModelCopy = findModel.clone(); + + ReplaceInProjectManager.getInstance(project).searchAndShowUsages( + manager, + new MyUsageSearcherFactory(model, propertyName, selectedString), + findModelCopy, + presentation, + processPresentation + ); + } + + //IDEA-54113 + private static void assureFindToolWindowRegistered(@Nonnull Project project) { + UsageViewManager uvm = UsageViewManager.getInstance(project); + } + + private static FindModel createFindModel(FindManager findManager, String selectedString, String replaceWith) { + FindModel findModel = (FindModel)findManager.getFindInProjectModel().clone(); + + findModel.setStringToFind(selectedString); + findModel.setStringToReplace(replaceWith); + findModel.setReplaceState(true); + findModel.setPromptOnReplace(true); + findModel.setCaseSensitive(true); + findModel.setRegularExpressions(false); + + return findModel; + } + + @Override + public void invoke(@Nonnull Project project, @Nonnull PsiElement[] elements, DataContext dataContext) { + } + + private static class MyUsageSearcherFactory implements Supplier { + private final MavenDomProjectModel myModel; + private final String myPropertyName; + private final String mySelectedString; + + public MyUsageSearcherFactory(MavenDomProjectModel model, String propertyName, String selectedString) { + myModel = model; + myPropertyName = propertyName; + mySelectedString = selectedString; + } + + @Override + public UsageSearcher get() { + return new UsageSearcher() { + Set usages = new HashSet<>(); + + @Override + public void generate(final Processor processor) { + ReadAction.run(() -> { + collectUsages(myModel); + for (MavenDomProjectModel model : MavenDomProjectProcessorUtils.getChildrenProjects(myModel)) { + collectUsages(model); + } + + for (UsageInfo usage : usages) { + processor.process(UsageInfo2UsageAdapter.CONVERTER.apply(usage)); + } + }); + } + + private void collectUsages(@Nonnull MavenDomProjectModel model) { + if (model.isValid()) { + final XmlElement root = model.getXmlElement(); + if (root != null) { + root.acceptChildren(new XmlElementVisitor() { + + @Override + public void visitXmlText(XmlText text) { + XmlTag xmlTag = PsiTreeUtil.getParentOfType(text, XmlTag.class); + if (xmlTag != null && !xmlTag.getName().equals(myPropertyName)) { + usages.addAll(getUsages(text)); + } + } + + @Override + public void visitXmlAttributeValue(XmlAttributeValue value) { + XmlTag xmlTag = PsiTreeUtil.getParentOfType(value, XmlTag.class); + if (xmlTag != null && !xmlTag.equals(root)) { + usages.addAll(getUsages(value)); + } + } + + @Override + public void visitXmlElement(XmlElement element) { + element.acceptChildren(this); + } + }); + } + } + } + + @Nonnull + private Set getUsages(@Nonnull XmlElement xmlElement) { + String s = xmlElement.getText(); + if (StringUtil.isEmptyOrSpaces(s)) { + return Collections.emptySet(); + } + + int start = s.indexOf(mySelectedString); + if (start == -1) { + return Collections.emptySet(); + } + + Set usages = new HashSet<>(); + + List ranges = getPropertiesTextRanges(s); + TextRange elementTextRange = xmlElement.getTextRange(); + PsiFile containingFile = xmlElement.getContainingFile(); + + do { + int end = start + mySelectedString.length(); + boolean isInsideProperty = isInsideTextRanges(ranges, start, end); + if (!isInsideProperty) { + usages.add(new UsageInfo( + containingFile, + elementTextRange.getStartOffset() + start, + elementTextRange.getStartOffset() + end + )); + } + start = s.indexOf(mySelectedString, end); + } + while (start != -1); + + return usages; + } + }; + } + } + } + + private static List getPropertiesTextRanges(String s) { + List ranges = new ArrayList(); + int startOffset = s.indexOf(PREFIX); + while (startOffset >= 0) { + int endOffset = s.indexOf(SUFFIX, startOffset); + if (endOffset > startOffset) { + if (s.substring(startOffset + PREFIX.length(), endOffset).contains(PREFIX)) { + startOffset = s.indexOf(PREFIX, startOffset + 1); + } + else { + ranges.add(new TextRange(startOffset, endOffset)); + startOffset = s.indexOf(PREFIX, endOffset); + } + } + else { + break; + } + } + + return ranges; + } + + private static boolean isInsideTextRanges(@Nonnull Collection ranges, int start, int end) { + for (TextRange range : ranges) { + if ((start >= range.getStartOffset() && (end <= range.getEndOffset() || start <= range.getEndOffset())) + || (end <= range.getEndOffset() && end > range.getStartOffset())) { + return true; + } + } + return false; + } } diff --git a/plugin/src/main/java/org/jetbrains/idea/maven/dom/refactorings/introduce/IntroducePropertyDialog.java b/plugin/src/main/java/org/jetbrains/idea/maven/dom/refactorings/introduce/IntroducePropertyDialog.java index 90015211..a0c9991c 100644 --- a/plugin/src/main/java/org/jetbrains/idea/maven/dom/refactorings/introduce/IntroducePropertyDialog.java +++ b/plugin/src/main/java/org/jetbrains/idea/maven/dom/refactorings/introduce/IntroducePropertyDialog.java @@ -19,6 +19,7 @@ import consulo.language.editor.refactoring.ui.NameSuggestionsField; import consulo.language.psi.util.PsiTreeUtil; import consulo.project.Project; +import consulo.ui.annotation.RequiredUIAccess; import consulo.ui.ex.awt.DialogWrapper; import consulo.util.collection.ArrayUtil; import consulo.util.lang.Pair; @@ -29,12 +30,12 @@ import consulo.xml.util.xml.DomElement; import consulo.xml.util.xml.DomFileElement; import consulo.xml.util.xml.DomUtil; -import org.jetbrains.idea.maven.dom.MavenDomBundle; import org.jetbrains.idea.maven.dom.MavenDomProjectProcessorUtils; import org.jetbrains.idea.maven.dom.MavenDomUtil; import org.jetbrains.idea.maven.dom.model.MavenDomProjectModel; import org.jetbrains.idea.maven.dom.model.MavenDomProperties; import org.jetbrains.idea.maven.dom.model.MavenDomShortArtifactCoordinates; +import org.jetbrains.idea.maven.localize.MavenDomLocalize; import org.jetbrains.idea.maven.project.MavenProject; import org.jetbrains.idea.maven.utils.ComboBoxUtil; @@ -43,228 +44,250 @@ import java.awt.*; import java.util.List; import java.util.*; -import java.util.function.Function; public class IntroducePropertyDialog extends DialogWrapper { - private final Project myProject; - private final XmlElement myContext; - private final MavenDomProjectModel myMavenDomProjectModel; - - private final String mySelectedString; - private NameSuggestionsField myNameField; - private NameSuggestionsField.DataChanged myNameChangedListener; - - private JComboBox myMavenProjectsComboBox; - private JPanel myMainPanel; - private JPanel myFieldNamePanel; - - public IntroducePropertyDialog(@Nonnull Project project, - @Nonnull XmlElement context, - @Nonnull MavenDomProjectModel mavenDomProjectModel, - @Nonnull String selectedString) { - super(project, true); - myProject = project; - myContext = context; - myMavenDomProjectModel = mavenDomProjectModel; - - mySelectedString = selectedString; - - setTitle(MavenDomBundle.message("refactoring.introduce.property")); - init(); - } - - protected void dispose() { - myNameField.removeDataChangedListener(myNameChangedListener); - - super.dispose(); - } - - @Nonnull - protected Action[] createActions() { - return new Action[]{getOKAction(), getCancelAction()}; - } - - protected void init() { - super.init(); - updateOkStatus(); - } - - public String getEnteredName() { - return myNameField.getEnteredName().trim(); - } - - @Nonnull - public MavenDomProjectModel getSelectedProject() { - MavenDomProjectModel selectedItem = - (MavenDomProjectModel)ComboBoxUtil.getSelectedValue((DefaultComboBoxModel)myMavenProjectsComboBox.getModel()); - - return selectedItem == null ? myMavenDomProjectModel : selectedItem; - } - - private String[] getSuggestions() { - return getSuggestions(1); - } - - private String[] getSuggestions(int level) { - Collection result = new HashSet(); - - String value = mySelectedString.trim(); - boolean addUnqualifiedForm = true; - - XmlTag parent = PsiTreeUtil.getParentOfType(myContext, XmlTag.class, false); - - DomElement domParent = DomUtil.getDomElement(parent); - if (domParent != null) { - DomElement domSuperParent = domParent.getParent(); - DomFileElement domFile = DomUtil.getFileElement(domParent); - if (domSuperParent != null && domFile != null && domFile.getRootElement() == domSuperParent) { - value = domSuperParent.getXmlElementName(); - addUnqualifiedForm = false; - } - else { - MavenDomShortArtifactCoordinates coordinates = DomUtil.getParentOfType(domParent, MavenDomShortArtifactCoordinates.class, false); - if (coordinates != null && !(coordinates instanceof MavenDomProjectModel) && domParent != coordinates.getArtifactId()) { - String artifactId = coordinates.getArtifactId().getStringValue(); - if (!StringUtil.isEmptyOrSpaces(artifactId)) { - value = artifactId; - addUnqualifiedForm = false; - } - } - } + private final Project myProject; + private final XmlElement myContext; + private final MavenDomProjectModel myMavenDomProjectModel; + + private final String mySelectedString; + private NameSuggestionsField myNameField; + private NameSuggestionsField.DataChanged myNameChangedListener; + + private JComboBox myMavenProjectsComboBox; + private JPanel myMainPanel; + private JPanel myFieldNamePanel; + + public IntroducePropertyDialog( + @Nonnull Project project, + @Nonnull XmlElement context, + @Nonnull MavenDomProjectModel mavenDomProjectModel, + @Nonnull String selectedString + ) { + super(project, true); + myProject = project; + myContext = context; + myMavenDomProjectModel = mavenDomProjectModel; + + mySelectedString = selectedString; + + setTitle(MavenDomLocalize.refactoringIntroduceProperty()); + init(); } - while (true) { - String newValue = value.replaceAll(" ", " "); - if (newValue.equals(value)) break; - value = newValue; + @Override + protected void dispose() { + myNameField.removeDataChangedListener(myNameChangedListener); + + super.dispose(); } - value = value.replaceAll(" ", "."); - List parts = StringUtil.split(value, "."); - String shortValue = parts.get(parts.size() - 1); + @Nonnull + @Override + protected Action[] createActions() { + return new Action[]{getOKAction(), getCancelAction()}; + } - if (addUnqualifiedForm) { - result.add(value); - result.add(shortValue); + @Override + protected void init() { + super.init(); + updateOkStatus(); } - String suffix = ""; - while (parent != null && level != 0) { - suffix = parent.getName() + suffix; - result.add(suffix); - result.add(value + "." + suffix); - result.add(shortValue + "." + suffix); - suffix = "." + suffix; - parent = parent.getParentTag(); - level--; + public String getEnteredName() { + return myNameField.getEnteredName().trim(); } - result = new ArrayList(result); - Collections.sort((List)result, CodeStyleSettingsManager.getSettings(myProject).PREFER_LONGER_NAMES ? - StringLenComparator.getDescendingInstance() : StringLenComparator.getInstance()); - return ArrayUtil.toStringArray(result); - } - - private static String joinWords(@Nonnull String s, @Nonnull String delimiter) { - return joinWords(StringUtil.split(s, delimiter)); - } - - private static String joinWords(@Nonnull List stringList) { - StringBuffer sb = new StringBuffer(); - for (int i = 0; i < stringList.size(); i++) { - String word = stringList.get(i); - if (!StringUtil.isEmptyOrSpaces(word)) { - sb.append(i == 0 ? StringUtil.decapitalize(word.trim()) : StringUtil.capitalize(word.trim())); - } + @Nonnull + public MavenDomProjectModel getSelectedProject() { + MavenDomProjectModel selectedItem = + (MavenDomProjectModel)ComboBoxUtil.getSelectedValue((DefaultComboBoxModel)myMavenProjectsComboBox.getModel()); + + return selectedItem == null ? myMavenDomProjectModel : selectedItem; } - return sb.toString(); - } - protected JComponent createCenterPanel() { - myFieldNamePanel.setLayout(new BorderLayout()); + private String[] getSuggestions() { + return getSuggestions(1); + } - myNameField = new NameSuggestionsField(myProject); - myNameChangedListener = new NameSuggestionsField.DataChanged() { - public void dataChanged() { - updateOkStatus(); - } - }; - myNameField.addDataChangedListener(myNameChangedListener); - myNameField.setSuggestions(getSuggestions()); - - myFieldNamePanel.add(myNameField, BorderLayout.CENTER); - - List projects = getProjects(); - - ComboBoxUtil - .setModel(myMavenProjectsComboBox, new DefaultComboBoxModel(), projects, new Function>() { - public Pair apply(MavenDomProjectModel model) { - String projectName = model.getName().getStringValue(); - MavenProject mavenProject = MavenDomUtil.findProject(model); - if (mavenProject != null) { - projectName = mavenProject.getDisplayName(); - } - if (StringUtil.isEmptyOrSpaces(projectName)) { - projectName = "pom.xml"; - } - return Pair.create(projectName, model); + private String[] getSuggestions(int level) { + Collection result = new HashSet<>(); + + String value = mySelectedString.trim(); + boolean addUnqualifiedForm = true; + + XmlTag parent = PsiTreeUtil.getParentOfType(myContext, XmlTag.class, false); + + DomElement domParent = DomUtil.getDomElement(parent); + if (domParent != null) { + DomElement domSuperParent = domParent.getParent(); + DomFileElement domFile = DomUtil.getFileElement(domParent); + if (domSuperParent != null && domFile != null && domFile.getRootElement() == domSuperParent) { + value = domSuperParent.getXmlElementName(); + addUnqualifiedForm = false; + } + else { + MavenDomShortArtifactCoordinates coordinates = + DomUtil.getParentOfType(domParent, MavenDomShortArtifactCoordinates.class, false); + if (coordinates != null && !(coordinates instanceof MavenDomProjectModel) && domParent != coordinates.getArtifactId()) { + String artifactId = coordinates.getArtifactId().getStringValue(); + if (!StringUtil.isEmptyOrSpaces(artifactId)) { + value = artifactId; + addUnqualifiedForm = false; + } + } + } } - }); - myMavenProjectsComboBox.setSelectedItem(myMavenDomProjectModel); + while (true) { + String newValue = value.replaceAll(" ", " "); + if (newValue.equals(value)) { + break; + } + value = newValue; + } + + value = value.replaceAll(" ", "."); + List parts = StringUtil.split(value, "."); + String shortValue = parts.get(parts.size() - 1); + + if (addUnqualifiedForm) { + result.add(value); + result.add(shortValue); + } - return myMainPanel; - } + String suffix = ""; + while (parent != null && level != 0) { + suffix = parent.getName() + suffix; + result.add(suffix); + result.add(value + "." + suffix); + result.add(shortValue + "." + suffix); + suffix = "." + suffix; + parent = parent.getParentTag(); + level--; + } + + List listResult = new ArrayList<>(result); + Collections.sort( + listResult, + CodeStyleSettingsManager.getSettings(myProject).PREFER_LONGER_NAMES + ? StringLenComparator.getDescendingInstance() + : StringLenComparator.getInstance() + ); + return ArrayUtil.toStringArray(listResult); + } + private static String joinWords(@Nonnull String s, @Nonnull String delimiter) { + return joinWords(StringUtil.split(s, delimiter)); + } - private List getProjects() { - List projects = new ArrayList(); + private static String joinWords(@Nonnull List stringList) { + StringBuilder sb = new StringBuilder(); + for (int i = 0; i < stringList.size(); i++) { + String word = stringList.get(i); + if (!StringUtil.isEmptyOrSpaces(word)) { + sb.append(i == 0 ? StringUtil.decapitalize(word.trim()) : StringUtil.capitalize(word.trim())); + } + } + return sb.toString(); + } - projects.add(myMavenDomProjectModel); - projects.addAll(MavenDomProjectProcessorUtils.collectParentProjects(myMavenDomProjectModel)); + @Override + protected JComponent createCenterPanel() { + myFieldNamePanel.setLayout(new BorderLayout()); + + myNameField = new NameSuggestionsField(myProject); + myNameChangedListener = this::updateOkStatus; + myNameField.addDataChangedListener(myNameChangedListener); + myNameField.setSuggestions(getSuggestions()); + + myFieldNamePanel.add(myNameField, BorderLayout.CENTER); + + List projects = getProjects(); + + ComboBoxUtil.setModel( + myMavenProjectsComboBox, + new DefaultComboBoxModel(), + projects, + model -> { + String projectName = model.getName().getStringValue(); + MavenProject mavenProject = MavenDomUtil.findProject(model); + if (mavenProject != null) { + projectName = mavenProject.getDisplayName(); + } + if (StringUtil.isEmptyOrSpaces(projectName)) { + projectName = "pom.xml"; + } + return Pair.create(projectName, model); + } + ); + + myMavenProjectsComboBox.setSelectedItem(myMavenDomProjectModel); + + return myMainPanel; + } - return projects; - } - private void updateOkStatus() { - String text = getEnteredName(); + private List getProjects() { + List projects = new ArrayList<>(); - setOKActionEnabled(!StringUtil.isEmptyOrSpaces(text) && !isContainWrongSymbols(text) && !isPropertyExist(text)); - } + projects.add(myMavenDomProjectModel); + projects.addAll(MavenDomProjectProcessorUtils.collectParentProjects(myMavenDomProjectModel)); - private static boolean isContainWrongSymbols(@Nonnull String text) { - return text.length() == 0 || Character.isDigit(text.charAt(0)) || StringUtil.containsAnyChar(text, "\t ;*'\"\\/,()^&<>={}[]"); - } + return projects; + } - private boolean isPropertyExist(@Nonnull String text) { - MavenDomProjectModel project = getSelectedProject(); + private void updateOkStatus() { + String text = getEnteredName(); - if (isPropertyExist(text, project)) return true; + setOKActionEnabled(!StringUtil.isEmptyOrSpaces(text) && !isContainWrongSymbols(text) && !isPropertyExist(text)); + } - for (MavenDomProjectModel child : MavenDomProjectProcessorUtils.getChildrenProjects(project)) { - if (isPropertyExist(text, child)) return true; + private static boolean isContainWrongSymbols(@Nonnull String text) { + return text.length() == 0 + || Character.isDigit(text.charAt(0)) + || StringUtil.containsAnyChar(text, "\t ;*'\"\\/,()^&<>={}[]"); } - for (MavenDomProjectModel parent : MavenDomProjectProcessorUtils.collectParentProjects(project)) { - if (isPropertyExist(text, parent)) return true; + private boolean isPropertyExist(@Nonnull String text) { + MavenDomProjectModel project = getSelectedProject(); + + if (isPropertyExist(text, project)) { + return true; + } + + for (MavenDomProjectModel child : MavenDomProjectProcessorUtils.getChildrenProjects(project)) { + if (isPropertyExist(text, child)) { + return true; + } + } + + for (MavenDomProjectModel parent : MavenDomProjectProcessorUtils.collectParentProjects(project)) { + if (isPropertyExist(text, parent)) { + return true; + } + } + return false; } - return false; - } - private static boolean isPropertyExist(String propertyName, MavenDomProjectModel project) { - MavenDomProperties props = project.getProperties(); + private static boolean isPropertyExist(String propertyName, MavenDomProjectModel project) { + MavenDomProperties props = project.getProperties(); - XmlTag propsTag = props.getXmlTag(); - if (propsTag != null) { - for (XmlTag each : propsTag.getSubTags()) { - if (propertyName.equals(each.getName())) return true; - } + XmlTag propsTag = props.getXmlTag(); + if (propsTag != null) { + for (XmlTag each : propsTag.getSubTags()) { + if (propertyName.equals(each.getName())) { + return true; + } + } + } + return false; } - return false; - } - public JComponent getPreferredFocusedComponent() { - return myNameField.getFocusableComponent(); - } + @Override + @RequiredUIAccess + public JComponent getPreferredFocusedComponent() { + return myNameField.getFocusableComponent(); + } } \ No newline at end of file diff --git a/plugin/src/main/java/org/jetbrains/idea/maven/dom/references/MavenDependencyReferenceProvider.java b/plugin/src/main/java/org/jetbrains/idea/maven/dom/references/MavenDependencyReferenceProvider.java index f8b91f97..64fd1bb4 100644 --- a/plugin/src/main/java/org/jetbrains/idea/maven/dom/references/MavenDependencyReferenceProvider.java +++ b/plugin/src/main/java/org/jetbrains/idea/maven/dom/references/MavenDependencyReferenceProvider.java @@ -1,5 +1,6 @@ package org.jetbrains.idea.maven.dom.references; +import consulo.annotation.access.RequiredReadAction; import consulo.document.util.TextRange; import consulo.language.psi.*; import consulo.language.util.ProcessingContext; @@ -13,141 +14,167 @@ /** * Adds references to string like "groupId:artifactId:version" + * * @author Sergey Evdokimov */ public class MavenDependencyReferenceProvider extends PsiReferenceProvider implements MavenSoftAwareReferenceProvider { + private boolean mySoft = true; - private boolean mySoft = true; - - private boolean myCanHasVersion = true; - - @Nonnull - @Override - public PsiReference[] getReferencesByElement(@Nonnull PsiElement element, @Nonnull ProcessingContext context) { - ElementManipulator manipulator = ElementManipulators.getManipulator(element); - TextRange range = manipulator.getRangeInElement(element); - - String text = range.substring(element.getText()); - - int firstDelim = text.indexOf(':'); - - if (firstDelim == -1) { - return new PsiReference[]{ - new GroupReference(element, range, mySoft) - }; - } - - int secondDelim = myCanHasVersion ? text.indexOf(':', firstDelim + 1) : -1; - - int start = range.getStartOffset(); - - if (secondDelim == -1) { - return new PsiReference[]{ - new GroupReference(element, new TextRange(start, start + firstDelim), mySoft), - new ArtifactReference(text.substring(0, firstDelim), - element, new TextRange(start + firstDelim + 1, range.getEndOffset()), mySoft) - }; - } - - int lastDelim = text.indexOf(secondDelim + 1); - if (lastDelim == -1) { - lastDelim = text.length(); - } - - return new PsiReference[]{ - new GroupReference(element, new TextRange(start, start + firstDelim), mySoft), - - new ArtifactReference(text.substring(0, firstDelim), - element, new TextRange(start + firstDelim + 1, start + secondDelim), mySoft), - - new VersionReference(text.substring(0, firstDelim), text.substring(firstDelim + 1, secondDelim), - element, new TextRange(start + secondDelim + 1, start + lastDelim), mySoft) - }; - } - - @Override - public void setSoft(boolean soft) { - mySoft = soft; - } - - public boolean isCanHasVersion() { - return myCanHasVersion; - } - - public void setCanHasVersion(boolean canHasVersion) { - myCanHasVersion = canHasVersion; - } - - private static class GroupReference extends PsiReferenceBase { - - public GroupReference(PsiElement element, TextRange range, boolean soft) { - super(element, range, soft); - } - - @Nullable - @Override - public PsiElement resolve() { - return null; - } + private boolean myCanHasVersion = true; @Nonnull @Override - public Object[] getVariants() { - return MavenProjectIndicesManager.getInstance(getElement().getProject()).getGroupIds().toArray(); - } - } - - public static class ArtifactReference extends PsiReferenceBase { - - private final String myGroupId; - - public ArtifactReference(@Nonnull String groupId, @Nonnull PsiElement element, @Nonnull TextRange range, @Nonnull boolean soft) { - super(element, range, soft); - myGroupId = groupId; + @RequiredReadAction + public PsiReference[] getReferencesByElement(@Nonnull PsiElement element, @Nonnull ProcessingContext context) { + ElementManipulator manipulator = ElementManipulators.getManipulator(element); + TextRange range = manipulator.getRangeInElement(element); + + String text = range.substring(element.getText()); + + int firstDelim = text.indexOf(':'); + + if (firstDelim == -1) { + return new PsiReference[]{ + new GroupReference(element, range, mySoft) + }; + } + + int secondDelim = myCanHasVersion ? text.indexOf(':', firstDelim + 1) : -1; + + int start = range.getStartOffset(); + + if (secondDelim == -1) { + return new PsiReference[]{ + new GroupReference(element, new TextRange(start, start + firstDelim), mySoft), + new ArtifactReference( + text.substring(0, firstDelim), + element, + new TextRange(start + firstDelim + 1, range.getEndOffset()), + mySoft + ) + }; + } + + int lastDelim = text.indexOf(secondDelim + 1); + if (lastDelim == -1) { + lastDelim = text.length(); + } + + return new PsiReference[]{ + new GroupReference(element, new TextRange(start, start + firstDelim), mySoft), + + new ArtifactReference( + text.substring(0, firstDelim), + element, + new TextRange(start + firstDelim + 1, start + secondDelim), + mySoft + ), + + new VersionReference( + text.substring(0, firstDelim), + text.substring(firstDelim + 1, secondDelim), + element, + new TextRange(start + secondDelim + 1, start + lastDelim), + mySoft + ) + }; } - @Nullable @Override - public PsiElement resolve() { - return null; + public void setSoft(boolean soft) { + mySoft = soft; } - @Nonnull - @Override - public Object[] getVariants() { - if (StringUtil.isEmptyOrSpaces(myGroupId)) return ArrayUtil.EMPTY_OBJECT_ARRAY; - - MavenProjectIndicesManager manager = MavenProjectIndicesManager.getInstance(getElement().getProject()); - return manager.getArtifactIds(myGroupId).toArray(); + public boolean isCanHasVersion() { + return myCanHasVersion; } - } - - public static class VersionReference extends PsiReferenceBase { - - private final String myGroupId; - private final String myArtifactId; - public VersionReference(@Nonnull String groupId, @Nonnull String artifactId, @Nonnull PsiElement element, @Nonnull TextRange range, @Nonnull boolean soft) { - super(element, range, soft); - myGroupId = groupId; - myArtifactId = artifactId; + public void setCanHasVersion(boolean canHasVersion) { + myCanHasVersion = canHasVersion; } - @Nullable - @Override - public PsiElement resolve() { - return null; + private static class GroupReference extends PsiReferenceBase { + + public GroupReference(PsiElement element, TextRange range, boolean soft) { + super(element, range, soft); + } + + @Nullable + @Override + @RequiredReadAction + public PsiElement resolve() { + return null; + } + + @Nonnull + @Override + @RequiredReadAction + public Object[] getVariants() { + return MavenProjectIndicesManager.getInstance(getElement().getProject()).getGroupIds().toArray(); + } } - @Nonnull - @Override - public Object[] getVariants() { - if (StringUtil.isEmptyOrSpaces(myGroupId) || StringUtil.isEmptyOrSpaces(myArtifactId)) { - return ArrayUtil.EMPTY_OBJECT_ARRAY; - } + public static class ArtifactReference extends PsiReferenceBase { + private final String myGroupId; + + public ArtifactReference(@Nonnull String groupId, @Nonnull PsiElement element, @Nonnull TextRange range, boolean soft) { + super(element, range, soft); + myGroupId = groupId; + } + + @Nullable + @Override + @RequiredReadAction + public PsiElement resolve() { + return null; + } + + @Nonnull + @Override + @RequiredReadAction + public Object[] getVariants() { + if (StringUtil.isEmptyOrSpaces(myGroupId)) { + return ArrayUtil.EMPTY_OBJECT_ARRAY; + } + + MavenProjectIndicesManager manager = MavenProjectIndicesManager.getInstance(getElement().getProject()); + return manager.getArtifactIds(myGroupId).toArray(); + } + } - MavenProjectIndicesManager manager = MavenProjectIndicesManager.getInstance(getElement().getProject()); - return manager.getVersions(myGroupId, myArtifactId).toArray(); + public static class VersionReference extends PsiReferenceBase { + private final String myGroupId; + private final String myArtifactId; + + public VersionReference( + @Nonnull String groupId, + @Nonnull String artifactId, + @Nonnull PsiElement element, + @Nonnull TextRange range, + boolean soft + ) { + super(element, range, soft); + myGroupId = groupId; + myArtifactId = artifactId; + } + + @Nullable + @Override + @RequiredReadAction + public PsiElement resolve() { + return null; + } + + @Nonnull + @Override + @RequiredReadAction + public Object[] getVariants() { + if (StringUtil.isEmptyOrSpaces(myGroupId) || StringUtil.isEmptyOrSpaces(myArtifactId)) { + return ArrayUtil.EMPTY_OBJECT_ARRAY; + } + + MavenProjectIndicesManager manager = MavenProjectIndicesManager.getInstance(getElement().getProject()); + return manager.getVersions(myGroupId, myArtifactId).toArray(); + } } - } } diff --git a/plugin/src/main/java/org/jetbrains/idea/maven/dom/references/MavenDirectoryPathReferenceConverter.java b/plugin/src/main/java/org/jetbrains/idea/maven/dom/references/MavenDirectoryPathReferenceConverter.java index c99b04c3..fb815aeb 100644 --- a/plugin/src/main/java/org/jetbrains/idea/maven/dom/references/MavenDirectoryPathReferenceConverter.java +++ b/plugin/src/main/java/org/jetbrains/idea/maven/dom/references/MavenDirectoryPathReferenceConverter.java @@ -21,8 +21,7 @@ * @author Sergey Evdokimov */ public class MavenDirectoryPathReferenceConverter extends MavenPathReferenceConverter { - - public MavenDirectoryPathReferenceConverter() { - super(FileReferenceSet.DIRECTORY_FILTER); - } + public MavenDirectoryPathReferenceConverter() { + super(FileReferenceSet.DIRECTORY_FILTER); + } } diff --git a/plugin/src/main/java/org/jetbrains/idea/maven/dom/references/MavenFilteredPropertyPsiReference.java b/plugin/src/main/java/org/jetbrains/idea/maven/dom/references/MavenFilteredPropertyPsiReference.java index 6a4cc08f..46b195e8 100644 --- a/plugin/src/main/java/org/jetbrains/idea/maven/dom/references/MavenFilteredPropertyPsiReference.java +++ b/plugin/src/main/java/org/jetbrains/idea/maven/dom/references/MavenFilteredPropertyPsiReference.java @@ -16,6 +16,8 @@ package org.jetbrains.idea.maven.dom.references; import com.intellij.lang.properties.IProperty; +import consulo.annotation.access.RequiredReadAction; +import consulo.annotation.access.RequiredWriteAction; import consulo.document.util.TextRange; import consulo.language.psi.PsiElement; import consulo.language.psi.PsiFile; @@ -30,44 +32,54 @@ import java.util.Set; public class MavenFilteredPropertyPsiReference extends MavenPropertyPsiReference { - public MavenFilteredPropertyPsiReference(MavenProject mavenProject, PsiElement element, String text, TextRange range) { - super(mavenProject, element, text, range, true); - } + public MavenFilteredPropertyPsiReference(MavenProject mavenProject, PsiElement element, String text, TextRange range) { + super(mavenProject, element, text, range, true); + } - @Override - protected PsiElement doResolve() { - PsiElement result = super.doResolve(); - if (result != null) return result; + @Override + @RequiredReadAction + protected PsiElement doResolve() { + PsiElement result = super.doResolve(); + if (result != null) { + return result; + } - for (String each : myMavenProject.getFilters()) { - VirtualFile file = LocalFileSystem.getInstance().findFileByPath(each); - if (file == null) continue; - IProperty property = MavenDomUtil.findProperty(myProject, file, myText); - if (property != null) return property.getPsiElement(); - } + for (String each : myMavenProject.getFilters()) { + VirtualFile file = LocalFileSystem.getInstance().findFileByPath(each); + if (file == null) { + continue; + } + IProperty property = MavenDomUtil.findProperty(myProject, file, myText); + if (property != null) { + return property.getPsiElement(); + } + } - return null; - } + return null; + } - @Override - protected void collectVariants(List result, Set variants) { - super.collectVariants(result, variants); + @Override + @RequiredReadAction + protected void collectVariants(List result, Set variants) { + super.collectVariants(result, variants); - for (String each : myMavenProject.getFilters()) { - VirtualFile file = LocalFileSystem.getInstance().findFileByPath(each); - if (file == null) continue; - collectPropertiesFileVariants(MavenDomUtil.getPropertiesFile(myProject, file), null, result, variants); + for (String each : myMavenProject.getFilters()) { + VirtualFile file = LocalFileSystem.getInstance().findFileByPath(each); + if (file == null) { + continue; + } + collectPropertiesFileVariants(MavenDomUtil.getPropertiesFile(myProject, file), null, result, variants); + } } - } - @Override - public PsiElement handleElementRename(String newElementName) throws IncorrectOperationException - { - String newText = myRange.replace(myElement.getText(), newElementName); - PsiFile psiFile = myElement.getContainingFile(); - String newFileText = myElement.getTextRange().replace(psiFile.getText(), newText); - PsiFile f = PsiFileFactory.getInstance(myProject).createFileFromText("__" + psiFile.getName(), psiFile.getLanguage(), newFileText); - PsiElement el = f.findElementAt(myElement.getTextOffset()); - return myElement.replace(el); - } + @Override + @RequiredWriteAction + public PsiElement handleElementRename(String newElementName) throws IncorrectOperationException { + String newText = myRange.replace(myElement.getText(), newElementName); + PsiFile psiFile = myElement.getContainingFile(); + String newFileText = myElement.getTextRange().replace(psiFile.getText(), newText); + PsiFile f = PsiFileFactory.getInstance(myProject).createFileFromText("__" + psiFile.getName(), psiFile.getLanguage(), newFileText); + PsiElement el = f.findElementAt(myElement.getTextOffset()); + return myElement.replace(el); + } } \ No newline at end of file diff --git a/plugin/src/main/java/org/jetbrains/idea/maven/dom/references/MavenFilteredPropertyPsiReferenceProvider.java b/plugin/src/main/java/org/jetbrains/idea/maven/dom/references/MavenFilteredPropertyPsiReferenceProvider.java index f797c042..e6b4f8d9 100644 --- a/plugin/src/main/java/org/jetbrains/idea/maven/dom/references/MavenFilteredPropertyPsiReferenceProvider.java +++ b/plugin/src/main/java/org/jetbrains/idea/maven/dom/references/MavenFilteredPropertyPsiReferenceProvider.java @@ -15,6 +15,7 @@ */ package org.jetbrains.idea.maven.dom.references; +import consulo.annotation.access.RequiredReadAction; import consulo.document.util.TextRange; import consulo.language.psi.PsiElement; import consulo.language.psi.PsiReference; @@ -35,164 +36,135 @@ import java.util.regex.Matcher; import java.util.regex.Pattern; -public class MavenFilteredPropertyPsiReferenceProvider extends PsiReferenceProvider -{ - private static final Key KEY = Key.create("MavenFilteredPropertyPsiReferenceProvider:delimitersKey"); - - public static final Pattern DEFAULT_DELIMITERS = MavenPropertyResolver.PATTERN; - - @Nonnull - public static Pattern getDelimitersPattern(MavenProject mavenProject) - { - Pattern res = mavenProject.getCachedValue(KEY); - if(res == null) - { - Element cfg = mavenProject.getPluginConfiguration("org.apache.maven.plugins", "maven-resources-plugin"); - if(cfg == null) - { - res = DEFAULT_DELIMITERS; - } - else - { - List delimiters = MavenJDOMUtil.findChildrenValuesByPath(cfg, "delimiters", "delimiter"); - if(delimiters.isEmpty() || delimiters.size() > 10) - { - res = DEFAULT_DELIMITERS; - } - else - { - StringBuilder patternBuilder = new StringBuilder(); - - for(String delimiter : delimiters) - { - delimiter = delimiter.trim(); - if(delimiter.isEmpty()) - { - continue; - } - - int ind = delimiter.indexOf('*'); - if(ind >= 0) - { - appendDelimiter(patternBuilder, delimiter.substring(0, ind), delimiter.substring(ind + 1)); - } - else - { - appendDelimiter(patternBuilder, delimiter, delimiter); - } - } - - // is not used if custom delimiters are not present. - boolean useDefaultDelimiters = true; - - String useDefaultDelimitersText = cfg.getChildText("useDefaultDelimiters"); - if(StringUtil.isNotEmpty(useDefaultDelimitersText)) - { - useDefaultDelimiters = Boolean.parseBoolean(useDefaultDelimitersText); - } - - if(useDefaultDelimiters) - { - appendDelimiter(patternBuilder, "${", "}"); - appendDelimiter(patternBuilder, "@", "@"); - } - - res = Pattern.compile(patternBuilder.toString()); - } - } - - res = mavenProject.putCachedValue(KEY, res); - } - - return res; - } - - private static void appendDelimiter(StringBuilder pattern, String prefix, String suffix) - { - if(pattern.length() > 0) - { - pattern.append('|'); - } - pattern.append(Pattern.quote(prefix)).append("(.+?)").append(Pattern.quote(suffix)); - } - - private static boolean shouldAddReference(@Nonnull PsiElement element) - { - if(element.getFirstChild() == element.getLastChild()) - { - return true; // Add to all leaf elements - } - - if(element instanceof XmlAttribute) - { - return true; - } - - return false; // Don't add references to all element to avoid performance problem. - } - - @Nonnull - @Override - public PsiReference[] getReferencesByElement(@Nonnull PsiElement element, @Nonnull ProcessingContext context) - { - if(!shouldAddReference(element)) - { - // Add reference to element with one child or leaf element only to avoid performance problem. - return PsiReference.EMPTY_ARRAY; - } - - if(!MavenDomUtil.isFilteredResourceFile(element)) - { - return PsiReference.EMPTY_ARRAY; - } - - String text = element.getText(); - if(StringUtil.isEmptyOrSpaces(text)) - { - return PsiReference.EMPTY_ARRAY; - } - - MavenProject mavenProject = MavenDomUtil.findContainingProject(element); - if(mavenProject == null) - { - return PsiReference.EMPTY_ARRAY; - } - - List res = null; - - Pattern pattern = getDelimitersPattern(mavenProject); - - Matcher matcher = pattern.matcher(text); - - int groupCount = matcher.groupCount(); - - while(matcher.find()) - { - String propertyName = null; - int from = 0; - - for(int i = 0; i < groupCount; i++) - { - propertyName = matcher.group(i + 1); - if(propertyName != null) - { - from = matcher.start(i + 1); - break; - } - } - - assert propertyName != null; - - if(res == null) - { - res = new ArrayList(); - } - - TextRange range = TextRange.from(from, propertyName.length()); - - res.add(new MavenFilteredPropertyPsiReference(mavenProject, element, propertyName, range)); - } - - return res == null ? PsiReference.EMPTY_ARRAY : res.toArray(new PsiReference[res.size()]); - } +public class MavenFilteredPropertyPsiReferenceProvider extends PsiReferenceProvider { + private static final Key KEY = Key.create("MavenFilteredPropertyPsiReferenceProvider:delimitersKey"); + + public static final Pattern DEFAULT_DELIMITERS = MavenPropertyResolver.PATTERN; + + @Nonnull + public static Pattern getDelimitersPattern(MavenProject mavenProject) { + Pattern res = mavenProject.getCachedValue(KEY); + if (res == null) { + Element cfg = mavenProject.getPluginConfiguration("org.apache.maven.plugins", "maven-resources-plugin"); + if (cfg == null) { + res = DEFAULT_DELIMITERS; + } + else { + List delimiters = MavenJDOMUtil.findChildrenValuesByPath(cfg, "delimiters", "delimiter"); + if (delimiters.isEmpty() || delimiters.size() > 10) { + res = DEFAULT_DELIMITERS; + } + else { + StringBuilder patternBuilder = new StringBuilder(); + + for (String delimiter : delimiters) { + delimiter = delimiter.trim(); + if (delimiter.isEmpty()) { + continue; + } + + int ind = delimiter.indexOf('*'); + if (ind >= 0) { + appendDelimiter(patternBuilder, delimiter.substring(0, ind), delimiter.substring(ind + 1)); + } + else { + appendDelimiter(patternBuilder, delimiter, delimiter); + } + } + + // is not used if custom delimiters are not present. + boolean useDefaultDelimiters = true; + + String useDefaultDelimitersText = cfg.getChildText("useDefaultDelimiters"); + if (StringUtil.isNotEmpty(useDefaultDelimitersText)) { + useDefaultDelimiters = Boolean.parseBoolean(useDefaultDelimitersText); + } + + if (useDefaultDelimiters) { + appendDelimiter(patternBuilder, "${", "}"); + appendDelimiter(patternBuilder, "@", "@"); + } + + res = Pattern.compile(patternBuilder.toString()); + } + } + + res = mavenProject.putCachedValue(KEY, res); + } + + return res; + } + + private static void appendDelimiter(StringBuilder pattern, String prefix, String suffix) { + if (pattern.length() > 0) { + pattern.append('|'); + } + pattern.append(Pattern.quote(prefix)).append("(.+?)").append(Pattern.quote(suffix)); + } + + @RequiredReadAction + private static boolean shouldAddReference(@Nonnull PsiElement element) { + if (element.getFirstChild() == element.getLastChild()) { + return true; // Add to all leaf elements + } + + return element instanceof XmlAttribute; + } + + @Nonnull + @Override + @RequiredReadAction + public PsiReference[] getReferencesByElement(@Nonnull PsiElement element, @Nonnull ProcessingContext context) { + if (!shouldAddReference(element)) { + // Add reference to element with one child or leaf element only to avoid performance problem. + return PsiReference.EMPTY_ARRAY; + } + + if (!MavenDomUtil.isFilteredResourceFile(element)) { + return PsiReference.EMPTY_ARRAY; + } + + String text = element.getText(); + if (StringUtil.isEmptyOrSpaces(text)) { + return PsiReference.EMPTY_ARRAY; + } + + MavenProject mavenProject = MavenDomUtil.findContainingProject(element); + if (mavenProject == null) { + return PsiReference.EMPTY_ARRAY; + } + + List res = null; + + Pattern pattern = getDelimitersPattern(mavenProject); + + Matcher matcher = pattern.matcher(text); + + int groupCount = matcher.groupCount(); + + while (matcher.find()) { + String propertyName = null; + int from = 0; + + for (int i = 0; i < groupCount; i++) { + propertyName = matcher.group(i + 1); + if (propertyName != null) { + from = matcher.start(i + 1); + break; + } + } + + assert propertyName != null; + + if (res == null) { + res = new ArrayList<>(); + } + + TextRange range = TextRange.from(from, propertyName.length()); + + res.add(new MavenFilteredPropertyPsiReference(mavenProject, element, propertyName, range)); + } + + return res == null ? PsiReference.EMPTY_ARRAY : res.toArray(new PsiReference[res.size()]); + } } diff --git a/plugin/src/main/java/org/jetbrains/idea/maven/dom/references/MavenModelClassesProperties.java b/plugin/src/main/java/org/jetbrains/idea/maven/dom/references/MavenModelClassesProperties.java index 7d8aa1c1..6844217f 100644 --- a/plugin/src/main/java/org/jetbrains/idea/maven/dom/references/MavenModelClassesProperties.java +++ b/plugin/src/main/java/org/jetbrains/idea/maven/dom/references/MavenModelClassesProperties.java @@ -16,7 +16,7 @@ package org.jetbrains.idea.maven.dom.references; import com.google.common.collect.ImmutableMap; -import com.intellij.java.language.psi.CommonClassNames; +import consulo.java.language.module.util.JavaClassNames; import javax.annotation.Nonnull; import java.util.Collections; @@ -28,205 +28,215 @@ */ public class MavenModelClassesProperties { - private static final Map> PROPERTIES_MAP; - - public static final String MAVEN_PROJECT_CLASS = "org.apache.maven.project.MavenProject"; - public static final String MAVEN_MODEL_CLASS = "org.apache.maven.model.Model"; - - static { - Map> res = new HashMap>(); - - res.put(MAVEN_PROJECT_CLASS, ImmutableMap.builder() - .put("parentFile", "java.io.File") - .put("artifact", "org.apache.maven.artifact.Artifact") - .put("model", MAVEN_MODEL_CLASS) - .put("parent", MAVEN_PROJECT_CLASS) - .put("file", "java.io.File") - .put("dependencies", CommonClassNames.JAVA_UTIL_LIST) - .put("compileSourceRoots", CommonClassNames.JAVA_UTIL_LIST) - .put("scriptSourceRoots", CommonClassNames.JAVA_UTIL_LIST) - .put("testCompileSourceRoots", CommonClassNames.JAVA_UTIL_LIST) - .put("compileClasspathElements", CommonClassNames.JAVA_UTIL_LIST) - .put("compileArtifacts", CommonClassNames.JAVA_UTIL_LIST) - .put("compileDependencies", CommonClassNames.JAVA_UTIL_LIST) - .put("testClasspathElements", CommonClassNames.JAVA_UTIL_LIST) - .put("testArtifacts", CommonClassNames.JAVA_UTIL_LIST) - .put("testDependencies", CommonClassNames.JAVA_UTIL_LIST) - .put("runtimeClasspathElements", CommonClassNames.JAVA_UTIL_LIST) - .put("runtimeArtifacts", CommonClassNames.JAVA_UTIL_LIST) - .put("runtimeDependencies", CommonClassNames.JAVA_UTIL_LIST) - .put("systemClasspathElements", CommonClassNames.JAVA_UTIL_LIST) - .put("systemArtifacts", CommonClassNames.JAVA_UTIL_LIST) - .put("systemDependencies", CommonClassNames.JAVA_UTIL_LIST) - .put("modelVersion", CommonClassNames.JAVA_LANG_STRING) - .put("id", CommonClassNames.JAVA_LANG_STRING) - .put("groupId", CommonClassNames.JAVA_LANG_STRING) - .put("artifactId", CommonClassNames.JAVA_LANG_STRING) - .put("version", CommonClassNames.JAVA_LANG_STRING) - .put("packaging", CommonClassNames.JAVA_LANG_STRING) - .put("name", CommonClassNames.JAVA_LANG_STRING) - .put("inceptionYear", CommonClassNames.JAVA_LANG_STRING) - .put("url", CommonClassNames.JAVA_LANG_STRING) - .put("prerequisites", "org.apache.maven.model.Prerequisites") - .put("issueManagement", "org.apache.maven.model.IssueManagement") - .put("ciManagement", "org.apache.maven.model.CiManagement") - .put("description", CommonClassNames.JAVA_LANG_STRING) - .put("organization", "org.apache.maven.model.Organization") - .put("scm", "org.apache.maven.model.Scm") - .put("mailingLists", CommonClassNames.JAVA_UTIL_LIST) - .put("developers", CommonClassNames.JAVA_UTIL_LIST) - .put("contributors", CommonClassNames.JAVA_UTIL_LIST) - .put("build", "org.apache.maven.model.Build") - - .put("resources", CommonClassNames.JAVA_UTIL_LIST) - .put("testResources", CommonClassNames.JAVA_UTIL_LIST) - .put("reporting", "org.apache.maven.model.Reporting") - .put("licenses", CommonClassNames.JAVA_UTIL_LIST) - .put("artifacts", CommonClassNames.JAVA_UTIL_LIST) - .put("artifactMap", CommonClassNames.JAVA_UTIL_LIST) - .put("pluginArtifacts", CommonClassNames.JAVA_UTIL_LIST) - .put("pluginArtifactMap", CommonClassNames.JAVA_UTIL_LIST) - .put("reportArtifacts", CommonClassNames.JAVA_UTIL_LIST) - .put("reportArtifactMap", CommonClassNames.JAVA_UTIL_LIST) - .put("extensionArtifacts", CommonClassNames.JAVA_UTIL_LIST) - .put("extensionArtifactMap", CommonClassNames.JAVA_UTIL_LIST) - .put("parentArtifact", CommonClassNames.JAVA_UTIL_LIST) - .put("repositories", CommonClassNames.JAVA_UTIL_LIST) - .put("reportPlugins", CommonClassNames.JAVA_UTIL_LIST) - .put("buildPlugins", CommonClassNames.JAVA_UTIL_LIST) - .put("modules", CommonClassNames.JAVA_UTIL_LIST) - .put("modelBuild", "org.apache.maven.model.Build") - .put("remoteArtifactRepositories", CommonClassNames.JAVA_UTIL_LIST) - .put("pluginArtifactRepositories", CommonClassNames.JAVA_UTIL_LIST) - .put("distributionManagementArtifactRepository", "org.apache.maven.artifact.repository.ArtifactRepository") - .put("pluginRepositories", CommonClassNames.JAVA_UTIL_LIST) - .put("remoteProjectRepositories", CommonClassNames.JAVA_UTIL_LIST) - .put("remotePluginRepositories", CommonClassNames.JAVA_UTIL_LIST) - .put("activeProfiles", CommonClassNames.JAVA_UTIL_LIST) - .put("injectedProfileIds", CommonClassNames.JAVA_UTIL_LIST) - .put("attachedArtifacts", CommonClassNames.JAVA_UTIL_LIST) - .put("executionProject", MAVEN_PROJECT_CLASS) - .put("collectedProjects", CommonClassNames.JAVA_UTIL_LIST) - .put("dependencyArtifacts", CommonClassNames.JAVA_UTIL_LIST) - .put("managedVersionMap", CommonClassNames.JAVA_UTIL_LIST) - .put("buildExtensions", CommonClassNames.JAVA_UTIL_LIST) - .put("properties", CommonClassNames.JAVA_UTIL_LIST) - .put("filters", CommonClassNames.JAVA_UTIL_LIST) - .put("projectReferences", CommonClassNames.JAVA_UTIL_LIST) - .put("executionRoot", "boolean") - .put("defaultGoal", CommonClassNames.JAVA_UTIL_LIST) - .put("releaseArtifactRepository", "org.apache.maven.artifact.repository.ArtifactRepository") - .put("snapshotArtifactRepository", "org.apache.maven.artifact.repository.ArtifactRepository") - .put("classRealm", "org.codehaus.plexus.classworlds.realm.ClassRealm") - .put("extensionDependencyFilter", "org.sonatype.aether.graph.DependencyFilter") - .put("projectBuildingRequest", "org.apache.maven.project.ProjectBuildingRequest") - - .build() - ); - - res.put(MAVEN_MODEL_CLASS, ImmutableMap.builder() - .put("modelVersion", CommonClassNames.JAVA_LANG_STRING) - .put("parent", MAVEN_PROJECT_CLASS) - .put("groupId", CommonClassNames.JAVA_LANG_STRING) - .put("artifactId", CommonClassNames.JAVA_LANG_STRING) - .put("version", CommonClassNames.JAVA_LANG_STRING) - .put("packaging", CommonClassNames.JAVA_LANG_STRING) - .put("name", CommonClassNames.JAVA_LANG_STRING) - .put("description", CommonClassNames.JAVA_LANG_STRING) - .put("url", CommonClassNames.JAVA_LANG_STRING) - .put("inceptionYear", CommonClassNames.JAVA_LANG_STRING) - .put("organization", "org.apache.maven.model.Organization") - .put("licenses", CommonClassNames.JAVA_UTIL_LIST) - .put("developers", CommonClassNames.JAVA_UTIL_LIST) - .put("contributors", CommonClassNames.JAVA_UTIL_LIST) - .put("mailingLists", CommonClassNames.JAVA_UTIL_LIST) - .put("prerequisites", "org.apache.maven.model.Prerequisites") - .put("scm", "org.apache.maven.model.Scm") - .put("issueManagement", "org.apache.maven.model.IssueManagement") - .put("ciManagement", "org.apache.maven.model.CiManagement") - .put("build", "org.apache.maven.model.Build") - .put("profiles", CommonClassNames.JAVA_UTIL_LIST) - .put("modelEncoding", CommonClassNames.JAVA_LANG_STRING) - .put("pomFile", "java.io.File") - .put("projectDirectory", "java.io.File") - .put("id", CommonClassNames.JAVA_LANG_STRING) - - .put("repositories", CommonClassNames.JAVA_UTIL_LIST) - .put("dependencies", CommonClassNames.JAVA_UTIL_LIST) - .put("modules", CommonClassNames.JAVA_UTIL_LIST) - .put("pluginRepositories", CommonClassNames.JAVA_UTIL_LIST) - .put("properties", CommonClassNames.JAVA_UTIL_LIST) - .put("reports", CommonClassNames.JAVA_LANG_OBJECT) - .put("reporting", "org.apache.maven.model.Reporting") - .build() - ); - - res.put(CommonClassNames.JAVA_UTIL_LIST, ImmutableMap.of("empty", "boolean")); - - res.put("org.apache.maven.model.Build", ImmutableMap.builder() - .put("extensions", CommonClassNames.JAVA_UTIL_LIST) - .put("filters", CommonClassNames.JAVA_UTIL_LIST) - .put("resources", CommonClassNames.JAVA_UTIL_LIST) - .put("testResources", CommonClassNames.JAVA_UTIL_LIST) - .build()); - - res.put("java.io.File", ImmutableMap.builder() - .put("prefixLength", "long") - .put("name", CommonClassNames.JAVA_LANG_STRING) - .put("parent", CommonClassNames.JAVA_LANG_STRING) - .put("parentFile", "java.io.File") - .put("path", CommonClassNames.JAVA_LANG_STRING) - .put("absolute", "boolean") - .put("absolutePath", CommonClassNames.JAVA_LANG_STRING) - .put("absoluteFile", "java.io.File") - .put("canonicalPath", CommonClassNames.JAVA_LANG_STRING) - .put("canonicalFile", "java.io.File") - .put("directory", "boolean") - .put("file", "boolean") - .put("hidden", "boolean") - .put("totalSpace", "long") - .put("freeSpace", "long") - .put("usableSpace", "long") - .build()); - - PROPERTIES_MAP = res; - } - - public static boolean isPathValid(@Nonnull String className, @Nonnull String path) { - Map cMap = PROPERTIES_MAP.get(className); - if (cMap == null) return false; - - int idx = 0; - - do { - int i = path.indexOf('.', idx); - if (i == -1) { - return cMap.containsKey(path.substring(idx)); - } - - cMap = PROPERTIES_MAP.get(cMap.get(path.substring(idx, i))); - if (cMap == null) return false; - - idx = i + 1; - } while (true); - } - - public static Map getCompletionVariants(@Nonnull String className, @Nonnull String path) { - Map cMap = PROPERTIES_MAP.get(className); - if (cMap == null) return Collections.emptyMap(); - - int idx = 0; - - do { - int i = path.indexOf('.', idx); - if (i == -1) { - return cMap; - } - - cMap = PROPERTIES_MAP.get(cMap.get(path.substring(idx, i))); - if (cMap == null) return Collections.emptyMap(); - - idx = i + 1; - } while (true); - } + private static final Map> PROPERTIES_MAP; + + public static final String MAVEN_PROJECT_CLASS = "org.apache.maven.project.MavenProject"; + public static final String MAVEN_MODEL_CLASS = "org.apache.maven.model.Model"; + + static { + Map> res = new HashMap<>(); + + res.put(MAVEN_PROJECT_CLASS, ImmutableMap.builder() + .put("parentFile", "java.io.File") + .put("artifact", "org.apache.maven.artifact.Artifact") + .put("model", MAVEN_MODEL_CLASS) + .put("parent", MAVEN_PROJECT_CLASS) + .put("file", "java.io.File") + .put("dependencies", JavaClassNames.JAVA_UTIL_LIST) + .put("compileSourceRoots", JavaClassNames.JAVA_UTIL_LIST) + .put("scriptSourceRoots", JavaClassNames.JAVA_UTIL_LIST) + .put("testCompileSourceRoots", JavaClassNames.JAVA_UTIL_LIST) + .put("compileClasspathElements", JavaClassNames.JAVA_UTIL_LIST) + .put("compileArtifacts", JavaClassNames.JAVA_UTIL_LIST) + .put("compileDependencies", JavaClassNames.JAVA_UTIL_LIST) + .put("testClasspathElements", JavaClassNames.JAVA_UTIL_LIST) + .put("testArtifacts", JavaClassNames.JAVA_UTIL_LIST) + .put("testDependencies", JavaClassNames.JAVA_UTIL_LIST) + .put("runtimeClasspathElements", JavaClassNames.JAVA_UTIL_LIST) + .put("runtimeArtifacts", JavaClassNames.JAVA_UTIL_LIST) + .put("runtimeDependencies", JavaClassNames.JAVA_UTIL_LIST) + .put("systemClasspathElements", JavaClassNames.JAVA_UTIL_LIST) + .put("systemArtifacts", JavaClassNames.JAVA_UTIL_LIST) + .put("systemDependencies", JavaClassNames.JAVA_UTIL_LIST) + .put("modelVersion", JavaClassNames.JAVA_LANG_STRING) + .put("id", JavaClassNames.JAVA_LANG_STRING) + .put("groupId", JavaClassNames.JAVA_LANG_STRING) + .put("artifactId", JavaClassNames.JAVA_LANG_STRING) + .put("version", JavaClassNames.JAVA_LANG_STRING) + .put("packaging", JavaClassNames.JAVA_LANG_STRING) + .put("name", JavaClassNames.JAVA_LANG_STRING) + .put("inceptionYear", JavaClassNames.JAVA_LANG_STRING) + .put("url", JavaClassNames.JAVA_LANG_STRING) + .put("prerequisites", "org.apache.maven.model.Prerequisites") + .put("issueManagement", "org.apache.maven.model.IssueManagement") + .put("ciManagement", "org.apache.maven.model.CiManagement") + .put("description", JavaClassNames.JAVA_LANG_STRING) + .put("organization", "org.apache.maven.model.Organization") + .put("scm", "org.apache.maven.model.Scm") + .put("mailingLists", JavaClassNames.JAVA_UTIL_LIST) + .put("developers", JavaClassNames.JAVA_UTIL_LIST) + .put("contributors", JavaClassNames.JAVA_UTIL_LIST) + .put("build", "org.apache.maven.model.Build") + + .put("resources", JavaClassNames.JAVA_UTIL_LIST) + .put("testResources", JavaClassNames.JAVA_UTIL_LIST) + .put("reporting", "org.apache.maven.model.Reporting") + .put("licenses", JavaClassNames.JAVA_UTIL_LIST) + .put("artifacts", JavaClassNames.JAVA_UTIL_LIST) + .put("artifactMap", JavaClassNames.JAVA_UTIL_LIST) + .put("pluginArtifacts", JavaClassNames.JAVA_UTIL_LIST) + .put("pluginArtifactMap", JavaClassNames.JAVA_UTIL_LIST) + .put("reportArtifacts", JavaClassNames.JAVA_UTIL_LIST) + .put("reportArtifactMap", JavaClassNames.JAVA_UTIL_LIST) + .put("extensionArtifacts", JavaClassNames.JAVA_UTIL_LIST) + .put("extensionArtifactMap", JavaClassNames.JAVA_UTIL_LIST) + .put("parentArtifact", JavaClassNames.JAVA_UTIL_LIST) + .put("repositories", JavaClassNames.JAVA_UTIL_LIST) + .put("reportPlugins", JavaClassNames.JAVA_UTIL_LIST) + .put("buildPlugins", JavaClassNames.JAVA_UTIL_LIST) + .put("modules", JavaClassNames.JAVA_UTIL_LIST) + .put("modelBuild", "org.apache.maven.model.Build") + .put("remoteArtifactRepositories", JavaClassNames.JAVA_UTIL_LIST) + .put("pluginArtifactRepositories", JavaClassNames.JAVA_UTIL_LIST) + .put("distributionManagementArtifactRepository", "org.apache.maven.artifact.repository.ArtifactRepository") + .put("pluginRepositories", JavaClassNames.JAVA_UTIL_LIST) + .put("remoteProjectRepositories", JavaClassNames.JAVA_UTIL_LIST) + .put("remotePluginRepositories", JavaClassNames.JAVA_UTIL_LIST) + .put("activeProfiles", JavaClassNames.JAVA_UTIL_LIST) + .put("injectedProfileIds", JavaClassNames.JAVA_UTIL_LIST) + .put("attachedArtifacts", JavaClassNames.JAVA_UTIL_LIST) + .put("executionProject", MAVEN_PROJECT_CLASS) + .put("collectedProjects", JavaClassNames.JAVA_UTIL_LIST) + .put("dependencyArtifacts", JavaClassNames.JAVA_UTIL_LIST) + .put("managedVersionMap", JavaClassNames.JAVA_UTIL_LIST) + .put("buildExtensions", JavaClassNames.JAVA_UTIL_LIST) + .put("properties", JavaClassNames.JAVA_UTIL_LIST) + .put("filters", JavaClassNames.JAVA_UTIL_LIST) + .put("projectReferences", JavaClassNames.JAVA_UTIL_LIST) + .put("executionRoot", "boolean") + .put("defaultGoal", JavaClassNames.JAVA_UTIL_LIST) + .put("releaseArtifactRepository", "org.apache.maven.artifact.repository.ArtifactRepository") + .put("snapshotArtifactRepository", "org.apache.maven.artifact.repository.ArtifactRepository") + .put("classRealm", "org.codehaus.plexus.classworlds.realm.ClassRealm") + .put("extensionDependencyFilter", "org.sonatype.aether.graph.DependencyFilter") + .put("projectBuildingRequest", "org.apache.maven.project.ProjectBuildingRequest") + + .build() + ); + + res.put(MAVEN_MODEL_CLASS, ImmutableMap.builder() + .put("modelVersion", JavaClassNames.JAVA_LANG_STRING) + .put("parent", MAVEN_PROJECT_CLASS) + .put("groupId", JavaClassNames.JAVA_LANG_STRING) + .put("artifactId", JavaClassNames.JAVA_LANG_STRING) + .put("version", JavaClassNames.JAVA_LANG_STRING) + .put("packaging", JavaClassNames.JAVA_LANG_STRING) + .put("name", JavaClassNames.JAVA_LANG_STRING) + .put("description", JavaClassNames.JAVA_LANG_STRING) + .put("url", JavaClassNames.JAVA_LANG_STRING) + .put("inceptionYear", JavaClassNames.JAVA_LANG_STRING) + .put("organization", "org.apache.maven.model.Organization") + .put("licenses", JavaClassNames.JAVA_UTIL_LIST) + .put("developers", JavaClassNames.JAVA_UTIL_LIST) + .put("contributors", JavaClassNames.JAVA_UTIL_LIST) + .put("mailingLists", JavaClassNames.JAVA_UTIL_LIST) + .put("prerequisites", "org.apache.maven.model.Prerequisites") + .put("scm", "org.apache.maven.model.Scm") + .put("issueManagement", "org.apache.maven.model.IssueManagement") + .put("ciManagement", "org.apache.maven.model.CiManagement") + .put("build", "org.apache.maven.model.Build") + .put("profiles", JavaClassNames.JAVA_UTIL_LIST) + .put("modelEncoding", JavaClassNames.JAVA_LANG_STRING) + .put("pomFile", "java.io.File") + .put("projectDirectory", "java.io.File") + .put("id", JavaClassNames.JAVA_LANG_STRING) + + .put("repositories", JavaClassNames.JAVA_UTIL_LIST) + .put("dependencies", JavaClassNames.JAVA_UTIL_LIST) + .put("modules", JavaClassNames.JAVA_UTIL_LIST) + .put("pluginRepositories", JavaClassNames.JAVA_UTIL_LIST) + .put("properties", JavaClassNames.JAVA_UTIL_LIST) + .put("reports", JavaClassNames.JAVA_LANG_OBJECT) + .put("reporting", "org.apache.maven.model.Reporting") + .build() + ); + + res.put(JavaClassNames.JAVA_UTIL_LIST, ImmutableMap.of("empty", "boolean")); + + res.put("org.apache.maven.model.Build", ImmutableMap.builder() + .put("extensions", JavaClassNames.JAVA_UTIL_LIST) + .put("filters", JavaClassNames.JAVA_UTIL_LIST) + .put("resources", JavaClassNames.JAVA_UTIL_LIST) + .put("testResources", JavaClassNames.JAVA_UTIL_LIST) + .build()); + + res.put("java.io.File", ImmutableMap.builder() + .put("prefixLength", "long") + .put("name", JavaClassNames.JAVA_LANG_STRING) + .put("parent", JavaClassNames.JAVA_LANG_STRING) + .put("parentFile", "java.io.File") + .put("path", JavaClassNames.JAVA_LANG_STRING) + .put("absolute", "boolean") + .put("absolutePath", JavaClassNames.JAVA_LANG_STRING) + .put("absoluteFile", "java.io.File") + .put("canonicalPath", JavaClassNames.JAVA_LANG_STRING) + .put("canonicalFile", "java.io.File") + .put("directory", "boolean") + .put("file", "boolean") + .put("hidden", "boolean") + .put("totalSpace", "long") + .put("freeSpace", "long") + .put("usableSpace", "long") + .build()); + + PROPERTIES_MAP = res; + } + + public static boolean isPathValid(@Nonnull String className, @Nonnull String path) { + Map cMap = PROPERTIES_MAP.get(className); + if (cMap == null) { + return false; + } + + int idx = 0; + + do { + int i = path.indexOf('.', idx); + if (i == -1) { + return cMap.containsKey(path.substring(idx)); + } + + cMap = PROPERTIES_MAP.get(cMap.get(path.substring(idx, i))); + if (cMap == null) { + return false; + } + + idx = i + 1; + } + while (true); + } + + public static Map getCompletionVariants(@Nonnull String className, @Nonnull String path) { + Map cMap = PROPERTIES_MAP.get(className); + if (cMap == null) { + return Collections.emptyMap(); + } + + int idx = 0; + + do { + int i = path.indexOf('.', idx); + if (i == -1) { + return cMap; + } + + cMap = PROPERTIES_MAP.get(cMap.get(path.substring(idx, i))); + if (cMap == null) { + return Collections.emptyMap(); + } + + idx = i + 1; + } + while (true); + } } diff --git a/plugin/src/main/java/org/jetbrains/idea/maven/dom/references/MavenModulePsiReference.java b/plugin/src/main/java/org/jetbrains/idea/maven/dom/references/MavenModulePsiReference.java index 36c53de0..dfadbd3c 100644 --- a/plugin/src/main/java/org/jetbrains/idea/maven/dom/references/MavenModulePsiReference.java +++ b/plugin/src/main/java/org/jetbrains/idea/maven/dom/references/MavenModulePsiReference.java @@ -15,6 +15,7 @@ */ package org.jetbrains.idea.maven.dom.references; +import consulo.annotation.access.RequiredReadAction; import consulo.document.util.TextRange; import consulo.ide.impl.idea.util.PathUtil; import consulo.language.editor.completion.lookup.LookupElementBuilder; @@ -32,9 +33,9 @@ import consulo.virtualFileSystem.VirtualFile; import consulo.virtualFileSystem.util.VirtualFileUtil; import consulo.xml.util.xml.DomFileElement; -import org.jetbrains.idea.maven.dom.MavenDomBundle; import org.jetbrains.idea.maven.dom.MavenDomUtil; import org.jetbrains.idea.maven.dom.model.MavenDomProjectModel; +import org.jetbrains.idea.maven.localize.MavenDomLocalize; import org.jetbrains.idea.maven.utils.MavenUtil; import javax.annotation.Nonnull; @@ -43,108 +44,129 @@ import java.util.List; public class MavenModulePsiReference extends MavenPsiReference implements LocalQuickFixProvider { - public MavenModulePsiReference(PsiElement element, String text, TextRange range) { - super(element, text, range); - } - - public PsiElement resolve() { - VirtualFile baseDir = myPsiFile.getVirtualFile().getParent(); - if(baseDir == null) return null; - String relPath = FileUtil.toSystemIndependentName(myText + "/" + MavenConstants.POM_XML); - VirtualFile file = baseDir.findFileByRelativePath(relPath); - - if (file == null) return null; + public MavenModulePsiReference(PsiElement element, String text, TextRange range) { + super(element, text, range); + } - return getPsiFile(file); - } + @Override + @RequiredReadAction + public PsiElement resolve() { + VirtualFile baseDir = myPsiFile.getVirtualFile().getParent(); + if (baseDir == null) { + return null; + } + String relPath = FileUtil.toSystemIndependentName(myText + "/" + MavenConstants.POM_XML); + VirtualFile file = baseDir.findFileByRelativePath(relPath); + + if (file == null) { + return null; + } + + return getPsiFile(file); + } - @Nonnull - public Object[] getVariants() { - List> files = MavenDomUtil.collectProjectModels(getProject()); + @Nonnull + @Override + @RequiredReadAction + public Object[] getVariants() { + List> files = MavenDomUtil.collectProjectModels(getProject()); - List result = new ArrayList(); + List result = new ArrayList<>(); - for (DomFileElement eachDomFile : files) { - VirtualFile eachVFile = eachDomFile.getOriginalFile().getVirtualFile(); - if (Comparing.equal(eachVFile, myVirtualFile)) continue; + for (DomFileElement eachDomFile : files) { + VirtualFile eachVFile = eachDomFile.getOriginalFile().getVirtualFile(); + if (Comparing.equal(eachVFile, myVirtualFile)) { + continue; + } - PsiFile psiFile = eachDomFile.getFile(); - String modulePath = calcRelativeModulePath(myVirtualFile, eachVFile); + PsiFile psiFile = eachDomFile.getFile(); + String modulePath = calcRelativeModulePath(myVirtualFile, eachVFile); - result.add(LookupElementBuilder.create(psiFile, modulePath).withPresentableText(modulePath)); - } + result.add(LookupElementBuilder.create(psiFile, modulePath).withPresentableText(modulePath)); + } - return result.toArray(); - } - - public static String calcRelativeModulePath(VirtualFile parentPom, VirtualFile modulePom) { - String result = MavenDomUtil.calcRelativePath(parentPom.getParent(), modulePom); - int to = result.length() - ("/" + MavenConstants.POM_XML).length(); - if (to < 0) { - // todo IDEADEV-35440 - throw new RuntimeException("Filed to calculate relative path for:" + - "\nparentPom: " + parentPom + "(valid: " + parentPom.isValid() + ")" + - "\nmodulePom: " + modulePom + "(valid: " + modulePom.isValid() + ")" + - "\nequals:" + parentPom.equals(modulePom)); + return result.toArray(); } - return result.substring(0, to); - } - private PsiFile getPsiFile(VirtualFile file) { - return PsiManager.getInstance(getProject()).findFile(file); - } - - private Project getProject() { - return myPsiFile.getProject(); - } - - public LocalQuickFix[] getQuickFixes() { - if (myText.length() == 0 || resolve() != null) return LocalQuickFix.EMPTY_ARRAY; - return new LocalQuickFix[]{new CreateModuleFix(true), new CreateModuleFix(false)}; - } - - private class CreateModuleFix implements LocalQuickFix { - private final boolean myWithParent; - - private CreateModuleFix(boolean withParent) { - myWithParent = withParent; + public static String calcRelativeModulePath(VirtualFile parentPom, VirtualFile modulePom) { + String result = MavenDomUtil.calcRelativePath(parentPom.getParent(), modulePom); + int to = result.length() - ("/" + MavenConstants.POM_XML).length(); + if (to < 0) { + // todo IDEADEV-35440 + throw new RuntimeException("Filed to calculate relative path for:" + + "\nparentPom: " + parentPom + "(valid: " + parentPom.isValid() + ")" + + "\nmodulePom: " + modulePom + "(valid: " + modulePom.isValid() + ")" + + "\nequals:" + parentPom.equals(modulePom)); + } + return result.substring(0, to); } - @Nonnull - public String getName() { - return myWithParent ? MavenDomBundle.message("fix.create.module.with.parent") : MavenDomBundle.message("fix.create.module"); + @RequiredReadAction + private PsiFile getPsiFile(VirtualFile file) { + return PsiManager.getInstance(getProject()).findFile(file); } - @Nonnull - public String getFamilyName() { - return MavenDomBundle.message("inspection.group"); + private Project getProject() { + return myPsiFile.getProject(); } - public void applyFix(@Nonnull Project project, @Nonnull ProblemDescriptor d) { - try { - VirtualFile modulePom = createModulePom(); - MavenId id = MavenDomUtil.describe(myPsiFile); - - String groupId = id.getGroupId() == null ? "groupId" : id.getGroupId(); - String artifactId = modulePom.getParent().getName(); - String version = id.getVersion() == null ? "version" : id.getVersion(); - MavenUtil.runOrApplyMavenProjectFileTemplate(project, - modulePom, - new MavenId(groupId, artifactId, version), - myWithParent ? id : null, - myPsiFile.getVirtualFile(), - true); - } - catch (IOException e) { - MavenUtil.showError(project, "Cannot create a module", e); - } + @Override + public LocalQuickFix[] getQuickFixes() { + if (myText.length() == 0 || resolve() != null) { + return LocalQuickFix.EMPTY_ARRAY; + } + return new LocalQuickFix[]{new CreateModuleFix(true), new CreateModuleFix(false)}; } - private VirtualFile createModulePom() throws IOException { - VirtualFile baseDir = myVirtualFile.getParent(); - String modulePath = PathUtil.getCanonicalPath(baseDir.getPath() + "/" + myText); - VirtualFile moduleDir = VirtualFileUtil.createDirectories(modulePath); - return moduleDir.createChildData(this, MavenConstants.POM_XML); + private class CreateModuleFix implements LocalQuickFix { + private final boolean myWithParent; + + private CreateModuleFix(boolean withParent) { + myWithParent = withParent; + } + + @Nonnull + @Override + public String getName() { + return myWithParent + ? MavenDomLocalize.fixCreateModuleWithParent().get() + : MavenDomLocalize.fixCreateModule().get(); + } + + @Nonnull + @Override + public String getFamilyName() { + return MavenDomLocalize.inspectionGroup().get(); + } + + @Override + public void applyFix(@Nonnull Project project, @Nonnull ProblemDescriptor d) { + try { + VirtualFile modulePom = createModulePom(); + MavenId id = MavenDomUtil.describe(myPsiFile); + + String groupId = id.getGroupId() == null ? "groupId" : id.getGroupId(); + String artifactId = modulePom.getParent().getName(); + String version = id.getVersion() == null ? "version" : id.getVersion(); + MavenUtil.runOrApplyMavenProjectFileTemplate( + project, + modulePom, + new MavenId(groupId, artifactId, version), + myWithParent ? id : null, + myPsiFile.getVirtualFile(), + true + ); + } + catch (IOException e) { + MavenUtil.showError(project, "Cannot create a module", e); + } + } + + private VirtualFile createModulePom() throws IOException { + VirtualFile baseDir = myVirtualFile.getParent(); + String modulePath = PathUtil.getCanonicalPath(baseDir.getPath() + "/" + myText); + VirtualFile moduleDir = VirtualFileUtil.createDirectories(modulePath); + return moduleDir.createChildData(this, MavenConstants.POM_XML); + } } - } } diff --git a/plugin/src/main/java/org/jetbrains/idea/maven/dom/references/MavenPathReferenceConverter.java b/plugin/src/main/java/org/jetbrains/idea/maven/dom/references/MavenPathReferenceConverter.java index 3c69cbef..7698b201 100644 --- a/plugin/src/main/java/org/jetbrains/idea/maven/dom/references/MavenPathReferenceConverter.java +++ b/plugin/src/main/java/org/jetbrains/idea/maven/dom/references/MavenPathReferenceConverter.java @@ -1,6 +1,7 @@ // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.idea.maven.dom.references; +import consulo.annotation.access.RequiredReadAction; import consulo.document.util.TextRange; import consulo.ide.impl.idea.openapi.vfs.VfsUtil; import consulo.language.psi.*; @@ -28,199 +29,175 @@ /** * @author Sergey Evdokimov */ -public class MavenPathReferenceConverter extends PathReferenceConverter -{ - private final Condition myCondition; - - public MavenPathReferenceConverter() - { - this(Conditions.alwaysTrue()); - } - - public MavenPathReferenceConverter(@Nonnull Condition condition) - { - myCondition = condition; - } - - public static PsiReference[] createReferences(final DomElement genericDomValue, - PsiElement element, - @Nonnull final Condition fileFilter) - { - return createReferences(genericDomValue, element, fileFilter, false); - } - - public static PsiReference[] createReferences(final DomElement genericDomValue, - PsiElement element, - @Nonnull final Condition fileFilter, boolean isAbsolutePath) - { - TextRange range = ElementManipulators.getValueTextRange(element); - String text = range.substring(element.getText()); - - FileReferenceSet set = new FileReferenceSet(text, element, range.getStartOffset(), null, Platform.current().fs().isCaseSensitive(), false) - { - - private MavenDomProjectModel model; - - @Override - public Condition getReferenceCompletionFilter() - { - return fileFilter; - } - - @Override - protected boolean isSoft() - { - return true; - } - - @Override - public FileReference createFileReference(TextRange range, int index, String text) - { - return new FileReference(this, range, index, text) - { - @Override - protected void innerResolveInContext(@Nonnull String text, - @Nonnull PsiFileSystemItem context, - Collection result, - boolean caseSensitive) - { - if(model == null) - { - DomElement rootElement = DomUtil.getFileElement(genericDomValue).getRootElement(); - if(rootElement instanceof MavenDomProjectModel) - { - model = (MavenDomProjectModel) rootElement; - } - } - - String resolvedText = model == null ? text : MavenPropertyResolver.resolve(text, model); - - if(resolvedText.equals(text)) - { - if(getIndex() == 0 && resolvedText.length() == 2 && resolvedText.charAt(1) == ':') - { - // it's root on windows, e.g. "C:" - VirtualFile file = LocalFileSystem.getInstance().findFileByPath(resolvedText + '/'); - if(file != null) - { - PsiDirectory psiDirectory = context.getManager().findDirectory(file); - if(psiDirectory != null) - { - result.add(new PsiElementResolveResult(psiDirectory)); - } - } - } - else if(getIndex() == getAllReferences().length - 1 && - Objects.equals("relativePath", genericDomValue.getXmlElementName()) && - context.getVirtualFile() != null) - { - // it is a last context and should be resolved to pom.xml - - VirtualFile parentFile = context.getVirtualFile().findChild(text); - if(parentFile != null) - { - VirtualFile parentPom = parentFile.isDirectory() ? parentFile.findChild("pom.xml") : parentFile; - if(parentPom != null) - { - PsiFile psiFile = context.getManager().findFile(parentPom); - if(psiFile != null) - { - result.add(new PsiElementResolveResult(psiFile)); - } - } - } - } - else if("..".equals(resolvedText)) - { - PsiFileSystemItem resolved = context.getParent(); - if(resolved != null) - { - if(context instanceof XmlFileImpl) - { - resolved = resolved.getParent(); // calculated regarding parent directory, not the pom itself - } - if(resolved != null) - { - result.add(new PsiElementResolveResult(resolved)); - } - } - } - else - { - super.innerResolveInContext(resolvedText, context, result, caseSensitive); - } - } - else - { - VirtualFile contextFile = context.getVirtualFile(); - if(contextFile == null) - { - return; - } - - VirtualFile file = null; - - if(getIndex() == 0) - { - file = LocalFileSystem.getInstance().findFileByPath(resolvedText); - } - - if(file == null) - { - file = LocalFileSystem.getInstance().findFileByPath(contextFile.getPath() + '/' + resolvedText); - } - - if(file != null) - { - PsiFileSystemItem res = file.isDirectory() ? context.getManager().findDirectory(file) : context.getManager().findFile(file); - - if(res != null) - { - result.add(new PsiElementResolveResult(res)); - } - } - } - } - }; - } - }; - - if(isAbsolutePath) - { - set.addCustomization(FileReferenceSet.DEFAULT_PATH_EVALUATOR_OPTION, file -> { - VirtualFile virtualFile = file.getVirtualFile(); - - if(virtualFile == null) - { - return FileReferenceSet.ABSOLUTE_TOP_LEVEL.apply(file); - } - - virtualFile = VfsUtil.getRootFile(virtualFile); - PsiDirectory root = file.getManager().findDirectory(virtualFile); - - if(root == null) - { - return FileReferenceSet.ABSOLUTE_TOP_LEVEL.apply(file); - } - - return Collections.singletonList(root); - }); - } - - return set.getAllReferences(); - } - - @Nonnull - @Override - public PsiReference[] createReferences(final GenericDomValue genericDomValue, PsiElement element, ConvertContext context) - { - return createReferences(genericDomValue, element, myCondition); - } - - @Nonnull - @Override - public PsiReference [] createReferences(@Nonnull PsiElement psiElement, boolean soft) - { - throw new UnsupportedOperationException(); - } +public class MavenPathReferenceConverter extends PathReferenceConverter { + private final Condition myCondition; + + public MavenPathReferenceConverter() { + this(Conditions.alwaysTrue()); + } + + public MavenPathReferenceConverter(@Nonnull Condition condition) { + myCondition = condition; + } + + @RequiredReadAction + public static PsiReference[] createReferences( + final DomElement genericDomValue, + PsiElement element, + @Nonnull final Condition fileFilter + ) { + return createReferences(genericDomValue, element, fileFilter, false); + } + + @RequiredReadAction + public static PsiReference[] createReferences( + final DomElement genericDomValue, + PsiElement element, + @Nonnull final Condition fileFilter, + boolean isAbsolutePath + ) { + TextRange range = ElementManipulators.getValueTextRange(element); + String text = range.substring(element.getText()); + + FileReferenceSet set = + new FileReferenceSet(text, element, range.getStartOffset(), null, Platform.current().fs().isCaseSensitive(), false) { + + private MavenDomProjectModel model; + + @Override + public Condition getReferenceCompletionFilter() { + return fileFilter; + } + + @Override + protected boolean isSoft() { + return true; + } + + @Override + public FileReference createFileReference(TextRange range, int index, String text) { + return new FileReference(this, range, index, text) { + @RequiredReadAction + @Override + protected void innerResolveInContext( + @Nonnull String text, + @Nonnull PsiFileSystemItem context, + Collection result, + boolean caseSensitive + ) { + if (model == null) { + DomElement rootElement = DomUtil.getFileElement(genericDomValue).getRootElement(); + if (rootElement instanceof MavenDomProjectModel domProjectModel) { + model = domProjectModel; + } + } + + String resolvedText = model == null ? text : MavenPropertyResolver.resolve(text, model); + + if (resolvedText.equals(text)) { + if (getIndex() == 0 && resolvedText.length() == 2 && resolvedText.charAt(1) == ':') { + // it's root on windows, e.g. "C:" + VirtualFile file = LocalFileSystem.getInstance().findFileByPath(resolvedText + '/'); + if (file != null) { + PsiDirectory psiDirectory = context.getManager().findDirectory(file); + if (psiDirectory != null) { + result.add(new PsiElementResolveResult(psiDirectory)); + } + } + } + else if (getIndex() == getAllReferences().length - 1 && + Objects.equals("relativePath", genericDomValue.getXmlElementName()) && + context.getVirtualFile() != null) { + // it is a last context and should be resolved to pom.xml + + VirtualFile parentFile = context.getVirtualFile().findChild(text); + if (parentFile != null) { + VirtualFile parentPom = parentFile.isDirectory() ? parentFile.findChild("pom.xml") : parentFile; + if (parentPom != null) { + PsiFile psiFile = context.getManager().findFile(parentPom); + if (psiFile != null) { + result.add(new PsiElementResolveResult(psiFile)); + } + } + } + } + else if ("..".equals(resolvedText)) { + PsiFileSystemItem resolved = context.getParent(); + if (resolved != null) { + if (context instanceof XmlFileImpl) { + resolved = resolved.getParent(); // calculated regarding parent directory, not the pom itself + } + if (resolved != null) { + result.add(new PsiElementResolveResult(resolved)); + } + } + } + else { + super.innerResolveInContext(resolvedText, context, result, caseSensitive); + } + } + else { + VirtualFile contextFile = context.getVirtualFile(); + if (contextFile == null) { + return; + } + + VirtualFile file = null; + + if (getIndex() == 0) { + file = LocalFileSystem.getInstance().findFileByPath(resolvedText); + } + + if (file == null) { + file = LocalFileSystem.getInstance().findFileByPath(contextFile.getPath() + '/' + resolvedText); + } + + if (file != null) { + PsiFileSystemItem res = + file.isDirectory() ? context.getManager().findDirectory(file) : context.getManager().findFile(file); + + if (res != null) { + result.add(new PsiElementResolveResult(res)); + } + } + } + } + }; + } + }; + + if (isAbsolutePath) { + set.addCustomization(FileReferenceSet.DEFAULT_PATH_EVALUATOR_OPTION, file -> { + VirtualFile virtualFile = file.getVirtualFile(); + + if (virtualFile == null) { + return FileReferenceSet.ABSOLUTE_TOP_LEVEL.apply(file); + } + + virtualFile = VfsUtil.getRootFile(virtualFile); + PsiDirectory root = file.getManager().findDirectory(virtualFile); + + if (root == null) { + return FileReferenceSet.ABSOLUTE_TOP_LEVEL.apply(file); + } + + return Collections.singletonList(root); + }); + } + + return set.getAllReferences(); + } + + @Nonnull + @Override + @RequiredReadAction + public PsiReference[] createReferences(final GenericDomValue genericDomValue, PsiElement element, ConvertContext context) { + return createReferences(genericDomValue, element, myCondition); + } + + @Nonnull + @Override + public PsiReference[] createReferences(@Nonnull PsiElement psiElement, boolean soft) { + throw new UnsupportedOperationException(); + } } \ No newline at end of file diff --git a/plugin/src/main/java/org/jetbrains/idea/maven/dom/references/MavenPropertyCompletionContributor.java b/plugin/src/main/java/org/jetbrains/idea/maven/dom/references/MavenPropertyCompletionContributor.java index 523a3023..e7a423b4 100644 --- a/plugin/src/main/java/org/jetbrains/idea/maven/dom/references/MavenPropertyCompletionContributor.java +++ b/plugin/src/main/java/org/jetbrains/idea/maven/dom/references/MavenPropertyCompletionContributor.java @@ -15,6 +15,7 @@ */ package org.jetbrains.idea.maven.dom.references; +import consulo.annotation.access.RequiredReadAction; import consulo.annotation.component.ExtensionImpl; import consulo.document.util.TextRange; import consulo.language.Language; @@ -35,93 +36,77 @@ import java.util.Collection; @ExtensionImpl(id = "Maven", order = "after propertiesCompletion, before javaClassReference") -public class MavenPropertyCompletionContributor extends CompletionContributor -{ - @Override - public void fillCompletionVariants(CompletionParameters parameters, CompletionResultSet result) - { - PsiFile psiFile = parameters.getOriginalFile(); - Project project = psiFile.getProject(); +public class MavenPropertyCompletionContributor extends CompletionContributor { + @Override + @RequiredReadAction + public void fillCompletionVariants(CompletionParameters parameters, CompletionResultSet result) { + PsiFile psiFile = parameters.getOriginalFile(); + Project project = psiFile.getProject(); - MavenProjectsManager manager = MavenProjectsManager.getInstance(project); - if(!manager.isMavenizedProject()) - { - return; - } + MavenProjectsManager manager = MavenProjectsManager.getInstance(project); + if (!manager.isMavenizedProject()) { + return; + } - MavenProject projectFile = MavenDomUtil.findContainingProject(psiFile); - if(projectFile == null) - { - return; - } + MavenProject projectFile = MavenDomUtil.findContainingProject(psiFile); + if (projectFile == null) { + return; + } - if(!MavenDomUtil.isMavenFile(psiFile) && !MavenDomUtil.isFilteredResourceFile(psiFile)) - { - return; - } + if (!MavenDomUtil.isMavenFile(psiFile) && !MavenDomUtil.isFilteredResourceFile(psiFile)) { + return; + } - String text = psiFile.getText(); - int offset = parameters.getOffset(); - int braceOffset = findOpenBrace(text, offset); - if(braceOffset == -1) - { - return; - } + String text = psiFile.getText(); + int offset = parameters.getOffset(); + int braceOffset = findOpenBrace(text, offset); + if (braceOffset == -1) { + return; + } - TextRange range = TextRange.create(braceOffset, offset); - String prefix = range.substring(text); + TextRange range = TextRange.create(braceOffset, offset); + String prefix = range.substring(text); - MavenFilteredPropertyPsiReference ref = new MavenFilteredPropertyPsiReference(projectFile, psiFile, prefix, range); + MavenFilteredPropertyPsiReference ref = new MavenFilteredPropertyPsiReference(projectFile, psiFile, prefix, range); - addVariants(Arrays.asList(ref.getVariants()), result.withPrefixMatcher(prefix)); - } + addVariants(Arrays.asList(ref.getVariants()), result.withPrefixMatcher(prefix)); + } - public static void addVariants(Collection variants, CompletionResultSet result) - { - for(Object each : variants) - { - LookupElement e; - if(each instanceof LookupElement) - { - e = (LookupElement) each; - } - else if(each instanceof String) - { - e = LookupElementBuilder.create((String) each); - } - else if(each instanceof PsiNamedElement) - { - e = LookupElementBuilder.create((PsiNamedElement) each); - } - else - { - e = LookupElementBuilder.create(each, String.valueOf(each)); - } - result.addElement(e); - } - } + public static void addVariants(Collection variants, CompletionResultSet result) { + for (Object each : variants) { + LookupElement e; + if (each instanceof LookupElement) { + e = (LookupElement)each; + } + else if (each instanceof String) { + e = LookupElementBuilder.create((String)each); + } + else if (each instanceof PsiNamedElement) { + e = LookupElementBuilder.create((PsiNamedElement)each); + } + else { + e = LookupElementBuilder.create(each, String.valueOf(each)); + } + result.addElement(e); + } + } - private static int findOpenBrace(CharSequence text, int offset) - { - for(int i = offset - 1; i > 0; i--) - { - char c = text.charAt(i); - if(c == '{' && text.charAt(i - 1) == '$') - { - return i + 1; - } - if(!Character.isLetterOrDigit(c) && c != '.') - { - return -1; - } - } - return -1; - } + private static int findOpenBrace(CharSequence text, int offset) { + for (int i = offset - 1; i > 0; i--) { + char c = text.charAt(i); + if (c == '{' && text.charAt(i - 1) == '$') { + return i + 1; + } + if (!Character.isLetterOrDigit(c) && c != '.') { + return -1; + } + } + return -1; + } - @Nonnull - @Override - public Language getLanguage() - { - return Language.ANY; - } + @Nonnull + @Override + public Language getLanguage() { + return Language.ANY; + } } diff --git a/plugin/src/main/java/org/jetbrains/idea/maven/dom/references/MavenPropertyPsiReference.java b/plugin/src/main/java/org/jetbrains/idea/maven/dom/references/MavenPropertyPsiReference.java index c2bc09ab..56594560 100644 --- a/plugin/src/main/java/org/jetbrains/idea/maven/dom/references/MavenPropertyPsiReference.java +++ b/plugin/src/main/java/org/jetbrains/idea/maven/dom/references/MavenPropertyPsiReference.java @@ -20,6 +20,8 @@ import com.intellij.lang.properties.psi.PropertiesFile; import com.intellij.xml.XmlElementDescriptor; import com.intellij.xml.XmlNSDescriptor; +import consulo.annotation.access.RequiredReadAction; +import consulo.annotation.access.RequiredWriteAction; import consulo.application.AllIcons; import consulo.content.bundle.Sdk; import consulo.document.util.TextRange; @@ -30,6 +32,7 @@ import consulo.language.psi.util.PsiTreeUtil; import consulo.language.util.IncorrectOperationException; import consulo.language.util.ModuleUtilCore; +import consulo.maven.icon.MavenIconGroup; import consulo.maven.rt.server.common.model.MavenId; import consulo.module.Module; import consulo.navigation.Navigatable; @@ -42,7 +45,6 @@ import consulo.xml.psi.xml.XmlTagChild; import consulo.xml.util.xml.DomElement; import consulo.xml.util.xml.DomUtil; -import org.jetbrains.idea.maven.MavenIcons; import org.jetbrains.idea.maven.dom.MavenDomProjectProcessorUtils; import org.jetbrains.idea.maven.dom.MavenDomUtil; import org.jetbrains.idea.maven.dom.MavenSchemaProvider; @@ -63,455 +65,547 @@ import java.util.Set; public class MavenPropertyPsiReference extends MavenPsiReference { - public static final String TIMESTAMP_PROP = "maven.build.timestamp"; - - @Nullable - protected final MavenDomProjectModel myProjectDom; - protected final MavenProject myMavenProject; - private final boolean mySoft; - - public MavenPropertyPsiReference(MavenProject mavenProject, PsiElement element, String text, TextRange range, boolean isSoft) { - super(element, text, range); - myMavenProject = mavenProject; - mySoft = isSoft; - myProjectDom = MavenDomUtil.getMavenDomProjectModel(myProject, mavenProject.getFile()); - } - - @Nullable - public PsiElement resolve() { - PsiElement result = doResolve(); - if (result == null) { - if (MavenDomUtil.isMavenFile(getElement())) { - result = tryResolveToActivationSection(); - if (result == null) return null; - } - } + public static final String TIMESTAMP_PROP = "maven.build.timestamp"; + + @Nullable + protected final MavenDomProjectModel myProjectDom; + protected final MavenProject myMavenProject; + private final boolean mySoft; - if (result instanceof XmlTag) { - XmlTagChild[] children = ((XmlTag)result).getValue().getChildren(); - if (children.length != 1 || !(children[0] instanceof Navigatable)) return result; - return new MavenPsiElementWrapper(result, (Navigatable)children[0]); + public MavenPropertyPsiReference(MavenProject mavenProject, PsiElement element, String text, TextRange range, boolean isSoft) { + super(element, text, range); + myMavenProject = mavenProject; + mySoft = isSoft; + myProjectDom = MavenDomUtil.getMavenDomProjectModel(myProject, mavenProject.getFile()); } - return result; - } - - private PsiElement tryResolveToActivationSection() { - XmlTag xmlTag = PsiTreeUtil.getParentOfType(getElement(), XmlTag.class); - while (xmlTag != null) { - if (xmlTag.getName().equals("profile")) { - XmlTag activation = xmlTag.findFirstSubTag("activation"); - if (activation != null) { - for (XmlTag propertyTag : activation.findSubTags("property")) { - XmlTag nameTag = propertyTag.findFirstSubTag("name"); - if (nameTag != null) { - if (nameTag.getValue().getTrimmedText().equals(myText)) { - return nameTag; - } + @Nullable + @Override + @RequiredReadAction + public PsiElement resolve() { + PsiElement result = doResolve(); + if (result == null && MavenDomUtil.isMavenFile(getElement())) { + result = tryResolveToActivationSection(); + if (result == null) { + return null; } - } } - break; - } - xmlTag = xmlTag.getParentTag(); - } + if (result instanceof XmlTag tag) { + XmlTagChild[] children = tag.getValue().getChildren(); + return children.length == 1 && children[0] instanceof Navigatable navigatable + ? new MavenPsiElementWrapper(result, navigatable) + : result; + } - return null; - } + return result; + } + + private PsiElement tryResolveToActivationSection() { + XmlTag xmlTag = PsiTreeUtil.getParentOfType(getElement(), XmlTag.class); + while (xmlTag != null) { + if ("profile".equals(xmlTag.getName())) { + XmlTag activation = xmlTag.findFirstSubTag("activation"); + if (activation != null) { + for (XmlTag propertyTag : activation.findSubTags("property")) { + XmlTag nameTag = propertyTag.findFirstSubTag("name"); + if (nameTag != null && nameTag.getValue().getTrimmedText().equals(myText)) { + return nameTag; + } + } + } + break; + } - // See org.apache.maven.project.interpolation.AbstractStringBasedModelInterpolator.createValueSources() - @Nullable - protected PsiElement doResolve() { - boolean hasPrefix = false; - String unprefixed = myText; + xmlTag = xmlTag.getParentTag(); + } - if (myText.startsWith("pom.")) { - unprefixed = myText.substring("pom.".length()); - hasPrefix = true; - } - else if (myText.startsWith("project.")) { - unprefixed = myText.substring("project.".length()); - hasPrefix = true; + return null; } - MavenProject mavenProject = myMavenProject; + // See org.apache.maven.project.interpolation.AbstractStringBasedModelInterpolator.createValueSources() + @Nullable + @RequiredReadAction + protected PsiElement doResolve() { + boolean hasPrefix = false; + String unprefixed = myText; + + if (myText.startsWith("pom.")) { + unprefixed = myText.substring("pom.".length()); + hasPrefix = true; + } + else if (myText.startsWith("project.")) { + unprefixed = myText.substring("project.".length()); + hasPrefix = true; + } - while (unprefixed.startsWith("parent.")) { - if (unprefixed.equals("parent.groupId") || unprefixed.equals("parent.artifactId") || unprefixed.equals("parent.version") - || unprefixed.equals("parent.relativePath")) { - break; - } + MavenProject mavenProject = myMavenProject; - MavenId parentId = mavenProject.getParentId(); - if (parentId == null) return null; + while (unprefixed.startsWith("parent.")) { + if (unprefixed.equals("parent.groupId") + || unprefixed.equals("parent.artifactId") + || unprefixed.equals("parent.version") + || unprefixed.equals("parent.relativePath")) { + break; + } - mavenProject = myProjectsManager.findProject(parentId); - if (mavenProject == null) return null; + MavenId parentId = mavenProject.getParentId(); + if (parentId == null) { + return null; + } - unprefixed = unprefixed.substring("parent.".length()); - } + mavenProject = myProjectsManager.findProject(parentId); + if (mavenProject == null) { + return null; + } - if (unprefixed.equals("basedir") || (hasPrefix && mavenProject == myMavenProject && unprefixed.equals("baseUri"))) { - return getBaseDir(mavenProject); - } + unprefixed = unprefixed.substring("parent.".length()); + } - if (myText.equals(TIMESTAMP_PROP)) { - return myElement; - } + if (unprefixed.equals("basedir") || (hasPrefix && mavenProject == myMavenProject && unprefixed.equals("baseUri"))) { + return getBaseDir(mavenProject); + } - if (hasPrefix) { - MavenDomProjectModel domProjectModel = MavenDomUtil.getMavenDomProjectModel(myProject, mavenProject.getFile()); - if (domProjectModel != null) { - PsiElement res = resolveModelProperty(domProjectModel, unprefixed, new HashSet()); - if (res != null) { - return res; + if (myText.equals(TIMESTAMP_PROP)) { + return myElement; } - } - } - // todo resolve properties from config. - MavenRunnerSettings runnerSettings = MavenRunner.getInstance(myProject).getSettings(); - if (runnerSettings.getMavenProperties().containsKey(myText) || runnerSettings.getVmOptions().contains("-D" + myText + '=')) { - return myElement; - } - if (MavenUtil.getPropertiesFromMavenOpts().containsKey(myText)) { - return myElement; - } + if (hasPrefix) { + MavenDomProjectModel domProjectModel = MavenDomUtil.getMavenDomProjectModel(myProject, mavenProject.getFile()); + if (domProjectModel != null) { + PsiElement res = resolveModelProperty(domProjectModel, unprefixed, new HashSet<>()); + if (res != null) { + return res; + } + } + } - MavenDomProfile profile = DomUtil.findDomElement(myElement, MavenDomProfile.class); - if (profile != null) { - PsiElement result = MavenDomProjectProcessorUtils.findProperty(profile.getProperties(), myText); - if (result != null) return result; - } + // todo resolve properties from config. + MavenRunnerSettings runnerSettings = MavenRunner.getInstance(myProject).getSettings(); + if (runnerSettings.getMavenProperties().containsKey(myText) || runnerSettings.getVmOptions().contains("-D" + myText + '=')) { + return myElement; + } + if (MavenUtil.getPropertiesFromMavenOpts().containsKey(myText)) { + return myElement; + } - if (myProjectDom != null) { - PsiElement result = MavenDomProjectProcessorUtils.searchProperty(myText, myProjectDom, myProject); - if (result != null) return result; - } + MavenDomProfile profile = DomUtil.findDomElement(myElement, MavenDomProfile.class); + if (profile != null) { + PsiElement result = MavenDomProjectProcessorUtils.findProperty(profile.getProperties(), myText); + if (result != null) { + return result; + } + } - if ("java.home".equals(myText)) { - PsiElement element = resolveToJavaHome(mavenProject); - if (element != null) { - return element; - } - } + if (myProjectDom != null) { + PsiElement result = MavenDomProjectProcessorUtils.searchProperty(myText, myProjectDom, myProject); + if (result != null) { + return result; + } + } - MavenPropertiesVirtualFileSystem mavenPropertiesVirtualFileSystem = MavenPropertiesVirtualFileSystem.getInstance(); + if ("java.home".equals(myText)) { + PsiElement element = resolveToJavaHome(mavenProject); + if (element != null) { + return element; + } + } - IProperty property = mavenPropertiesVirtualFileSystem.findSystemProperty(myProject, myText); - if (property != null) return property.getPsiElement(); + MavenPropertiesVirtualFileSystem mavenPropertiesVirtualFileSystem = MavenPropertiesVirtualFileSystem.getInstance(); - if (myText.startsWith("env.")) { - property = mavenPropertiesVirtualFileSystem.findEnvProperty(myProject, myText.substring("env.".length())); - if (property != null) return property.getPsiElement(); - } + IProperty property = mavenPropertiesVirtualFileSystem.findSystemProperty(myProject, myText); + if (property != null) { + return property.getPsiElement(); + } - String textWithEnv = "env." + myText; + if (myText.startsWith("env.")) { + property = mavenPropertiesVirtualFileSystem.findEnvProperty(myProject, myText.substring("env.".length())); + if (property != null) { + return property.getPsiElement(); + } + } - property = mavenPropertiesVirtualFileSystem.findSystemProperty(myProject, textWithEnv); - if (property != null) return property.getPsiElement(); + String textWithEnv = "env." + myText; - property = mavenPropertiesVirtualFileSystem.findEnvProperty(myProject, textWithEnv); - if (property != null) return property.getPsiElement(); + property = mavenPropertiesVirtualFileSystem.findSystemProperty(myProject, textWithEnv); + if (property != null) { + return property.getPsiElement(); + } - if (!hasPrefix) { - MavenDomProjectModel domProjectModel = MavenDomUtil.getMavenDomProjectModel(myProject, mavenProject.getFile()); - if (domProjectModel != null) { - PsiElement res = resolveModelProperty(domProjectModel, unprefixed, new HashSet()); - if (res != null) { - return res; + property = mavenPropertiesVirtualFileSystem.findEnvProperty(myProject, textWithEnv); + if (property != null) { + return property.getPsiElement(); } - } - } - if (mavenProject.getProperties().containsKey(myText)) { - return myElement; - } + if (!hasPrefix) { + MavenDomProjectModel domProjectModel = MavenDomUtil.getMavenDomProjectModel(myProject, mavenProject.getFile()); + if (domProjectModel != null) { + PsiElement res = resolveModelProperty(domProjectModel, unprefixed, new HashSet<>()); + if (res != null) { + return res; + } + } + } - if (myText.startsWith("settings.")) { - return resolveSettingsModelProperty(); - } + if (mavenProject.getProperties().containsKey(myText)) { + return myElement; + } - return null; - } + if (myText.startsWith("settings.")) { + return resolveSettingsModelProperty(); + } + + return null; + } - @Nullable - private PsiElement resolveToJavaHome(@Nonnull MavenProject mavenProject) { - Module module = myProjectsManager.findModule(mavenProject); - if (module == null) return null; + @Nullable + private PsiElement resolveToJavaHome(@Nonnull MavenProject mavenProject) { + Module module = myProjectsManager.findModule(mavenProject); + if (module == null) { + return null; + } - Sdk sdk = ModuleUtilCore.getSdk(module, JavaModuleExtensionImpl.class); - if (sdk == null) return null; + Sdk sdk = ModuleUtilCore.getSdk(module, JavaModuleExtensionImpl.class); + if (sdk == null) { + return null; + } - VirtualFile homeDirectory = sdk.getHomeDirectory(); - if (homeDirectory == null) return null; + VirtualFile homeDirectory = sdk.getHomeDirectory(); + if (homeDirectory == null) { + return null; + } - VirtualFile jreDir = homeDirectory.findChild("jre"); - if (jreDir == null) return null; + VirtualFile jreDir = homeDirectory.findChild("jre"); + if (jreDir == null) { + return null; + } - PsiFile propFile = PsiFileFactory.getInstance(myProject).createFileFromText("SystemProperties.properties", PropertiesLanguage.INSTANCE, - "java.home=" + jreDir.getPath()); + PsiFile propFile = PsiFileFactory.getInstance(myProject).createFileFromText( + "SystemProperties.properties", + PropertiesLanguage.INSTANCE, + "java.home=" + jreDir.getPath() + ); - return ((PropertiesFile)propFile).getProperties().get(0).getPsiElement(); - } + return ((PropertiesFile)propFile).getProperties().get(0).getPsiElement(); + } - private PsiDirectory getBaseDir(@Nonnull MavenProject mavenProject) { - return PsiManager.getInstance(myProject).findDirectory(mavenProject.getDirectoryFile()); - } + @RequiredReadAction + private PsiDirectory getBaseDir(@Nonnull MavenProject mavenProject) { + return PsiManager.getInstance(myProject).findDirectory(mavenProject.getDirectoryFile()); + } - @Nullable - private PsiElement resolveSettingsModelProperty() { - if (!schemaHasProperty(MavenSchemaProvider.MAVEN_SETTINGS_SCHEMA_URL, myText)) return null; + @Nullable + @RequiredReadAction + private PsiElement resolveSettingsModelProperty() { + if (!schemaHasProperty(MavenSchemaProvider.MAVEN_SETTINGS_SCHEMA_URL, myText)) { + return null; + } - for (VirtualFile each : myProjectsManager.getGeneralSettings().getEffectiveSettingsFiles()) { - MavenDomSettingsModel settingsDom = MavenDomUtil.getMavenDomModel(myProject, each, MavenDomSettingsModel.class); - if (settingsDom == null) continue; - PsiElement result = MavenDomUtil.findTag(settingsDom, myText); - if (result != null) return result; + for (VirtualFile each : myProjectsManager.getGeneralSettings().getEffectiveSettingsFiles()) { + MavenDomSettingsModel settingsDom = MavenDomUtil.getMavenDomModel(myProject, each, MavenDomSettingsModel.class); + if (settingsDom == null) { + continue; + } + PsiElement result = MavenDomUtil.findTag(settingsDom, myText); + if (result != null) { + return result; + } + } + return myElement; } - return myElement; - } - @Nullable - private PsiElement resolveModelProperty(@Nonnull MavenDomProjectModel projectDom, - @Nonnull final String path, - @Nonnull final Set recursionGuard) { - if (!recursionGuard.add(projectDom)) return null; + @Nullable + @RequiredReadAction + private PsiElement resolveModelProperty( + @Nonnull MavenDomProjectModel projectDom, + @Nonnull final String path, + @Nonnull final Set recursionGuard + ) { + if (!recursionGuard.add(projectDom)) { + return null; + } - String pathWithProjectPrefix = "project." + path; + String pathWithProjectPrefix = "project." + path; - if (!MavenModelClassesProperties.isPathValid(MavenModelClassesProperties.MAVEN_PROJECT_CLASS, path) - && !MavenModelClassesProperties.isPathValid(MavenModelClassesProperties.MAVEN_MODEL_CLASS, path)) { - if (!schemaHasProperty(MavenSchemaProvider.MAVEN_PROJECT_SCHEMA_URL, pathWithProjectPrefix)) return null; - } + if (!MavenModelClassesProperties.isPathValid(MavenModelClassesProperties.MAVEN_PROJECT_CLASS, path) + && !MavenModelClassesProperties.isPathValid(MavenModelClassesProperties.MAVEN_MODEL_CLASS, path)) { + if (!schemaHasProperty(MavenSchemaProvider.MAVEN_PROJECT_SCHEMA_URL, pathWithProjectPrefix)) { + return null; + } + } + + PsiElement result = MavenDomUtil.findTag(projectDom, pathWithProjectPrefix); + if (result != null) { + return result; + } + + if (pathWithProjectPrefix.equals("project.groupId") || pathWithProjectPrefix.equals("project.version")) { + return MavenDomUtil.findTag(projectDom, "project.parent." + path); + } - PsiElement result = MavenDomUtil.findTag(projectDom, pathWithProjectPrefix); - if (result != null) return result; + result = new MavenDomProjectProcessorUtils.DomParentProjectFileProcessor(myProjectsManager) { + @Override + @RequiredReadAction + protected PsiElement doProcessParent(VirtualFile parentFile) { + MavenDomProjectModel parentProjectDom = MavenDomUtil.getMavenDomProjectModel(myProject, parentFile); + return parentProjectDom == null ? null : resolveModelProperty(parentProjectDom, path, recursionGuard); + } + }.process(projectDom); + if (result != null) { + return result; + } - if (pathWithProjectPrefix.equals("project.groupId") || pathWithProjectPrefix.equals("project.version")) { - return MavenDomUtil.findTag(projectDom, "project.parent." + path); + return myElement; + } + + @RequiredReadAction + private boolean schemaHasProperty(String schema, final String property) { + return processSchema( + schema, + new SchemaProcessor() { + @Nullable + @Override + public Boolean process(@Nonnull String eachProperty, XmlElementDescriptor descriptor) { + if (eachProperty.equals(property)) { + return true; + } + return null; + } + } + ) != null; } - result = new MavenDomProjectProcessorUtils.DomParentProjectFileProcessor(myProjectsManager) { - protected PsiElement doProcessParent(VirtualFile parentFile) { - MavenDomProjectModel parentProjectDom = MavenDomUtil.getMavenDomProjectModel(myProject, parentFile); - if (parentProjectDom == null) return null; - return resolveModelProperty(parentProjectDom, path, recursionGuard); - } - }.process(projectDom); - if (result != null) return result; - - return myElement; - } - - private boolean schemaHasProperty(String schema, final String property) { - return processSchema(schema, new SchemaProcessor() { - @Nullable - public Boolean process(@Nonnull String eachProperty, XmlElementDescriptor descriptor) { - if (eachProperty.equals(property)) return true; - return null; - } - }) != null; - } - - @Override - public PsiElement handleElementRename(String newElementName) throws IncorrectOperationException - { - return ElementManipulators.getManipulator(myElement).handleContentChange(myElement, myRange, newElementName); - } - - @Nonnull - public Object[] getVariants() { - List result = new ArrayList(); - collectVariants(result, new HashSet()); - return ArrayUtil.toObjectArray(result); - } - - protected void collectVariants(final List result, Set variants) { - int prefixLength = 0; - if (myText.startsWith("pom.")) { - prefixLength = "pom.".length(); + @Override + @RequiredWriteAction + public PsiElement handleElementRename(String newElementName) throws IncorrectOperationException { + return ElementManipulators.getManipulator(myElement).handleContentChange(myElement, myRange, newElementName); } - else if (myText.startsWith("project.")) { - prefixLength = "project.".length(); + + @Nonnull + @Override + @RequiredReadAction + public Object[] getVariants() { + List result = new ArrayList<>(); + collectVariants(result, new HashSet<>()); + return ArrayUtil.toObjectArray(result); } - MavenProject mavenProject = myMavenProject; - while (myText.startsWith("parent.", prefixLength)) { - MavenId parentId = mavenProject.getParentId(); - if (parentId == null) return; + @RequiredReadAction + protected void collectVariants(final List result, Set variants) { + int prefixLength = 0; + if (myText.startsWith("pom.")) { + prefixLength = "pom.".length(); + } + else if (myText.startsWith("project.")) { + prefixLength = "project.".length(); + } - mavenProject = myProjectsManager.findProject(parentId); - if (mavenProject == null) return; + MavenProject mavenProject = myMavenProject; + while (myText.startsWith("parent.", prefixLength)) { + MavenId parentId = mavenProject.getParentId(); + if (parentId == null) { + return; + } - prefixLength += "parent.".length(); - } + mavenProject = myProjectsManager.findProject(parentId); + if (mavenProject == null) { + return; + } - final String prefix = prefixLength == 0 ? null : myText.substring(0, prefixLength); + prefixLength += "parent.".length(); + } - PsiDirectory baseDir = getBaseDir(mavenProject); - addVariant(result, "basedir", baseDir, prefix, MavenIcons.MavenLogo); - if (prefix == null) { - result.add(createLookupElement(baseDir, "project.baseUri", MavenIcons.MavenLogo)); - result.add(createLookupElement(baseDir, "pom.baseUri", MavenIcons.MavenLogo)); - result.add(LookupElementBuilder.create(TIMESTAMP_PROP).withIcon(MavenIcons.MavenLogo)); - } + final String prefix = prefixLength == 0 ? null : myText.substring(0, prefixLength); - processSchema(MavenSchemaProvider.MAVEN_PROJECT_SCHEMA_URL, new SchemaProcessor() { - @Override - public Object process(@Nonnull String property, XmlElementDescriptor descriptor) { - if (property.startsWith("project.")) { - addVariant(result, property.substring("project.".length()), descriptor, prefix, MavenIcons.MavenLogo); + PsiDirectory baseDir = getBaseDir(mavenProject); + addVariant(result, "basedir", baseDir, prefix, MavenIconGroup.mavenlogo()); + if (prefix == null) { + result.add(createLookupElement(baseDir, "project.baseUri", MavenIconGroup.mavenlogo())); + result.add(createLookupElement(baseDir, "pom.baseUri", MavenIconGroup.mavenlogo())); + result.add(LookupElementBuilder.create(TIMESTAMP_PROP).withIcon(MavenIconGroup.mavenlogo())); } - return null; - } - }); - processSchema(MavenSchemaProvider.MAVEN_SETTINGS_SCHEMA_URL, new SchemaProcessor(){ - @Override - public Object process(@Nonnull String property, XmlElementDescriptor descriptor) { - result.add(createLookupElement(descriptor, property, MavenIcons.MavenLogo)); - return null; - } - }); - - collectPropertiesVariants(result, variants); - collectSystemEnvProperties(MavenPropertiesVirtualFileSystem.SYSTEM_PROPERTIES_FILE, null, result, variants); - collectSystemEnvProperties(MavenPropertiesVirtualFileSystem.ENV_PROPERTIES_FILE, "env.", result, variants); - - MavenRunnerSettings runnerSettings = MavenRunner.getInstance(myProject).getSettings(); - for (String prop : runnerSettings.getMavenProperties().keySet()) { - if (variants.add(prefix)) { - result.add(LookupElementBuilder.create(prop).withIcon(AllIcons.Nodes.Property)); - } - } - for (String prop : MavenUtil.getPropertiesFromMavenOpts().keySet()) { - if (variants.add(prop)) { - result.add(LookupElementBuilder.create(prop).withIcon(AllIcons.Nodes.Property)); - } - } + processSchema( + MavenSchemaProvider.MAVEN_PROJECT_SCHEMA_URL, + (property, descriptor) -> { + if (property.startsWith("project.")) { + addVariant(result, property.substring("project.".length()), descriptor, prefix, MavenIconGroup.mavenlogo()); + } + return null; + } + ); + + processSchema( + MavenSchemaProvider.MAVEN_SETTINGS_SCHEMA_URL, + (property, descriptor) -> { + result.add(createLookupElement(descriptor, property, MavenIconGroup.mavenlogo())); + return null; + } + ); - for (Object key : myMavenProject.getProperties().keySet()) { - if (key instanceof String) { - String property = (String)key; - if (variants.add(property)) { - result.add(LookupElementBuilder.create(property).withIcon(AllIcons.Nodes.Property)); + collectPropertiesVariants(result, variants); + collectSystemEnvProperties(MavenPropertiesVirtualFileSystem.SYSTEM_PROPERTIES_FILE, null, result, variants); + collectSystemEnvProperties(MavenPropertiesVirtualFileSystem.ENV_PROPERTIES_FILE, "env.", result, variants); + + MavenRunnerSettings runnerSettings = MavenRunner.getInstance(myProject).getSettings(); + for (String prop : runnerSettings.getMavenProperties().keySet()) { + if (variants.add(prefix)) { + result.add(LookupElementBuilder.create(prop).withIcon(AllIcons.Nodes.Property)); + } + } + for (String prop : MavenUtil.getPropertiesFromMavenOpts().keySet()) { + if (variants.add(prop)) { + result.add(LookupElementBuilder.create(prop).withIcon(AllIcons.Nodes.Property)); + } + } + + for (Object key : myMavenProject.getProperties().keySet()) { + if (key instanceof String) { + String property = (String)key; + if (variants.add(property)) { + result.add(LookupElementBuilder.create(property).withIcon(AllIcons.Nodes.Property)); + } + } } - } - } - } - - private static void addVariant(List result, String name, @Nonnull Object element, @Nullable String prefix, @Nonnull Image icon) { - String nameWithPrefix; - if (prefix == null) { - nameWithPrefix = name; - result.add(createLookupElement(element, "pom." + name, icon)); - result.add(createLookupElement(element, "project." + name, icon)); - } - else { - nameWithPrefix = prefix + name; } - result.add(createLookupElement(element, nameWithPrefix, icon)); - } + private static void addVariant( + List result, + String name, + @Nonnull Object element, + @Nullable String prefix, + @Nonnull Image icon + ) { + String nameWithPrefix; + if (prefix == null) { + nameWithPrefix = name; + result.add(createLookupElement(element, "pom." + name, icon)); + result.add(createLookupElement(element, "project." + name, icon)); + } + else { + nameWithPrefix = prefix + name; + } + + result.add(createLookupElement(element, nameWithPrefix, icon)); + } - private void collectPropertiesVariants(final List result, Set variants) { - if (myProjectDom != null) { - for (XmlTag xmlTag : MavenDomProjectProcessorUtils.collectProperties(myProjectDom, myProject)) { - String propertyName = xmlTag.getName(); - if (variants.add(propertyName)) { - result.add(createLookupElement(xmlTag, propertyName, AllIcons.Nodes.Property)); + private void collectPropertiesVariants(final List result, Set variants) { + if (myProjectDom != null) { + for (XmlTag xmlTag : MavenDomProjectProcessorUtils.collectProperties(myProjectDom, myProject)) { + String propertyName = xmlTag.getName(); + if (variants.add(propertyName)) { + result.add(createLookupElement(xmlTag, propertyName, AllIcons.Nodes.Property)); + } + } } - } } - } - private void collectSystemEnvProperties(String propertiesFileName, @Nullable String prefix, List result, Set variants) { - VirtualFile virtualFile = MavenPropertiesVirtualFileSystem.getInstance().findFileByPath(propertiesFileName); - PropertiesFile file = MavenDomUtil.getPropertiesFile(myProject, virtualFile); - collectPropertiesFileVariants(file, prefix, result, variants); - } + private void collectSystemEnvProperties(String propertiesFileName, @Nullable String prefix, List result, Set variants) { + VirtualFile virtualFile = MavenPropertiesVirtualFileSystem.getInstance().findFileByPath(propertiesFileName); + PropertiesFile file = MavenDomUtil.getPropertiesFile(myProject, virtualFile); + collectPropertiesFileVariants(file, prefix, result, variants); + } - protected static void collectPropertiesFileVariants(@Nullable PropertiesFile file, @Nullable String prefix, List result, Set variants) { - if (file == null) return; + protected static void collectPropertiesFileVariants( + @Nullable PropertiesFile file, + @Nullable String prefix, + List result, + Set variants + ) { + if (file == null) { + return; + } - for (IProperty each : file.getProperties()) { - String name = each.getKey(); - if (name != null) { - if (prefix != null) name = prefix + name; + for (IProperty each : file.getProperties()) { + String name = each.getKey(); + if (name != null) { + if (prefix != null) { + name = prefix + name; + } - if (variants.add(name)) { - result.add(createLookupElement(each, name, AllIcons.Nodes.Property)); + if (variants.add(name)) { + result.add(createLookupElement(each, name, AllIcons.Nodes.Property)); + } + } } - } } - } - - private static LookupElement createLookupElement(@Nonnull Object element, @Nonnull String name, @Nullable Image icon) { - return LookupElementBuilder.create(element, name) - .withIcon(icon) - .withPresentableText(name); - } - - @Nullable - private T processSchema(String schema, SchemaProcessor processor) { - VirtualFile file = MavenSchemaProvider.getSchemaFile(schema); - PsiFile psiFile = PsiManager.getInstance(myProject).findFile(file); - if (!(psiFile instanceof XmlFile)) return null; - - XmlFile xmlFile = (XmlFile)psiFile; - XmlDocument document = xmlFile.getDocument(); - XmlNSDescriptor desc = (XmlNSDescriptor)document.getMetaData(); - XmlElementDescriptor[] descriptors = desc.getRootElementsDescriptors(document); - return doProcessSchema(descriptors, null, processor, new HashSet()); - } - - private static T doProcessSchema(XmlElementDescriptor[] descriptors, - String prefix, - SchemaProcessor processor, - Set recursionGuard) { - for (XmlElementDescriptor each : descriptors) { - if (isCollection(each)) continue; - if (!recursionGuard.add(each)) continue; - - try { - String name = each.getName(); - if (prefix != null) name = prefix + "." + name; - - T result = processor.process(name, each); - if (result != null) return result; - - result = doProcessSchema(each.getElementsDescriptors(null), name, processor, recursionGuard); - if (result != null) return result; - } - finally { - recursionGuard.remove(each); - } + + private static LookupElement createLookupElement(@Nonnull Object element, @Nonnull String name, @Nullable Image icon) { + return LookupElementBuilder.create(element, name) + .withIcon(icon) + .withPresentableText(name); + } + + @Nullable + @RequiredReadAction + private T processSchema(String schema, SchemaProcessor processor) { + VirtualFile file = MavenSchemaProvider.getSchemaFile(schema); + PsiFile psiFile = PsiManager.getInstance(myProject).findFile(file); + if (psiFile instanceof XmlFile xmlFile) { + XmlDocument document = xmlFile.getDocument(); + XmlNSDescriptor desc = (XmlNSDescriptor)document.getMetaData(); + XmlElementDescriptor[] descriptors = desc.getRootElementsDescriptors(document); + return doProcessSchema(descriptors, null, processor, new HashSet<>()); + } + return null; } - return null; - } + private static T doProcessSchema( + XmlElementDescriptor[] descriptors, + String prefix, + SchemaProcessor processor, + Set recursionGuard + ) { + for (XmlElementDescriptor each : descriptors) { + if (isCollection(each)) { + continue; + } + if (!recursionGuard.add(each)) { + continue; + } + + try { + String name = each.getName(); + if (prefix != null) { + name = prefix + "." + name; + } + + T result = processor.process(name, each); + if (result != null) { + return result; + } + + result = doProcessSchema(each.getElementsDescriptors(null), name, processor, recursionGuard); + if (result != null) { + return result; + } + } + finally { + recursionGuard.remove(each); + } + } - private static boolean isCollection(XmlElementDescriptor each) { - XmlTag declaration = (XmlTag)each.getDeclaration(); - if (declaration != null) { - XmlTag complexType = declaration.findFirstSubTag("xs:complexType"); - if (complexType != null) { - if (complexType.findFirstSubTag("xs:sequence") != null) return true; - } + return null; } - return false; - } - @Override - public boolean isSoft() { - return mySoft; - } + private static boolean isCollection(XmlElementDescriptor each) { + XmlTag declaration = (XmlTag)each.getDeclaration(); + if (declaration != null) { + XmlTag complexType = declaration.findFirstSubTag("xs:complexType"); + if (complexType != null && complexType.findFirstSubTag("xs:sequence") != null) { + return true; + } + } + return false; + } - private interface SchemaProcessor { - @Nullable - T process(@Nonnull String property, XmlElementDescriptor descriptor); - } + @Override + public boolean isSoft() { + return mySoft; + } + private interface SchemaProcessor { + @Nullable + T process(@Nonnull String property, XmlElementDescriptor descriptor); + } } diff --git a/plugin/src/main/java/org/jetbrains/idea/maven/dom/references/MavenPropertyPsiReferenceContributor.java b/plugin/src/main/java/org/jetbrains/idea/maven/dom/references/MavenPropertyPsiReferenceContributor.java index 222e2031..ca3e9848 100644 --- a/plugin/src/main/java/org/jetbrains/idea/maven/dom/references/MavenPropertyPsiReferenceContributor.java +++ b/plugin/src/main/java/org/jetbrains/idea/maven/dom/references/MavenPropertyPsiReferenceContributor.java @@ -28,22 +28,21 @@ import javax.annotation.Nonnull; @ExtensionImpl -public class MavenPropertyPsiReferenceContributor extends PsiReferenceContributor -{ - @Override - public void registerReferenceProviders(PsiReferenceRegistrar registrar) - { - ElementPattern pattern = XmlPatterns.xmlTag().withParent(DomPatterns.withDom(DomPatterns.domElement(MavenDomProperties.class))); - registrar.registerReferenceProvider(pattern, new MavenPropertyPsiReferenceProvider(), PsiReferenceRegistrar.DEFAULT_PRIORITY); - registrar.registerReferenceProvider(PlatformPatterns.psiElement(), - new MavenFilteredPropertyPsiReferenceProvider(), - PsiReferenceRegistrar.DEFAULT_PRIORITY); - } +public class MavenPropertyPsiReferenceContributor extends PsiReferenceContributor { + @Override + public void registerReferenceProviders(PsiReferenceRegistrar registrar) { + ElementPattern pattern = XmlPatterns.xmlTag().withParent(DomPatterns.withDom(DomPatterns.domElement(MavenDomProperties.class))); + registrar.registerReferenceProvider(pattern, new MavenPropertyPsiReferenceProvider(), PsiReferenceRegistrar.DEFAULT_PRIORITY); + registrar.registerReferenceProvider( + PlatformPatterns.psiElement(), + new MavenFilteredPropertyPsiReferenceProvider(), + PsiReferenceRegistrar.DEFAULT_PRIORITY + ); + } - @Nonnull - @Override - public Language getLanguage() - { - return Language.ANY; - } + @Nonnull + @Override + public Language getLanguage() { + return Language.ANY; + } } diff --git a/plugin/src/main/java/org/jetbrains/idea/maven/dom/references/MavenPropertyPsiReferenceInjector.java b/plugin/src/main/java/org/jetbrains/idea/maven/dom/references/MavenPropertyPsiReferenceInjector.java index 9f031ba2..42a12ff2 100644 --- a/plugin/src/main/java/org/jetbrains/idea/maven/dom/references/MavenPropertyPsiReferenceInjector.java +++ b/plugin/src/main/java/org/jetbrains/idea/maven/dom/references/MavenPropertyPsiReferenceInjector.java @@ -31,29 +31,24 @@ import javax.annotation.Nullable; @ExtensionImpl -public class MavenPropertyPsiReferenceInjector implements DomReferenceInjector -{ - @Override - public String resolveString(@Nullable String unresolvedText, @Nonnull ConvertContext context) - { - if(StringUtil.isEmptyOrSpaces(unresolvedText)) - { - return unresolvedText; - } - MavenDomProjectModel model = (MavenDomProjectModel) DomUtil.getFileElement(context.getInvocationElement()).getRootElement(); - return MavenPropertyResolver.resolve(unresolvedText, model); - } +public class MavenPropertyPsiReferenceInjector implements DomReferenceInjector { + @Override + public String resolveString(@Nullable String unresolvedText, @Nonnull ConvertContext context) { + if (StringUtil.isEmptyOrSpaces(unresolvedText)) { + return unresolvedText; + } + MavenDomProjectModel model = (MavenDomProjectModel)DomUtil.getFileElement(context.getInvocationElement()).getRootElement(); + return MavenPropertyResolver.resolve(unresolvedText, model); + } - @Override - @Nonnull - public PsiReference[] inject(@Nullable String unresolvedText, @Nonnull PsiElement element, @Nonnull ConvertContext context) - { - return MavenPropertyPsiReferenceProvider.getReferences(element, true); - } + @Override + @Nonnull + public PsiReference[] inject(@Nullable String unresolvedText, @Nonnull PsiElement element, @Nonnull ConvertContext context) { + return MavenPropertyPsiReferenceProvider.getReferences(element, true); + } - @Override - public boolean isAvaliable(DomFileDescription fileDescription) - { - return fileDescription instanceof MavenDomProjectModelDescription; - } + @Override + public boolean isAvaliable(DomFileDescription fileDescription) { + return fileDescription instanceof MavenDomProjectModelDescription; + } } diff --git a/plugin/src/main/java/org/jetbrains/idea/maven/dom/references/MavenPropertyPsiReferenceProvider.java b/plugin/src/main/java/org/jetbrains/idea/maven/dom/references/MavenPropertyPsiReferenceProvider.java index 73de5782..7e5bd0fe 100644 --- a/plugin/src/main/java/org/jetbrains/idea/maven/dom/references/MavenPropertyPsiReferenceProvider.java +++ b/plugin/src/main/java/org/jetbrains/idea/maven/dom/references/MavenPropertyPsiReferenceProvider.java @@ -15,6 +15,7 @@ */ package org.jetbrains.idea.maven.dom.references; +import consulo.annotation.access.RequiredReadAction; import consulo.document.util.TextRange; import consulo.language.psi.ElementManipulators; import consulo.language.psi.PsiElement; @@ -40,83 +41,95 @@ import java.util.regex.Matcher; public class MavenPropertyPsiReferenceProvider extends PsiReferenceProvider { - public static final boolean SOFT_DEFAULT = false; - - @Nonnull - @Override - public PsiReference[] getReferencesByElement(@Nonnull PsiElement element, @Nonnull ProcessingContext context) { - return getReferences(element, SOFT_DEFAULT); - } - - private static boolean isElementCanContainReference(PsiElement element) { - if (element instanceof XmlTag) { - if ("delimiter".equals(((XmlTag)element).getName())) { - XmlTag delimitersTag = ((XmlTag)element).getParentTag(); - if (delimitersTag != null && "delimiters".equals(delimitersTag.getName())) { - XmlTag configurationTag = delimitersTag.getParentTag(); - if (configurationTag != null && "configuration".equals(configurationTag.getName())) { - DomElement configurationDom = DomManager.getDomManager(configurationTag.getProject()).getDomElement(configurationTag); - if (configurationDom != null && configurationDom instanceof MavenDomConfiguration) { - if (MavenPluginDomUtil.isPlugin((MavenDomConfiguration)configurationDom, "org.apache.maven.plugins", "maven-resources-plugin")) { - return false; - } + public static final boolean SOFT_DEFAULT = false; + + @Nonnull + @Override + @RequiredReadAction + public PsiReference[] getReferencesByElement(@Nonnull PsiElement element, @Nonnull ProcessingContext context) { + return getReferences(element, SOFT_DEFAULT); + } + + private static boolean isElementCanContainReference(PsiElement element) { + if (element instanceof XmlTag tag && "delimiter".equals(tag.getName())) { + XmlTag delimitersTag = tag.getParentTag(); + if (delimitersTag != null && "delimiters".equals(delimitersTag.getName())) { + XmlTag configurationTag = delimitersTag.getParentTag(); + if (configurationTag != null && "configuration".equals(configurationTag.getName())) { + DomElement configurationDom = DomManager.getDomManager(configurationTag.getProject()).getDomElement(configurationTag); + if (configurationDom != null && configurationDom instanceof MavenDomConfiguration mavenDomConfiguration) { + if (MavenPluginDomUtil.isPlugin( + mavenDomConfiguration, + "org.apache.maven.plugins", + "maven-resources-plugin" + )) { + return false; + } + } + } } - } } - } + + return true; } - return true; - } + @Nullable + private static MavenProject findMavenProject(PsiElement element) { + VirtualFile virtualFile = MavenDomUtil.getVirtualFile(element); + if (virtualFile == null) { + return null; + } - @Nullable - private static MavenProject findMavenProject(PsiElement element) { - VirtualFile virtualFile = MavenDomUtil.getVirtualFile(element); - if (virtualFile == null) return null; + MavenProjectsManager manager = MavenProjectsManager.getInstance(element.getProject()); + return manager.findProject(virtualFile); + } - MavenProjectsManager manager = MavenProjectsManager.getInstance(element.getProject()); - return manager.findProject(virtualFile); - } + @RequiredReadAction + public static PsiReference[] getReferences(PsiElement element, boolean isSoft) { + TextRange textRange = ElementManipulators.getValueTextRange(element); + if (textRange.isEmpty()) { + return PsiReference.EMPTY_ARRAY; + } - public static PsiReference[] getReferences(PsiElement element, boolean isSoft) { - TextRange textRange = ElementManipulators.getValueTextRange(element); - if (textRange.isEmpty()) return PsiReference.EMPTY_ARRAY; + String text = element.getText(); - String text = element.getText(); + if (StringUtil.isEmptyOrSpaces(text)) { + return PsiReference.EMPTY_ARRAY; + } - if (StringUtil.isEmptyOrSpaces(text)) return PsiReference.EMPTY_ARRAY; + if (!isElementCanContainReference(element)) { + return PsiReference.EMPTY_ARRAY; + } - if (!isElementCanContainReference(element)) return PsiReference.EMPTY_ARRAY; + MavenProject mavenProject = null; + List result = null; - MavenProject mavenProject = null; - List result = null; + Matcher matcher = MavenPropertyResolver.PATTERN.matcher(textRange.substring(text)); + while (matcher.find()) { + String propertyName = matcher.group(1); + int from; + if (propertyName == null) { + propertyName = matcher.group(2); + from = matcher.start(2); + } + else { + from = matcher.start(1); + } - Matcher matcher = MavenPropertyResolver.PATTERN.matcher(textRange.substring(text)); - while (matcher.find()) { - String propertyName = matcher.group(1); - int from; - if (propertyName == null) { - propertyName = matcher.group(2); - from = matcher.start(2); - } - else { - from = matcher.start(1); - } + TextRange range = TextRange.from(textRange.getStartOffset() + from, propertyName.length()); - TextRange range = TextRange.from(textRange.getStartOffset() + from, propertyName.length()); + if (result == null) { + result = new ArrayList<>(); - if (result == null) { - result = new ArrayList(); + mavenProject = findMavenProject(element); + if (mavenProject == null) { + return PsiReference.EMPTY_ARRAY; + } + } - mavenProject = findMavenProject(element); - if (mavenProject == null) { - return PsiReference.EMPTY_ARRAY; + result.add(new MavenPropertyPsiReference(mavenProject, element, propertyName, range, isSoft)); } - } - result.add(new MavenPropertyPsiReference(mavenProject, element, propertyName, range, isSoft)); + return result == null ? PsiReference.EMPTY_ARRAY : result.toArray(new PsiReference[result.size()]); } - - return result == null ? PsiReference.EMPTY_ARRAY : result.toArray(new PsiReference[result.size()]); - } } diff --git a/plugin/src/main/java/org/jetbrains/idea/maven/dom/references/MavenPsiElementWrapper.java b/plugin/src/main/java/org/jetbrains/idea/maven/dom/references/MavenPsiElementWrapper.java index 985c3691..4bb50fd3 100644 --- a/plugin/src/main/java/org/jetbrains/idea/maven/dom/references/MavenPsiElementWrapper.java +++ b/plugin/src/main/java/org/jetbrains/idea/maven/dom/references/MavenPsiElementWrapper.java @@ -15,60 +15,63 @@ */ package org.jetbrains.idea.maven.dom.references; +import consulo.annotation.access.RequiredReadAction; import consulo.document.util.TextRange; +import consulo.maven.icon.MavenIconGroup; import consulo.navigation.Navigatable; import consulo.language.psi.PsiElement; import consulo.language.psi.PsiNamedElement; import consulo.language.impl.psi.RenameableFakePsiElement; import consulo.ui.image.Image; -import org.jetbrains.idea.maven.MavenIcons; public class MavenPsiElementWrapper extends RenameableFakePsiElement { - private final PsiElement myWrappee; - private final Navigatable myNavigatable; + private final PsiElement myWrappee; + private final Navigatable myNavigatable; - public MavenPsiElementWrapper(PsiElement wrappeeElement, Navigatable navigatable) { - super(wrappeeElement.getParent()); - myWrappee = wrappeeElement; - myNavigatable = navigatable; - } + public MavenPsiElementWrapper(PsiElement wrappeeElement, Navigatable navigatable) { + super(wrappeeElement.getParent()); + myWrappee = wrappeeElement; + myNavigatable = navigatable; + } - public PsiElement getWrappee() { - return myWrappee; - } + public PsiElement getWrappee() { + return myWrappee; + } - public PsiElement getParent() { - return myWrappee.getParent(); - } + @Override + public PsiElement getParent() { + return myWrappee.getParent(); + } - @Override - public String getName() { - return ((PsiNamedElement)myWrappee).getName(); - } + @Override + @RequiredReadAction + public String getName() { + return ((PsiNamedElement)myWrappee).getName(); + } - @Override - public void navigate(boolean requestFocus) { - myNavigatable.navigate(requestFocus); - } + @Override + public void navigate(boolean requestFocus) { + myNavigatable.navigate(requestFocus); + } - public String getTypeName() { - return "Property"; - } + @Override + public String getTypeName() { + return "Property"; + } - public Image getIcon() { - return MavenIcons.MavenLogo; - } + @Override + public Image getIcon() { + return MavenIconGroup.mavenlogo(); + } - @Override - public TextRange getTextRange() { - return myWrappee.getTextRange(); - } + @Override + @RequiredReadAction + public TextRange getTextRange() { + return myWrappee.getTextRange(); + } - @Override - public boolean isEquivalentTo(PsiElement other) { - if (other instanceof MavenPsiElementWrapper) { - return myWrappee == ((MavenPsiElementWrapper)other).myWrappee; + @Override + public boolean isEquivalentTo(PsiElement other) { + return other instanceof MavenPsiElementWrapper wrapper ? myWrappee == wrapper.myWrappee : myWrappee == other; } - return myWrappee == other; - } } diff --git a/plugin/src/main/java/org/jetbrains/idea/maven/dom/references/MavenPsiReference.java b/plugin/src/main/java/org/jetbrains/idea/maven/dom/references/MavenPsiReference.java index 9e44f9c5..133093ae 100644 --- a/plugin/src/main/java/org/jetbrains/idea/maven/dom/references/MavenPsiReference.java +++ b/plugin/src/main/java/org/jetbrains/idea/maven/dom/references/MavenPsiReference.java @@ -15,6 +15,8 @@ */ package org.jetbrains.idea.maven.dom.references; +import consulo.annotation.access.RequiredReadAction; +import consulo.annotation.access.RequiredWriteAction; import consulo.document.util.TextRange; import consulo.language.psi.PsiElement; import consulo.language.psi.PsiFile; @@ -26,78 +28,84 @@ import javax.annotation.Nonnull; -public abstract class MavenPsiReference implements PsiReference -{ - protected final - @Nonnull - Project myProject; - protected final - @Nonnull - MavenProjectsManager myProjectsManager; +public abstract class MavenPsiReference implements PsiReference { + protected final + @Nonnull + Project myProject; + protected final + @Nonnull + MavenProjectsManager myProjectsManager; - protected final - @Nonnull - PsiFile myPsiFile; - protected final - @Nonnull - VirtualFile myVirtualFile; + protected final + @Nonnull + PsiFile myPsiFile; + protected final + @Nonnull + VirtualFile myVirtualFile; - protected final - @Nonnull - PsiElement myElement; - protected final - @Nonnull - String myText; - protected final - @Nonnull - TextRange myRange; + protected final + @Nonnull + PsiElement myElement; + protected final + @Nonnull + String myText; + protected final + @Nonnull + TextRange myRange; - public MavenPsiReference(@Nonnull PsiElement element, @Nonnull String text, @Nonnull TextRange range) - { - myProject = element.getProject(); - myProjectsManager = MavenProjectsManager.getInstance(myProject); + public MavenPsiReference(@Nonnull PsiElement element, @Nonnull String text, @Nonnull TextRange range) { + myProject = element.getProject(); + myProjectsManager = MavenProjectsManager.getInstance(myProject); - myPsiFile = element.getContainingFile().getOriginalFile(); - myVirtualFile = myPsiFile.getVirtualFile(); + myPsiFile = element.getContainingFile().getOriginalFile(); + myVirtualFile = myPsiFile.getVirtualFile(); - myElement = element; - myText = text; - myRange = range; - } + myElement = element; + myText = text; + myRange = range; + } - public PsiElement getElement() - { - return myElement; - } + @Override + @RequiredReadAction + public PsiElement getElement() { + return myElement; + } - @Nonnull - public String getCanonicalText() - { - return myText; - } + @Nonnull + @Override + @RequiredReadAction + public String getCanonicalText() { + return myText; + } - public TextRange getRangeInElement() - { - return myRange; - } + @Nonnull + @Override + @RequiredReadAction + public TextRange getRangeInElement() { + return myRange; + } - public boolean isReferenceTo(PsiElement element) - { - return getElement().getManager().areElementsEquivalent(element, resolve()); - } + @Override + @RequiredReadAction + public boolean isReferenceTo(PsiElement element) { + return getElement().getManager().areElementsEquivalent(element, resolve()); + } - public PsiElement handleElementRename(String newElementName) throws IncorrectOperationException - { - return null; - } + @Override + @RequiredWriteAction + public PsiElement handleElementRename(String newElementName) throws IncorrectOperationException { + return null; + } - public PsiElement bindToElement(@Nonnull PsiElement element) throws IncorrectOperationException - { - return null; - } + @Override + @RequiredWriteAction + public PsiElement bindToElement(@Nonnull PsiElement element) throws IncorrectOperationException { + return null; + } - public boolean isSoft() - { - return true; - } + @Override + @RequiredReadAction + public boolean isSoft() { + return true; + } } \ No newline at end of file diff --git a/plugin/src/main/java/org/jetbrains/idea/maven/dom/references/MavenTargetUtil.java b/plugin/src/main/java/org/jetbrains/idea/maven/dom/references/MavenTargetUtil.java index 9c8f6e4d..b85bcaf5 100644 --- a/plugin/src/main/java/org/jetbrains/idea/maven/dom/references/MavenTargetUtil.java +++ b/plugin/src/main/java/org/jetbrains/idea/maven/dom/references/MavenTargetUtil.java @@ -28,48 +28,39 @@ import java.util.Set; -public class MavenTargetUtil -{ - @RequiredUIAccess - public static PsiElement getRefactorTarget(Editor editor, PsiFile file) - { - PsiElement target = getFindTarget(editor, file); - return target == null || !MavenDomUtil.isMavenProperty(target) ? null : target; - } +public class MavenTargetUtil { + @RequiredUIAccess + public static PsiElement getRefactorTarget(Editor editor, PsiFile file) { + PsiElement target = getFindTarget(editor, file); + return target == null || !MavenDomUtil.isMavenProperty(target) ? null : target; + } - @RequiredUIAccess - public static PsiElement getFindTarget(Editor editor, PsiFile file) - { - if(editor == null || file == null) - { - return null; - } + @RequiredUIAccess + public static PsiElement getFindTarget(Editor editor, PsiFile file) { + if (editor == null || file == null) { + return null; + } - PsiElement target = TargetElementUtil.findTargetElement(editor, Set.of(TargetElementUtilExtender.REFERENCED_ELEMENT_ACCEPTED)); - if(target instanceof MavenPsiElementWrapper) - { - return ((MavenPsiElementWrapper) target).getWrappee(); - } + PsiElement target = TargetElementUtil.findTargetElement(editor, Set.of(TargetElementUtilExtender.REFERENCED_ELEMENT_ACCEPTED)); + if (target instanceof MavenPsiElementWrapper wrapper) { + return wrapper.getWrappee(); + } - if(target == null || isSchema(target)) - { - target = file.findElementAt(editor.getCaretModel().getOffset()); - if(target == null) - { - return null; - } - } + if (target == null || isSchema(target)) { + target = file.findElementAt(editor.getCaretModel().getOffset()); + if (target == null) { + return null; + } + } - if(!MavenDomUtil.isMavenFile(target)) - { - return null; - } + if (!MavenDomUtil.isMavenFile(target)) { + return null; + } - return PsiTreeUtil.getParentOfType(target, XmlTag.class, false); - } + return PsiTreeUtil.getParentOfType(target, XmlTag.class, false); + } - private static boolean isSchema(PsiElement element) - { - return element instanceof XmlTag && XmlUtil.XML_SCHEMA_URI.equals(((XmlTag) element).getNamespace()); - } + private static boolean isSchema(PsiElement element) { + return element instanceof XmlTag tag && XmlUtil.XML_SCHEMA_URI.equals(tag.getNamespace()); + } } diff --git a/plugin/src/main/java/org/jetbrains/idea/maven/dom/references/MavenUrlPsiReference.java b/plugin/src/main/java/org/jetbrains/idea/maven/dom/references/MavenUrlPsiReference.java index 20f257d3..d2f5460c 100644 --- a/plugin/src/main/java/org/jetbrains/idea/maven/dom/references/MavenUrlPsiReference.java +++ b/plugin/src/main/java/org/jetbrains/idea/maven/dom/references/MavenUrlPsiReference.java @@ -17,36 +17,43 @@ import javax.annotation.Nonnull; +import consulo.annotation.access.RequiredReadAction; import consulo.ide.impl.idea.ide.BrowserUtil; import consulo.document.util.TextRange; import consulo.language.impl.psi.FakePsiElement; import consulo.language.psi.PsiElement; public class MavenUrlPsiReference extends MavenPsiReference { - public MavenUrlPsiReference(PsiElement element, String text, TextRange range) { - super(element, text, range); - } + public MavenUrlPsiReference(PsiElement element, String text, TextRange range) { + super(element, text, range); + } - public PsiElement resolve() { - return new FakePsiElement() { - public PsiElement getParent() { - return myElement; - } + @Override + @RequiredReadAction + public PsiElement resolve() { + return new FakePsiElement() { + @Override + public PsiElement getParent() { + return myElement; + } - @Override - public String getName() { - return myText; - } + @Override + @RequiredReadAction + public String getName() { + return myText; + } - @Override - public void navigate(boolean requestFocus) { - BrowserUtil.launchBrowser(myText); - } - }; - } + @Override + public void navigate(boolean requestFocus) { + BrowserUtil.launchBrowser(myText); + } + }; + } - @Nonnull - public Object[] getVariants() { - return EMPTY_ARRAY; - } + @Nonnull + @Override + @RequiredReadAction + public Object[] getVariants() { + return EMPTY_ARRAY; + } } \ No newline at end of file diff --git a/plugin/src/main/java/org/jetbrains/idea/maven/dom/references/MavenUsageTargetProvider.java b/plugin/src/main/java/org/jetbrains/idea/maven/dom/references/MavenUsageTargetProvider.java index 37f74dd8..fd59d4e6 100644 --- a/plugin/src/main/java/org/jetbrains/idea/maven/dom/references/MavenUsageTargetProvider.java +++ b/plugin/src/main/java/org/jetbrains/idea/maven/dom/references/MavenUsageTargetProvider.java @@ -20,24 +20,24 @@ import consulo.ide.impl.find.PsiElement2UsageTargetAdapter; import consulo.language.psi.PsiElement; import consulo.language.psi.PsiFile; +import consulo.ui.annotation.RequiredUIAccess; import consulo.usage.UsageTarget; import consulo.usage.UsageTargetProvider; @ExtensionImpl -public class MavenUsageTargetProvider implements UsageTargetProvider -{ - public UsageTarget[] getTargets(Editor editor, PsiFile file) - { - PsiElement target = MavenTargetUtil.getFindTarget(editor, file); - if(target == null) - { - return UsageTarget.EMPTY_ARRAY; - } - return new UsageTarget[]{new PsiElement2UsageTargetAdapter(target)}; - } +public class MavenUsageTargetProvider implements UsageTargetProvider { + @Override + @RequiredUIAccess + public UsageTarget[] getTargets(Editor editor, PsiFile file) { + PsiElement target = MavenTargetUtil.getFindTarget(editor, file); + if (target == null) { + return UsageTarget.EMPTY_ARRAY; + } + return new UsageTarget[]{new PsiElement2UsageTargetAdapter(target)}; + } - public UsageTarget[] getTargets(PsiElement psiElement) - { - return UsageTarget.EMPTY_ARRAY; - } + @Override + public UsageTarget[] getTargets(PsiElement psiElement) { + return UsageTarget.EMPTY_ARRAY; + } }