@Nullable
 public static MavenProject findContainingProject(@NotNull PsiElement element) {
   VirtualFile file = getVirtualFile(element);
   if (file == null) return null;
   MavenProjectsManager manager = MavenProjectsManager.getInstance(element.getProject());
   return manager.findContainingProject(file);
 }
  public void testHandlingDirectoryWithPomFileDeletion() throws Exception {
    importProject(
        "<groupId>test</groupId>"
            + "<artifactId>project</artifactId>"
            + "<packaging>pom</packaging>"
            + "<version>1</version>");

    createModulePom(
        "dir/module",
        "<groupId>test</groupId>" + "<artifactId>module</artifactId>" + "<version>1</version>");
    createProjectPom(
        "<groupId>test</groupId>"
            + "<artifactId>project</artifactId>"
            + "<packaging>pom</packaging>"
            + "<version>1</version>"
            + "<modules>"
            + "  <module>dir/module</module>"
            + "</modules>");
    waitForReadingCompletion();

    assertEquals(2, MavenProjectsManager.getInstance(myProject).getProjects().size());

    final VirtualFile dir = myProjectRoot.findChild("dir");
    new WriteCommandAction.Simple(myProject) {
      @Override
      protected void run() throws Throwable {
        dir.delete(null);
      }
    }.execute().throwException();

    waitForReadingCompletion();

    assertEquals(1, MavenProjectsManager.getInstance(myProject).getProjects().size());
  }
Example #3
0
 protected void readProjects(VirtualFile... files) {
   List<MavenProject> projects = new ArrayList<MavenProject>();
   for (VirtualFile each : files) {
     projects.add(myProjectsManager.findProject(each));
   }
   myProjectsManager.forceUpdateProjects(projects);
   waitForReadingCompletion();
 }
  @Nullable
  public static MavenProject findProject(@NotNull 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);
  }
Example #5
0
 protected void resolveFoldersAndImport() {
   myProjectsManager.scheduleFoldersResolveForAllProjects();
   myProjectsManager.waitForFoldersResolvingCompletion();
   UIUtil.invokeAndWaitIfNeeded(
       new Runnable() {
         @Override
         public void run() {
           myProjectsManager.performScheduledImportInTests();
         }
       });
 }
    public void applyFix(@NotNull Project project, @NotNull ProblemDescriptor descriptor) {
      GenericDomValue el = (GenericDomValue) myContext.getInvocationElement();
      MavenId id = MavenArtifactCoordinatesHelper.getId(myContext);

      MavenProjectsManager manager = MavenProjectsManager.getInstance(project);
      MavenProject parentFile = manager.findProject(id);
      if (parentFile != null) {
        VirtualFile currentFile = myContext.getFile().getVirtualFile();
        el.setStringValue(
            MavenDomUtil.calcRelativePath(currentFile.getParent(), parentFile.getFile()));
      }
    }
  private static File dumpModulesPaths(@NotNull Project project) throws IOException {
    ApplicationManager.getApplication().assertReadAccessAllowed();

    Properties res = new Properties();

    MavenProjectsManager manager = MavenProjectsManager.getInstance(project);

    for (Module module : ModuleManager.getInstance(project).getModules()) {
      if (manager.isMavenizedModule(module)) {
        MavenProject mavenProject = manager.findProject(module);
        if (mavenProject != null && !manager.isIgnored(mavenProject)) {
          res.setProperty(
              mavenProject.getMavenId().getGroupId()
                  + ':'
                  + mavenProject.getMavenId().getArtifactId()
                  + ":pom"
                  + ':'
                  + mavenProject.getMavenId().getVersion(),
              mavenProject.getFile().getPath());

          res.setProperty(
              mavenProject.getMavenId().getGroupId()
                  + ':'
                  + mavenProject.getMavenId().getArtifactId()
                  + ':'
                  + mavenProject.getPackaging()
                  + ':'
                  + mavenProject.getMavenId().getVersion(),
              mavenProject.getOutputDirectory());
        }
      }
    }

    File file =
        new File(
            PathManager.getSystemPath(),
            "Maven/idea-projects-state-" + project.getLocationHash() + ".properties");
    file.getParentFile().mkdirs();

    OutputStream out = new BufferedOutputStream(new FileOutputStream(file));
    try {
      res.store(out, null);
    } finally {
      out.close();
    }

    return file;
  }
  private static <T> boolean processParentProjectFile(
      MavenDomProjectModel projectDom,
      final Processor<T> processor,
      final Project project,
      final Function<? super MavenDomProfile, T> domProfileFunction,
      final Function<? super MavenDomProjectModel, T> projectDomFunction,
      final Set<MavenDomProjectModel> processed) {
    Boolean aBoolean =
        new DomParentProjectFileProcessor<Boolean>(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();
  }
  @Nullable
  public static Module findContainingMavenizedModule(@NotNull 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();

    Module module = index.getModuleForFile(file);
    if (module == null || !manager.isMavenizedModule(module)) return null;
    return module;
  }
  private static ExecutionException createExecutionException(
      String text,
      String textWithFix,
      @NotNull MavenGeneralSettings coreSettings,
      @Nullable Project project,
      @Nullable MavenRunConfiguration runConfiguration) {
    Project notNullProject = project;
    if (notNullProject == null) {
      if (runConfiguration == null) return new ExecutionException(text);
      notNullProject = runConfiguration.getProject();
      if (notNullProject == null) return new ExecutionException(text);
    }

    if (coreSettings == MavenProjectsManager.getInstance(notNullProject).getGeneralSettings()) {
      return new ProjectSettingsOpenerExecutionException(textWithFix, notNullProject);
    }

    if (runConfiguration != null) {
      Project runCfgProject = runConfiguration.getProject();
      if (runCfgProject != null) {
        if (((RunManagerImpl) RunManager.getInstance(runCfgProject)).getSettings(runConfiguration)
            != null) {
          return new RunConfigurationOpenerExecutionException(textWithFix, runConfiguration);
        }
      }
    }

    return new ExecutionException(text);
  }
  public static void actionPerformed(
      @NotNull final Project project, @NotNull final VirtualFile file) {
    final MavenProjectsManager manager = MavenProjectsManager.getInstance(project);

    final MavenProject mavenProject = manager.findProject(file);
    assert mavenProject != null;

    manager.evaluateEffectivePom(
        mavenProject,
        new NullableConsumer<String>() {
          @Override
          public void consume(final String s) {
            ApplicationManager.getApplication()
                .invokeLater(
                    new Runnable() {
                      @Override
                      public void run() {
                        if (project.isDisposed()) return;

                        if (s == null) { // null means UnsupportedOperationException
                          new Notification(
                                  MavenUtil.MAVEN_NOTIFICATION_GROUP,
                                  "Error",
                                  "Failed to evaluate effective pom.",
                                  NotificationType.ERROR)
                              .notify(project);
                          return;
                        }

                        String fileName =
                            mavenProject.getMavenId().getArtifactId() + "-effective-pom.xml";
                        PsiFile file =
                            PsiFileFactory.getInstance(project)
                                .createFileFromText(fileName, XMLLanguage.INSTANCE, s);
                        try {
                          //noinspection ConstantConditions
                          file.getVirtualFile().setWritable(false);
                        } catch (IOException e) {
                          LOG.error(e);
                        }

                        file.navigate(true);
                      }
                    });
          }
        });
  }
  private static void notifyUserIfNeeded(
      DataContext context,
      MavenProjectsManager projectsManager,
      List<VirtualFile> selectedFiles,
      VirtualFile pomXml) {
    MavenProject mavenProject = projectsManager.findProject(pomXml);
    assert mavenProject != null;

    MavenProject aggregator = projectsManager.findAggregator(mavenProject);
    while (aggregator != null && !projectsManager.isManagedFile(aggregator.getFile())) {
      aggregator = projectsManager.findAggregator(aggregator);
    }

    if (aggregator != null && !selectedFiles.contains(aggregator.getFile())) {
      notifyUser(context, mavenProject, aggregator);
    }
  }
  @Nullable
  private static VirtualFile findPomXml(@NotNull DataContext dataContext) {
    VirtualFile file = CommonDataKeys.VIRTUAL_FILE.getData(dataContext);
    if (file == null) return null;

    if (file.isDirectory()) {
      file = file.findChild("pom.xml");
      if (file == null) return null;
    }

    MavenProjectsManager manager = MavenActionUtil.getProjectsManager(dataContext);
    if (manager == null) return null;
    MavenProject mavenProject = manager.findProject(file);
    if (mavenProject == null) return null;

    return file;
  }
  private MavenRunnerParameters createBuildParameters(Location l) {
    final PsiElement element = l.getPsiElement();
    final Project project = l.getProject();

    final Module module = ModuleUtil.findModuleForPsiElement(element);
    if (module == null) return null;

    final MavenProjectsManager mavenProjectsManager = MavenProjectsManager.getInstance(project);
    final MavenProject mavenProject = mavenProjectsManager.findProject(module);

    if (mavenProject == null) return null;

    // todo: check this code
    final List<MavenArtifact> dependencies = mavenProject.getDependencies();
    MavenArtifact artifact = null;
    for (MavenArtifact dependence : dependencies) {
      if (dependence.getArtifactId().equals(GROUP_ID_LIFT)) {
        artifact = dependence;
        break;
      } else if (dependence.getArtifactId().equals(ARTIFACT_ID_LIFT)) {
        artifact = dependence;
        break;
      }
    }
    // final MavenArtifact artifact = mavenProjectModel.findDependency(GROUP_ID_LIFT,
    // ARTIFACT_ID_LIFT);

    if (artifact == null) return null;

    mySourceElement = element;

    MavenExplicitProfiles profiles =
        MavenProjectsManager.getInstance(project).getExplicitProfiles();
    List<String> goals = new ArrayList<String>();

    goals.add(JETTY_RUN);

    final VirtualFile file = module.getModuleFile();
    if (file == null) return null;

    final VirtualFile parent = file.getParent();
    if (parent == null) return null;

    return new MavenRunnerParameters(true, parent.getPath(), goals, profiles);
  }
  @Override
  public void actionPerformed(@NotNull AnActionEvent e) {
    final DataContext context = e.getDataContext();

    MavenProjectsManager projectsManager = MavenActionUtil.getProjectsManager(context);
    if (projectsManager == null) return;

    List<VirtualFile> selectedFiles = MavenActionUtil.getMavenProjectsFiles(context);
    List<VirtualFile> removableFiles = new ArrayList<>();

    for (VirtualFile pomXml : selectedFiles) {
      if (projectsManager.isManagedFile(pomXml)) {
        removableFiles.add(pomXml);
      } else {
        notifyUserIfNeeded(context, projectsManager, selectedFiles, pomXml);
      }
    }
    projectsManager.removeManagedFiles(removableFiles);
  }
  @NotNull
  public String[] getNames(Project project, boolean includeNonProjectItems) {
    List<String> result = new ArrayList<String>();

    for (MavenProject each : MavenProjectsManager.getInstance(project).getProjects()) {
      result.add(each.getMavenId().getArtifactId());
    }

    return ArrayUtil.toStringArray(result);
  }
Example #17
0
 @Override
 protected void tearDown() throws Exception {
   Messages.setTestDialog(TestDialog.DEFAULT);
   myProjectsManager.projectClosed();
   removeFromLocalRepository("test");
   if (useJps()) {
     CompilerTestUtil.disableExternalCompiler(myProject);
     FileUtil.delete(BuildManager.getInstance().getBuildSystemDirectory());
   }
   super.tearDown();
 }
Example #18
0
 @Override
 protected void setUpInWriteAction() throws Exception {
   super.setUpInWriteAction();
   myProjectsManager = MavenProjectsManager.getInstance(myProject);
   removeFromLocalRepository("test");
   if (useJps()) {
     CompilerTestUtil.enableExternalCompiler(myProject);
   } else {
     CompilerTestUtil.disableExternalCompiler(myProject);
   }
 }
Example #19
0
  protected MavenArtifactDownloader.DownloadResult downloadArtifacts(
      Collection<MavenProject> projects, List<MavenArtifact> artifacts) {
    final MavenArtifactDownloader.DownloadResult[] unresolved =
        new MavenArtifactDownloader.DownloadResult[1];

    AsyncResult<MavenArtifactDownloader.DownloadResult> result =
        new AsyncResult<MavenArtifactDownloader.DownloadResult>();
    result.doWhenDone(
        new Consumer<MavenArtifactDownloader.DownloadResult>() {
          @Override
          public void consume(MavenArtifactDownloader.DownloadResult unresolvedArtifacts) {
            unresolved[0] = unresolvedArtifacts;
          }
        });

    myProjectsManager.scheduleArtifactsDownloading(projects, artifacts, true, true, result);
    myProjectsManager.waitForArtifactsDownloadingCompletion();

    return unresolved[0];
  }
  public static boolean isFilteredResourceFile(PsiElement element) {
    PsiFile psiFile = element.getContainingFile();
    VirtualFile file = getVirtualFile(psiFile);
    if (file == null) return false;

    MavenProjectsManager manager = MavenProjectsManager.getInstance(psiFile.getProject());
    MavenProject mavenProject = manager.findContainingProject(file);
    if (mavenProject == null) return false;

    Set<VirtualFile> filteredRoots = getFilteredResourcesRoots(mavenProject);

    if (!filteredRoots.isEmpty()) {
      for (VirtualFile f = file.getParent(); f != null; f = f.getParent()) {
        if (filteredRoots.contains(f)) {
          return true;
        }
      }
    }

    return false;
  }
  @NotNull
  public NavigationItem[] getItemsByName(
      String name, String pattern, Project project, boolean includeNonProjectItems) {
    List<NavigationItem> result = new ArrayList<NavigationItem>();

    for (final MavenProject each : MavenProjectsManager.getInstance(project).getProjects()) {
      if (name.equals(each.getMavenId().getArtifactId())) {
        PsiFile psiFile = PsiManager.getInstance(project).findFile(each.getFile());
        if (psiFile != null) result.add(psiFile);
      }
    }

    return result.toArray(new NavigationItem[result.size()]);
  }
  public void testAddingExistingGeneratedSources3() throws Exception {
    createStdProjectFolders();

    MavenProjectsManager.getInstance(myProject)
        .getImportingSettings()
        .setGeneratedSourcesFolder(MavenImportingSettings.GeneratedSourcesFolder.SUBFOLDER);

    createProjectSubFile("target/generated-sources/com/A.java", "package com; class A {}");

    importProject(
        "<groupId>test</groupId>" + "<artifactId>project</artifactId>" + "<version>1</version>");

    assertSources("project", "src/main/java", "src/main/resources", "target/generated-sources/com");
  }
Example #23
0
  public static List<LookupElement> getPhaseVariants(MavenProjectsManager manager) {
    Set<String> goals = new HashSet<String>();
    goals.addAll(MavenConstants.PHASES);

    for (MavenProject mavenProject : manager.getProjects()) {
      for (MavenPlugin plugin : mavenProject.getPlugins()) {
        MavenPluginInfo pluginInfo =
            MavenArtifactUtil.readPluginInfo(manager.getLocalRepository(), plugin.getMavenId());
        if (pluginInfo != null) {
          for (MavenPluginInfo.Mojo mojo : pluginInfo.getMojos()) {
            goals.add(mojo.getDisplayName());
          }
        }
      }
    }

    List<LookupElement> res = new ArrayList<LookupElement>(goals.size());
    for (String goal : goals) {
      res.add(LookupElementBuilder.create(goal).withIcon(MavenIcons.Phase));
    }

    return res;
  }
  @Override
  public void initComponent() {
    if (!isNormalProject()) return;

    MavenProjectsManager.getInstance(myProject)
        .addProjectsTreeListener(
            new MavenProjectsTree.ListenerAdapter() {
              @Override
              public void projectsUpdated(
                  List<Pair<MavenProject, MavenProjectChanges>> updated,
                  List<MavenProject> deleted) {
                updateTabName(MavenUtil.collectFirsts(updated));
              }
            });
  }
 private void initOrderEntries() {
   for (OrderEntry e : myRootModel.getOrderEntries()) {
     if (e instanceof ModuleSourceOrderEntry || e instanceof JdkOrderEntry) continue;
     if (e instanceof LibraryOrderEntry) {
       if (!isMavenLibrary(((LibraryOrderEntry) e).getLibrary())) continue;
     }
     if (e instanceof ModuleOrderEntry) {
       Module m = ((ModuleOrderEntry) e).getModule();
       if (m != null
           && !MavenProjectsManager.getInstance(myRootModel.getProject()).isMavenizedModule(m))
         continue;
     }
     myRootModel.removeOrderEntry(e);
   }
 }
  @Nullable
  public static MavenDomProjectModel findParent(
      @NotNull 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;
  }
 private static void collectChildrenProjects(
     @NotNull final MavenDomProjectModel model, @NotNull Set<MavenDomProjectModel> 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);
       }
     }
   }
 }
    @Nullable
    public T process(@NotNull 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);
    }
  @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 = JarFileSystem.getInstance().getJarRootForLocalFile(pluginFile);
    if (pluginJarRoot == null) return null;
    return pluginJarRoot.findFileByRelativePath(MavenArtifactUtil.MAVEN_PLUGIN_DESCRIPTOR);
  }
  private static <T> boolean processSettingsXml(
      @Nullable MavenProject mavenProject,
      @NotNull Processor<T> processor,
      @NotNull Project project,
      Function<? super MavenDomProfile, T> 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;
  }