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());
  }
  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);
  }
Exemplo n.º 3
0
 @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);
 }
  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();
  }
  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);
  }
Exemplo n.º 6
0
  @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);
  }
  @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);
  }
Exemplo n.º 8
0
 @Override
 protected void setUpInWriteAction() throws Exception {
   super.setUpInWriteAction();
   myProjectsManager = MavenProjectsManager.getInstance(myProject);
   removeFromLocalRepository("test");
   if (useJps()) {
     CompilerTestUtil.enableExternalCompiler(myProject);
   } else {
     CompilerTestUtil.disableExternalCompiler(myProject);
   }
 }
    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()));
      }
    }
  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");
  }
  @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()]);
  }
  @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);
   }
 }
  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;
  }
Exemplo n.º 15
0
  @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;
  }
  @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);
       }
     }
   }
 }
  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);
                      }
                    });
          }
        });
  }
  @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;
  }
Exemplo n.º 21
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;
  }
  public static void processChildrenRecursively(
      @Nullable MavenDomProjectModel model,
      @NotNull Processor<MavenDomProjectModel> processor,
      @NotNull Project project,
      @NotNull Set<MavenDomProjectModel> 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);
        }
      }
    }
  }
  /**
   * @param project
   * @param parameters
   * @param coreSettings
   * @param runnerSettings
   * @param runConfiguration used to creation fix if maven home not found
   * @return
   * @throws ExecutionException
   */
  public static JavaParameters createJavaParameters(
      @Nullable final Project project,
      @NotNull final MavenRunnerParameters parameters,
      @Nullable MavenGeneralSettings coreSettings,
      @Nullable MavenRunnerSettings runnerSettings,
      @Nullable MavenRunConfiguration runConfiguration)
      throws ExecutionException {
    final JavaParameters params = new JavaParameters();

    ApplicationManager.getApplication().assertReadAccessAllowed();

    if (coreSettings == null) {
      coreSettings =
          project == null
              ? new MavenGeneralSettings()
              : MavenProjectsManager.getInstance(project).getGeneralSettings();
    }
    if (runnerSettings == null) {
      runnerSettings =
          project == null ? new MavenRunnerSettings() : MavenRunner.getInstance(project).getState();
    }

    params.setWorkingDirectory(parameters.getWorkingDirFile());

    params.setJdk(
        getJdk(
            project,
            runnerSettings,
            project != null && MavenRunner.getInstance(project).getState() == runnerSettings));

    final String mavenHome = resolveMavenHome(coreSettings, project, runConfiguration);

    addVMParameters(params.getVMParametersList(), mavenHome, runnerSettings);

    File confFile = MavenUtil.getMavenConfFile(new File(mavenHome));
    if (!confFile.isFile()) {
      throw new ExecutionException(
          "Configuration file is not exists in maven home: " + confFile.getAbsolutePath());
    }

    if (project != null && parameters.isResolveToWorkspace()) {
      try {
        String resolverJar = getArtifactResolverJar(MavenUtil.isMaven3(mavenHome));
        confFile = patchConfFile(confFile, resolverJar);

        File modulesPathsFile = dumpModulesPaths(project);
        params
            .getVMParametersList()
            .addProperty(MavenModuleMap.PATHS_FILE_PROPERTY, modulesPathsFile.getAbsolutePath());
      } catch (IOException e) {
        LOG.error(e);
        throw new ExecutionException("Failed to run maven configuration", e);
      }
    }

    params.getVMParametersList().addProperty("classworlds.conf", confFile.getPath());

    for (String path : getMavenClasspathEntries(mavenHome)) {
      params.getClassPath().add(path);
    }

    params.setMainClass(MAVEN_LAUNCHER_CLASS);
    EncodingManager encodingManager =
        project == null
            ? EncodingProjectManager.getInstance()
            : EncodingProjectManager.getInstance(project);
    params.setCharset(encodingManager.getDefaultCharset());

    addMavenParameters(
        params.getProgramParametersList(), mavenHome, coreSettings, runnerSettings, parameters);

    return params;
  }