Search in sources :

Example 1 with MavenProject

use of org.jetbrains.idea.maven.project.MavenProject in project intellij-community by JetBrains.

the class MavenGroovyPomCompletionContributor method fillCompletionVariants.

@Override
public void fillCompletionVariants(@NotNull CompletionParameters parameters, @NotNull CompletionResultSet result) {
    final PsiElement position = parameters.getPosition();
    if (!(position instanceof LeafElement))
        return;
    Project project = position.getProject();
    VirtualFile virtualFile = parameters.getOriginalFile().getVirtualFile();
    if (virtualFile == null)
        return;
    MavenProject mavenProject = MavenProjectsManager.getInstance(project).findProject(virtualFile);
    if (mavenProject == null)
        return;
    List<String> methodCallInfo = MavenGroovyPomUtil.getGroovyMethodCalls(position);
    if (methodCallInfo.isEmpty())
        return;
    StringBuilder buf = new StringBuilder();
    for (String s : methodCallInfo) {
        buf.append('<').append(s).append('>');
    }
    for (String s : ContainerUtil.reverse(methodCallInfo)) {
        buf.append('<').append(s).append("/>");
    }
    PsiFile psiFile = PsiFileFactory.getInstance(project).createFileFromText("pom.xml", XMLLanguage.INSTANCE, buf);
    psiFile.putUserData(ORIGINAL_POM_FILE, virtualFile);
    List<Object> variants = ContainerUtil.newArrayList();
    String lastMethodCall = ContainerUtil.getLastItem(methodCallInfo);
    Ref<Boolean> completeDependency = Ref.create(false);
    Ref<Boolean> completeVersion = Ref.create(false);
    psiFile.accept(new PsiRecursiveElementVisitor(true) {

        @Override
        public void visitElement(PsiElement element) {
            super.visitElement(element);
            if (!completeDependency.get() && element.getParent() instanceof XmlTag && "dependency".equals(((XmlTag) element.getParent()).getName())) {
                if ("artifactId".equals(lastMethodCall) || "groupId".equals(lastMethodCall)) {
                    completeDependency.set(true);
                } else if ("version".equals(lastMethodCall) || "dependency".equals(lastMethodCall)) {
                    completeVersion.set(true);
                //completeDependency.set(true);
                }
            }
            if (!completeDependency.get() && !completeVersion.get()) {
                PsiReference[] references = getReferences(element);
                for (PsiReference each : references) {
                    if (each instanceof GenericDomValueReference) {
                        Collections.addAll(variants, each.getVariants());
                    }
                }
            }
        }
    });
    for (Object variant : variants) {
        if (variant instanceof LookupElement) {
            result.addElement((LookupElement) variant);
        } else {
            result.addElement(LookupElementBuilder.create(variant));
        }
    }
    if (completeDependency.get()) {
        MavenProjectIndicesManager indicesManager = MavenProjectIndicesManager.getInstance(project);
        for (String groupId : indicesManager.getGroupIds()) {
            for (String artifactId : indicesManager.getArtifactIds(groupId)) {
                LookupElement builder = LookupElementBuilder.create(groupId + ':' + artifactId).withIcon(AllIcons.Nodes.PpLib).withInsertHandler(MavenDependencyInsertHandler.INSTANCE);
                result.addElement(builder);
            }
        }
    }
    if (completeVersion.get()) {
        consumeDependencyElement(position, closableBlock -> {
            String groupId = null;
            String artifactId = null;
            for (GrMethodCall methodCall : PsiTreeUtil.findChildrenOfType(closableBlock, GrMethodCall.class)) {
                GroovyPsiElement[] arguments = methodCall.getArgumentList().getAllArguments();
                if (arguments.length != 1)
                    continue;
                PsiReference reference = arguments[0].getReference();
                if (reference == null)
                    continue;
                String callExpression = methodCall.getInvokedExpression().getText();
                String argumentValue = reference.getCanonicalText();
                if ("groupId".equals(callExpression)) {
                    groupId = argumentValue;
                } else if ("artifactId".equals(callExpression)) {
                    artifactId = argumentValue;
                }
            }
            completeVersions(result, project, groupId, artifactId, "");
        }, element -> {
            if (element.getParent() instanceof PsiLiteral) {
                Object value = ((PsiLiteral) element.getParent()).getValue();
                if (value == null)
                    return;
                String[] mavenCoordinates = value.toString().split(":");
                if (mavenCoordinates.length < 3)
                    return;
                String prefix = mavenCoordinates[0] + ':' + mavenCoordinates[1] + ':';
                completeVersions(result, project, mavenCoordinates[0], mavenCoordinates[1], prefix);
            }
        });
    }
}
Also used : VirtualFile(com.intellij.openapi.vfs.VirtualFile) GrMethodCall(org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrMethodCall) MavenProject(org.jetbrains.idea.maven.project.MavenProject) GenericDomValueReference(com.intellij.util.xml.impl.GenericDomValueReference) GroovyPsiElement(org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElement) MavenProjectIndicesManager(org.jetbrains.idea.maven.indices.MavenProjectIndicesManager) GroovyPsiElement(org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElement) LookupElement(com.intellij.codeInsight.lookup.LookupElement) Project(com.intellij.openapi.project.Project) MavenProject(org.jetbrains.idea.maven.project.MavenProject) LeafElement(com.intellij.psi.impl.source.tree.LeafElement) XmlTag(com.intellij.psi.xml.XmlTag)

Example 2 with MavenProject

use of org.jetbrains.idea.maven.project.MavenProject in project intellij-community by JetBrains.

the class MavenAnnotationProcessorConfigurer method configure.

@Override
public void configure(@NotNull MavenProject mavenProject, @NotNull Project project, @Nullable Module module) {
    if (module == null)
        return;
    Sdk sdk = ModuleRootManager.getInstance(module).getSdk();
    if (sdk != null) {
        String versionString = sdk.getVersionString();
        if (versionString != null) {
            if (versionString.contains("1.5") || versionString.contains("1.4") || versionString.contains("1.3") || versionString.contains("1.2")) {
                return;
            }
        }
    }
    final CompilerConfigurationImpl compilerConfiguration = (CompilerConfigurationImpl) CompilerConfiguration.getInstance(project);
    final MavenProject rootProject = ObjectUtils.notNull(MavenProjectsManager.getInstance(project).findRootProject(mavenProject), mavenProject);
    if (shouldEnableAnnotationProcessors(mavenProject)) {
        final String moduleProfileName;
        String annotationProcessorDirectory = getRelativeAnnotationProcessorDirectory(mavenProject, false);
        if (annotationProcessorDirectory == null) {
            annotationProcessorDirectory = DEFAULT_ANNOTATION_PATH_OUTPUT;
        }
        String testAnnotationProcessorDirectory = getRelativeAnnotationProcessorDirectory(mavenProject, true);
        if (testAnnotationProcessorDirectory == null) {
            testAnnotationProcessorDirectory = DEFAULT_TEST_ANNOTATION_OUTPUT;
        }
        final boolean isDefault;
        if (isMavenDefaultAnnotationProcessorConfiguration(annotationProcessorDirectory, testAnnotationProcessorDirectory, mavenProject)) {
            moduleProfileName = MAVEN_DEFAULT_ANNOTATION_PROFILE;
            isDefault = true;
        } else if (isMavenProcessorPluginDefaultConfiguration(annotationProcessorDirectory, testAnnotationProcessorDirectory, mavenProject)) {
            moduleProfileName = MAVEN_BSC_DEFAULT_ANNOTATION_PROFILE;
            isDefault = true;
        } else {
            moduleProfileName = PROFILE_PREFIX + module.getName();
            isDefault = false;
        }
        ProcessorConfigProfile moduleProfile = compilerConfiguration.findModuleProcessorProfile(moduleProfileName);
        if (moduleProfile == null) {
            moduleProfile = new ProcessorConfigProfileImpl(moduleProfileName);
            compilerConfiguration.addModuleProcessorProfile(moduleProfile);
        }
        moduleProfile.setOutputRelativeToContentRoot(true);
        moduleProfile.setEnabled(true);
        moduleProfile.setObtainProcessorsFromClasspath(true);
        moduleProfile.setGeneratedSourcesDirectoryName(annotationProcessorDirectory, false);
        moduleProfile.setGeneratedSourcesDirectoryName(testAnnotationProcessorDirectory, true);
        moduleProfile.clearProcessorOptions();
        for (Map.Entry<String, String> entry : mavenProject.getAnnotationProcessorOptions().entrySet()) {
            moduleProfile.setOption(entry.getKey(), entry.getValue());
        }
        moduleProfile.clearProcessors();
        final List<String> processors = mavenProject.getDeclaredAnnotationProcessors();
        if (processors != null) {
            for (String processor : processors) {
                moduleProfile.addProcessor(processor);
            }
        }
        moduleProfile.addModuleName(module.getName());
        cleanAndMergeModuleProfiles(rootProject, compilerConfiguration, moduleProfile, isDefault, module);
    } else {
        cleanAndMergeModuleProfiles(rootProject, compilerConfiguration, null, false, module);
    }
}
Also used : MavenProject(org.jetbrains.idea.maven.project.MavenProject) CompilerConfigurationImpl(com.intellij.compiler.CompilerConfigurationImpl) ProcessorConfigProfile(org.jetbrains.jps.model.java.compiler.ProcessorConfigProfile) Sdk(com.intellij.openapi.projectRoots.Sdk) ProcessorConfigProfileImpl(org.jetbrains.jps.model.java.impl.compiler.ProcessorConfigProfileImpl) Map(java.util.Map)

Example 3 with MavenProject

use of org.jetbrains.idea.maven.project.MavenProject in project intellij-community by JetBrains.

the class MavenSelectProjectPopup method attachToButton.

public static void attachToButton(@NotNull final MavenProjectsManager projectsManager, @NotNull final JButton button, @NotNull final Consumer<MavenProject> callback) {
    button.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            List<MavenProject> projectList = projectsManager.getProjects();
            if (projectList.isEmpty()) {
                JBPopupFactory.getInstance().createMessage("Maven projects not found").showUnderneathOf(button);
                return;
            }
            DefaultMutableTreeNode root = buildTree(projectList);
            final Map<MavenProject, String> projectsNameMap = MavenProjectNamer.generateNameMap(projectList);
            final Tree projectTree = new Tree(root);
            projectTree.setRootVisible(false);
            projectTree.setCellRenderer(new NodeRenderer() {

                @Override
                public void customizeCellRenderer(JTree tree, Object value, boolean selected, boolean expanded, boolean leaf, int row, boolean hasFocus) {
                    if (value instanceof DefaultMutableTreeNode) {
                        MavenProject mavenProject = (MavenProject) ((DefaultMutableTreeNode) value).getUserObject();
                        value = projectsNameMap.get(mavenProject);
                        setIcon(MavenIcons.MavenProject);
                    }
                    super.customizeCellRenderer(tree, value, selected, expanded, leaf, row, hasFocus);
                }
            });
            new TreeSpeedSearch(projectTree, new Convertor<TreePath, String>() {

                @Override
                public String convert(TreePath o) {
                    Object lastPathComponent = o.getLastPathComponent();
                    if (!(lastPathComponent instanceof DefaultMutableTreeNode))
                        return null;
                    Object userObject = ((DefaultMutableTreeNode) lastPathComponent).getUserObject();
                    //noinspection SuspiciousMethodCalls
                    return projectsNameMap.get(userObject);
                }
            });
            final Ref<JBPopup> popupRef = new Ref<>();
            final Runnable clickCallBack = () -> {
                TreePath path = projectTree.getSelectionPath();
                if (path == null)
                    return;
                Object lastPathComponent = path.getLastPathComponent();
                if (!(lastPathComponent instanceof DefaultMutableTreeNode))
                    return;
                Object object = ((DefaultMutableTreeNode) lastPathComponent).getUserObject();
                // may be it's the root
                if (object == null)
                    return;
                callback.consume((MavenProject) object);
                popupRef.get().closeOk(null);
            };
            projectTree.addKeyListener(new KeyAdapter() {

                @Override
                public void keyPressed(KeyEvent e) {
                    if (e.getKeyCode() == KeyEvent.VK_ENTER) {
                        clickCallBack.run();
                        e.consume();
                    }
                }
            });
            JBPopup popup = new PopupChooserBuilder(projectTree).setTitle("Select maven project").setResizable(true).setItemChoosenCallback(clickCallBack).setAutoselectOnMouseMove(true).setCloseOnEnter(false).createPopup();
            popupRef.set(popup);
            popup.showUnderneathOf(button);
        }

        private DefaultMutableTreeNode buildTree(List<MavenProject> projectList) {
            MavenProject[] projects = projectList.toArray(new MavenProject[projectList.size()]);
            Arrays.sort(projects, new MavenProjectNamer.MavenProjectComparator());
            Map<MavenProject, DefaultMutableTreeNode> projectsToNode = new HashMap<>();
            for (MavenProject mavenProject : projects) {
                projectsToNode.put(mavenProject, new DefaultMutableTreeNode(mavenProject));
            }
            DefaultMutableTreeNode root = new DefaultMutableTreeNode();
            for (MavenProject mavenProject : projects) {
                DefaultMutableTreeNode parent;
                MavenProject aggregator = projectsManager.findAggregator(mavenProject);
                if (aggregator != null) {
                    parent = projectsToNode.get(aggregator);
                } else {
                    parent = root;
                }
                parent.add(projectsToNode.get(mavenProject));
            }
            return root;
        }
    });
}
Also used : DefaultMutableTreeNode(javax.swing.tree.DefaultMutableTreeNode) ActionEvent(java.awt.event.ActionEvent) TreeSpeedSearch(com.intellij.ui.TreeSpeedSearch) KeyAdapter(java.awt.event.KeyAdapter) Convertor(com.intellij.util.containers.Convertor) NodeRenderer(com.intellij.ide.util.treeView.NodeRenderer) KeyEvent(java.awt.event.KeyEvent) Ref(com.intellij.openapi.util.Ref) ActionListener(java.awt.event.ActionListener) MavenProject(org.jetbrains.idea.maven.project.MavenProject) TreePath(javax.swing.tree.TreePath) Tree(com.intellij.ui.treeStructure.Tree) List(java.util.List) PopupChooserBuilder(com.intellij.openapi.ui.popup.PopupChooserBuilder) JBPopup(com.intellij.openapi.ui.popup.JBPopup) HashMap(java.util.HashMap) Map(java.util.Map)

Example 4 with MavenProject

use of org.jetbrains.idea.maven.project.MavenProject in project intellij-community by JetBrains.

the class MavenProjectModelModifier method addModuleDependency.

@Nullable
@Override
public Promise<Void> addModuleDependency(@NotNull Module from, @NotNull Module to, @NotNull final DependencyScope scope) {
    final MavenProject toProject = myProjectsManager.findProject(to);
    if (toProject == null)
        return null;
    MavenId mavenId = toProject.getMavenId();
    return addDependency(Collections.singletonList(from), mavenId, scope);
}
Also used : MavenId(org.jetbrains.idea.maven.model.MavenId) MavenProject(org.jetbrains.idea.maven.project.MavenProject) Nullable(org.jetbrains.annotations.Nullable)

Example 5 with MavenProject

use of org.jetbrains.idea.maven.project.MavenProject in project intellij-community by JetBrains.

the class MavenProjectsNavigatorPanel method extractGoals.

private List<String> extractGoals(boolean qualifiedGoals) {
    final MavenProjectsStructure.ProjectNode projectNode = getSelectedProjectNode();
    if (projectNode != null) {
        MavenProject project = projectNode.getMavenProject();
        String goal = project.getDefaultGoal();
        if (!StringUtil.isEmptyOrSpaces(goal)) {
            // Maven uses StringTokenizer to split defaultGoal. See DefaultLifecycleTaskSegmentCalculator#calculateTaskSegments()
            return ContainerUtil.newArrayList(StringUtil.tokenize(new StringTokenizer(goal)));
        }
    } else {
        final List<MavenProjectsStructure.GoalNode> nodes = getSelectedNodes(MavenProjectsStructure.GoalNode.class);
        if (MavenProjectsStructure.getCommonProjectNode(nodes) == null) {
            return null;
        }
        final List<String> goals = new ArrayList<>();
        for (MavenProjectsStructure.GoalNode node : nodes) {
            goals.add(qualifiedGoals ? node.getGoal() : node.getName());
        }
        Collections.sort(goals, myGoalOrderComparator);
        return goals;
    }
    return null;
}
Also used : MavenProject(org.jetbrains.idea.maven.project.MavenProject)

Aggregations

MavenProject (org.jetbrains.idea.maven.project.MavenProject)132 VirtualFile (com.intellij.openapi.vfs.VirtualFile)40 MavenProjectsManager (org.jetbrains.idea.maven.project.MavenProjectsManager)20 MavenId (org.jetbrains.idea.maven.model.MavenId)16 Project (com.intellij.openapi.project.Project)10 Nullable (org.jetbrains.annotations.Nullable)9 Bombed (com.intellij.idea.Bombed)8 Module (com.intellij.openapi.module.Module)6 DataContext (com.intellij.openapi.actionSystem.DataContext)5 File (java.io.File)5 ArrayList (java.util.ArrayList)5 Result (com.intellij.openapi.application.Result)4 MavenArtifact (org.jetbrains.idea.maven.model.MavenArtifact)4 MavenEmbeddersManager (org.jetbrains.idea.maven.project.MavenEmbeddersManager)4 WriteCommandAction (com.intellij.openapi.command.WriteCommandAction)3 TextRange (com.intellij.openapi.util.TextRange)3 NotNull (org.jetbrains.annotations.NotNull)3 MavenRunnerParameters (org.jetbrains.idea.maven.execution.MavenRunnerParameters)3 MavenExplicitProfiles (org.jetbrains.idea.maven.model.MavenExplicitProfiles)3 MavenProjectsTree (org.jetbrains.idea.maven.project.MavenProjectsTree)3