Java Code Examples for com.intellij.openapi.roots.ProjectRootManager#getInstance()

The following examples show how to use com.intellij.openapi.roots.ProjectRootManager#getInstance() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ProjectScopeBuilderImpl.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Nonnull
@Override
public GlobalSearchScope buildAllScope() {
  ProjectRootManager projectRootManager = myProject.isDefault() ? null : ProjectRootManager.getInstance(myProject);
  if (projectRootManager == null) {
    return new EverythingGlobalScope(myProject);
  }

  return new ProjectAndLibrariesScope(myProject) {
    @Override
    public boolean contains(@Nonnull VirtualFile file) {
      DirectoryInfo info = ((ProjectFileIndexImpl)myProjectFileIndex).getInfoForFileOrDirectory(file);
      return info.isInProject(file) && (info.getModule() != null || info.hasLibraryClassRoot() || info.isInLibrarySource(file));
    }
  };
}
 
Example 2
Source File: GlobalSearchScopeUtil.java    From attic-polygene-java with Apache License 2.0 6 votes vote down vote up
/**
 * Determine search scope given a psi element.
 *
 * @param psiElement context.
 * @return Search scope given psi class.
 * @since 0.1
 */
@Nullable
public static GlobalSearchScope determineSearchScope( @NotNull PsiElement psiElement )
{
    VirtualFile classVirtualFile = getVirtualFile( psiElement );
    if( classVirtualFile == null )
    {
        return null;
    }

    Module module = findModuleForPsiElement( psiElement );
    if( module == null )
    {
        return null;
    }

    Project project = psiElement.getProject();
    ProjectRootManager projectRootManager = ProjectRootManager.getInstance( project );
    boolean includeTestClasses = projectRootManager.getFileIndex().isInTestSourceContent( classVirtualFile );
    return module.getModuleWithDependenciesAndLibrariesScope( includeTestClasses );
}
 
Example 3
Source File: FileChangeTracker.java    From intellij-pants-plugin with Apache License 2.0 6 votes vote down vote up
private static ChangeType detectChangeType(Project project,final PantsOptions pantsOptions, @NotNull VirtualFile file) {
  ProjectRootManager rootManager = ProjectRootManager.getInstance(project);

  if (rootManager.getFileIndex().getContentRootForFile(file) != null) {
    boolean isBuildFile = PantsUtil.isBUILDFileName(file.getName());
    boolean isUnderPantsRepo = PantsUtil.isFileUnderPantsRepo(file);

    Path filePath = Paths.get(file.getPath());
    boolean shouldBeIgnored =
        pantsOptions.get(PantsConstants.PANTS_OPTION_PANTS_WORKDIR)
        .map(workdir -> filePath.startsWith(Paths.get(workdir).toAbsolutePath()))
        .orElse(filePath.toUri().toString().contains("/.pants.d/"));

    if (isUnderPantsRepo && isBuildFile && !shouldBeIgnored) {
      return ChangeType.BUILD;
    }

    return ChangeType.OTHER;
  }

  return ChangeType.UNRELATED;
}
 
Example 4
Source File: NewClassAction.java    From json2java4idea with Apache License 2.0 6 votes vote down vote up
@CheckReturnValue
@VisibleForTesting
@SuppressWarnings("WeakerAccess")
static boolean isAvailable(@Nonnull AnActionEvent event) {
    final Project project = event.getProject();
    if (project == null) {
        return false;
    }

    final IdeView view = event.getData(LangDataKeys.IDE_VIEW);
    if (view == null) {
        return false;
    }

    final ProjectRootManager rootManager = ProjectRootManager.getInstance(project);
    final ProjectFileIndex fileIndex = rootManager.getFileIndex();
    final Optional<PsiDirectory> sourceDirectory = Stream.of(view.getDirectories())
            .filter(directory -> {
                final VirtualFile virtualFile = directory.getVirtualFile();
                return fileIndex.isUnderSourceRootOfType(virtualFile, JavaModuleSourceRootTypes.SOURCES);
            })
            .findFirst();
    return sourceDirectory.isPresent();
}
 
Example 5
Source File: OSSSdkRefreshActionTest.java    From intellij-pants-plugin with Apache License 2.0 5 votes vote down vote up
public void testRefreshPantsSdk() {
  ProjectRootManager rootManager = ProjectRootManager.getInstance(myProject);

  Sdk sdk = createDummySdk("1.8_from_" + pantsExecutable());
  String originalSdkPath = sdk.getHomePath();

  doImport("examples/src/java/org/pantsbuild/example/hello");
  assertEquals(originalSdkPath, rootManager.getProjectSdk().getHomePath());

  refreshProjectSdk();

  // the SDK gets updated
  assertSame(sdk, rootManager.getProjectSdk());
  assertNotEquals(originalSdkPath, sdk.getHomePath());
}
 
Example 6
Source File: BaseProjectViewDirectoryHelper.java    From consulo with Apache License 2.0 5 votes vote down vote up
public static List<VirtualFile> getTopLevelRoots(Project project) {
  List<VirtualFile> topLevelContentRoots = new ArrayList<>();
  ProjectRootManager prm = ProjectRootManager.getInstance(project);
  ProjectFileIndex index = prm.getFileIndex();

  for (VirtualFile root : prm.getContentRoots()) {
    VirtualFile parent = root.getParent();
    if (parent == null || !index.isInContent(parent)) {
      topLevelContentRoots.add(root);
    }
  }
  return topLevelContentRoots;
}
 
Example 7
Source File: TodoTreeHelper.java    From consulo with Apache License 2.0 5 votes vote down vote up
private static void addPackagesToChildren0(Project project, ArrayList<AbstractTreeNode> children, Module module, TodoTreeBuilder builder) {
  final List<VirtualFile> roots = new ArrayList<VirtualFile>();
  final List<VirtualFile> sourceRoots = new ArrayList<VirtualFile>();
  final PsiManager psiManager = PsiManager.getInstance(project);
  if (module == null) {
    final ProjectRootManager projectRootManager = ProjectRootManager.getInstance(project);
    ContainerUtil.addAll(roots, projectRootManager.getContentRoots());
    ContainerUtil.addAll(sourceRoots, projectRootManager.getContentSourceRoots());
  }
  else {
    ModuleRootManager moduleRootManager = ModuleRootManager.getInstance(module);
    ContainerUtil.addAll(roots, moduleRootManager.getContentRoots());
    ContainerUtil.addAll(sourceRoots, moduleRootManager.getContentFolderFiles(ContentFolderScopes.productionAndTest()));
  }
  roots.removeAll(sourceRoots);
  for (VirtualFile dir : roots) {
    final PsiDirectory directory = psiManager.findDirectory(dir);
    if (directory == null) {
      continue;
    }
    final Iterator<PsiFile> files = builder.getFiles(directory);
    if (!files.hasNext()) continue;
    TodoDirNode dirNode = new TodoDirNode(project, directory, builder);
    if (!children.contains(dirNode)) {
      children.add(dirNode);
    }
  }
}
 
Example 8
Source File: ProjectScopeBuilderImpl.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nonnull
@Override
public GlobalSearchScope buildProjectScope() {
  final ProjectRootManager projectRootManager = ProjectRootManager.getInstance(myProject);
  if (projectRootManager == null) {
    return new EverythingGlobalScope(myProject) {
      @Override
      public boolean isSearchInLibraries() {
        return false;
      }
    };
  }
  return new ProjectScopeImpl(myProject, FileIndexFacade.getInstance(myProject));
}
 
Example 9
Source File: HaxelibSdkUtils.java    From intellij-haxe with Apache License 2.0 5 votes vote down vote up
/**
 * Lookup the project's SDK.
 *
 * @param project to look up the SDK for.
 * @return the SDK instance, or DefaultSDK if the name of the selected SDK does not correspond
 * to any existing SDK instance.
 */
@NotNull
public static Sdk lookupSdk(@NotNull Project project) {
  ProjectRootManager mgr = ProjectRootManager.getInstance(project);
  Sdk sdk = null != mgr ? mgr.getProjectSdk() : null;
  if (null == sdk) {
    // TODO: Move error string to a resource in HaxeBundle.
    sdk = getDefaultSDK("Invalid (or no) SDK specified for project " + project.getName());
  }
  return sdk;
}
 
Example 10
Source File: OSSSdkRefreshActionTest.java    From intellij-pants-plugin with Apache License 2.0 5 votes vote down vote up
public void testRefreshNonPantsSdk() {
  String customJdkName = "Custom-JDK";

  try {
    Application application = ApplicationManager.getApplication();
    ProjectRootManager rootManager = ProjectRootManager.getInstance(myProject);

    Sdk customSdk = createDummySdk(customJdkName);

    doImport("examples/src/java/org/pantsbuild/example/hello");

    // set custom SDK
    application.runWriteAction(() -> {
      NewProjectUtil.applyJdkToProject(myProject, customSdk);
    });
    assertEquals(customJdkName, rootManager.getProjectSdk().getName());

    refreshProjectSdk();

    // refreshing changes the project SDK
    Sdk pantsSdk = rootManager.getProjectSdk();
    assertNotSame(customSdk, pantsSdk);

    // previously used custom SDK is not removed
    HashSet<Sdk> jdks = Sets.newHashSet(ProjectJdkTable.getInstance().getAllJdks());
    assertContainsElements(jdks, customSdk, pantsSdk);
  }
  finally {
    removeJdks(jdk -> jdk.getName().equals(customJdkName));
  }
}
 
Example 11
Source File: PantsProjectCache.java    From intellij-pants-plugin with Apache License 2.0 5 votes vote down vote up
@NotNull
private TreeSet<VirtualFile> collectRoots() {
  final TreeSet<VirtualFile> result = new TreeSet<>(VIRTUAL_FILE_COMPARATOR);
  final ProjectRootManager rootManager = ProjectRootManager.getInstance(myProject);
  result.addAll(rootManager.getModuleSourceRoots(ContainerUtil.set(JavaSourceRootType.SOURCE, JavaSourceRootType.TEST_SOURCE)));
  return result;
}
 
Example 12
Source File: AwesomeLinkFilter.java    From intellij-awesome-console with MIT License 5 votes vote down vote up
public AwesomeLinkFilter(final Project project) {
	this.project = project;
	this.fileCache = new HashMap<>();
	this.fileBaseCache = new HashMap<>();
	projectRootManager = ProjectRootManager.getInstance(project);
	srcRoots = getSourceRoots();
	config = AwesomeConsoleConfig.getInstance();
	fileMatcher = FILE_PATTERN.matcher("");
	urlMatcher = URL_PATTERN.matcher("");

	createFileCache();
}
 
Example 13
Source File: TomcatRunConfiguration.java    From SmartTomcat with Apache License 2.0 5 votes vote down vote up
@Override
public void onNewConfigurationCreated() {
    super.onNewConfigurationCreated();

    try {
        Project project = getProject();

        ProjectRootManager rootManager = ProjectRootManager.getInstance(project);
        VirtualFile[] sourceRoots = rootManager.getContentSourceRoots();

        Optional<VirtualFile> webinfFile = Stream.of(sourceRoots).map(VirtualFile::getParent).distinct().flatMap(f ->
                Stream.of(f.getChildren()).filter(c -> {
                    Path path = Paths.get(c.getCanonicalPath(), "WEB-INF");
                    return path.toFile().exists();
                })).distinct().findFirst();


        if (webinfFile.isPresent()) {
            VirtualFile file = webinfFile.get();
            docBase = file.getCanonicalPath();
            moduleName = ModuleUtil.findModuleForFile(file, project).getName();
            contextPath = "/" + moduleName;
        }
    } catch (Exception e) {
        //do nothing.
    }

}
 
Example 14
Source File: ProjectFileIndexFacade.java    From consulo with Apache License 2.0 4 votes vote down vote up
@Nonnull
@Override
public ModificationTracker getRootModificationTracker() {
  return ProjectRootManager.getInstance(myProject);
}
 
Example 15
Source File: RecursionDlg.java    From consulo with Apache License 2.0 4 votes vote down vote up
private void setupControls() {
  setTitle("Update Copyright");

  setOKButtonText("Run");

  ButtonGroup group = new ButtonGroup();
  group.add(rbFile);
  group.add(rbAll);

  rbFile.setMnemonic('F');
  rbAll.setMnemonic('A');
  cbSubdirs.setMnemonic('I');

  if (file.isDirectory()) {
    rbFile.setText("File");
    rbFile.setEnabled(false);
    rbAll.setText("All files in " + file.getPresentableUrl());
    rbAll.setSelected(true);
    cbSubdirs.setSelected(true);
    cbSubdirs.setEnabled(true);
  }
  else {
    VirtualFile parent = file.getParent();
    rbFile.setText("File '" + file.getPresentableUrl() + '\'');
    rbFile.setSelected(true);
    if (parent != null) {
      rbAll.setText("All files in " + parent.getPresentableUrl());
      cbSubdirs.setSelected(true);
      cbSubdirs.setEnabled(false);
    }
    else {
      rbAll.setVisible(false);
      cbSubdirs.setVisible(false);
    }
  }

  VirtualFile check = file;
  if (!file.isDirectory()) {
    check = file.getParent();
  }
  ProjectRootManager prm = ProjectRootManager.getInstance(project);
  ProjectFileIndex pfi = prm.getFileIndex();

  VirtualFile[] children = check != null ? check.getChildren() : VirtualFile.EMPTY_ARRAY;
  boolean hasSubdirs = false;
  for (int i = 0; i < children.length && !hasSubdirs; i++) {
    if (children[i].isDirectory() && !pfi.isExcluded(children[i])) {
      hasSubdirs = true;
    }
  }

  cbSubdirs.setVisible(hasSubdirs);
  if (!hasSubdirs) {
    cbSubdirs.setEnabled(false);
    mainPanel.remove(cbSubdirs);
  }

  ActionListener listener = new ActionListener() {
    public void actionPerformed(ActionEvent e) {
      if (cbSubdirs.isVisible()) {
        cbSubdirs.setEnabled(rbAll.isSelected());
      }
    }
  };

  rbFile.addActionListener(listener);
  rbAll.addActionListener(listener);
}
 
Example 16
Source File: WeaveRunnerCommandLine.java    From mule-intellij-plugins with Apache License 2.0 4 votes vote down vote up
@Override
protected JavaParameters createJavaParameters() throws ExecutionException
{
    final JavaParameters javaParams = new JavaParameters();
    // Use the same JDK as the project
    final Project project = this.model.getProject();
    final ProjectRootManager manager = ProjectRootManager.getInstance(project);
    javaParams.setJdk(manager.getProjectSdk());
    // All modules to use the same things
    final Module[] modules = ModuleManager.getInstance(project).getModules();
    if (modules.length > 0)
    {
        for (Module module : modules)
        {
            javaParams.configureByModule(module, JavaParameters.JDK_AND_CLASSES);
        }
    }

    final String weaveHome = model.getWeaveHome();
    if (StringUtils.isNotBlank(weaveHome))
    {
        final List<File> urLs = WeaveSdk.getJars(weaveHome);
        for (File jar : urLs)
        {
            javaParams.getClassPath().add(jar);
        }
    }
    //Mule main class
    javaParams.setMainClass(MAIN_CLASS);

    //Add default vm parameters
    javaParams.getVMParametersList().add("-Xms1024m");
    javaParams.getVMParametersList().add("-Xmx1024m");
    javaParams.getVMParametersList().add("-XX:PermSize=256m");
    javaParams.getVMParametersList().add("-XX:MaxPermSize=256m");
    javaParams.getVMParametersList().add("-XX:+HeapDumpOnOutOfMemoryError");
    javaParams.getVMParametersList().add("-XX:+AlwaysPreTouch");
    javaParams.getVMParametersList().add("-XX:NewSize=512m");
    javaParams.getVMParametersList().add("-XX:MaxNewSize=512m");
    javaParams.getVMParametersList().add("-XX:MaxTenuringThreshold=8");

    final List<WeaveInput> weaveInputs = model.getWeaveInputs();
    for (WeaveInput weaveInput : weaveInputs)
    {
        javaParams.getProgramParametersList().add("-input");
        javaParams.getProgramParametersList().add(weaveInput.getName());
        javaParams.getProgramParametersList().add(weaveInput.getPath());
    }

    if (isDebug)
    {
        javaParams.getVMParametersList().add("-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=5005");
        javaParams.getProgramParametersList().add("-debug");
    }

    if (!StringUtils.isBlank(model.getWeaveOutput()))
    {
        javaParams.getProgramParametersList().add("-output", model.getWeaveOutput());
    }

    javaParams.getProgramParametersList().add(model.getWeaveFile());

    // All done, run it
    return javaParams;
}
 
Example 17
Source File: MuleRunnerCommandLineState.java    From mule-intellij-plugins with Apache License 2.0 4 votes vote down vote up
@Override
    public JavaParameters createJavaParameters() throws ExecutionException {
        JavaParameters javaParams = new JavaParameters();
        // Use the same JDK as the project
        Project project = this.model.getProject();
        ProjectRootManager manager = ProjectRootManager.getInstance(project);
        javaParams.setJdk(manager.getProjectSdk());
        // All modules to use the same things
//        Module[] modules = ModuleManager.getInstance(project).getModules();
//        if (modules.length > 0) {
//            for (Module module : modules) {
//                javaParams.configureByModule(module, JavaParameters.JDK_AND_CLASSES);
//            }
//        }

        final String muleHome = model.getMuleHome();
        final MuleClassPath muleClassPath = new MuleClassPath(new File(muleHome));
        final List<File> urLs = muleClassPath.getJars();
        for (File jar : urLs) {
            javaParams.getClassPath().add(jar);
        }
        //EE license location 
        javaParams.getClassPath().add(muleHome + "/conf");
        
        //Mule main class
        javaParams.setMainClass(MAIN_CLASS);

        //Add default vm parameters
        javaParams.getVMParametersList().add("-Dmule.home=" + muleHome);
        javaParams.getVMParametersList().add("-Dmule.base=" + muleHome);
        javaParams.getVMParametersList().add("-Dmule.testingMode=true");
        javaParams.getVMParametersList().add("-Djava.net.preferIPv4Stack=TRUE ");
        javaParams.getVMParametersList().add("-Dmvel2.disable.jit=TRUE");
        javaParams.getVMParametersList().add("-Dorg.glassfish.grizzly.nio.transport.TCPNIOTransport.max-receive-buffer-size=1048576");
        javaParams.getVMParametersList().add("-Dorg.glassfish.grizzly.nio.transport.TCPNIOTransport.max-send-buffer-size=1048576");
        javaParams.getVMParametersList().add("-Djava.endorsed.dirs=" + muleHome + "/lib/endorsed ");
        javaParams.getVMParametersList().add("-Djava.util.logging.manager=org.apache.logging.log4j.jul.LogManager");
        javaParams.getVMParametersList().add("-Dmule.forceConsoleLog=true");

        if (isDebug) {
            javaParams.getVMParametersList().add("-Dmule.debug.enable=true");
            javaParams.getVMParametersList().add("-Dmule.debug.suspend=true");
        }

        javaParams.getVMParametersList().add("-Xms1024m");
        javaParams.getVMParametersList().add("-Xmx1024m");
        javaParams.getVMParametersList().add("-XX:PermSize=256m");
        javaParams.getVMParametersList().add("-XX:MaxPermSize=256m");
        javaParams.getVMParametersList().add("-XX:+HeapDumpOnOutOfMemoryError");
        javaParams.getVMParametersList().add("-XX:+AlwaysPreTouch");
        javaParams.getVMParametersList().add("-XX:NewSize=512m");
        javaParams.getVMParametersList().add("-XX:MaxNewSize=512m");
        javaParams.getVMParametersList().add("-XX:MaxTenuringThreshold=8");


        // VM Args
        String vmArgs = this.getVmArgs();
        if (vmArgs != null) {
            javaParams.getVMParametersList().addParametersString(vmArgs);
        }

        // All done, run it
        return javaParams;
    }
 
Example 18
Source File: DirectoryNode.java    From consulo with Apache License 2.0 4 votes vote down vote up
public DirectoryNode(VirtualFile aDirectory,
                     Project project,
                     boolean compactPackages,
                     boolean showFQName,
                     VirtualFile baseDir, final VirtualFile[] contentRoots) {
  super(project);
  myVDirectory = aDirectory;
  final ProjectRootManager projectRootManager = ProjectRootManager.getInstance(project);
  final ProjectFileIndex index = projectRootManager.getFileIndex();
  String dirName = aDirectory.getName();
  if (showFQName) {
    final VirtualFile contentRoot = index.getContentRootForFile(myVDirectory);
    if (contentRoot != null) {
      if (Comparing.equal(myVDirectory, contentRoot)) {
        myFQName = dirName;
      }
      else {
        final VirtualFile sourceRoot = index.getSourceRootForFile(myVDirectory);
        if (Comparing.equal(myVDirectory, sourceRoot)) {
          myFQName = VfsUtilCore.getRelativePath(myVDirectory, contentRoot, '/');
        }
        else if (sourceRoot != null) {
          myFQName = VfsUtilCore.getRelativePath(myVDirectory, sourceRoot, '/');
        }
        else {
          myFQName = VfsUtilCore.getRelativePath(myVDirectory, contentRoot, '/');
        }
      }

      if (contentRoots.length > 1 && ProjectRootsUtil.isModuleContentRoot(myVDirectory, project)) {
        myFQName = getContentRootName(baseDir, myFQName);
      }
    }
    else {
      myFQName = FilePatternPackageSet.getLibRelativePath(myVDirectory, index);
    }
    dirName = myFQName;
  } else {
    if (contentRoots.length > 1 && ProjectRootsUtil.isModuleContentRoot(myVDirectory, project)) {
      dirName = getContentRootName(baseDir, dirName);
    }
  }
  myDirName = dirName;
  myCompactPackages = compactPackages;
}
 
Example 19
Source File: AppCommandLineState.java    From SmartTomcat with Apache License 2.0 2 votes vote down vote up
@Override
protected JavaParameters createJavaParameters() {
    try {

        Path tomcatInstallationPath = Paths.get(configuration.getTomcatInfo().getPath());
        String moduleRoot = configuration.getModuleName();
        String contextPath = configuration.getContextPath();
        String tomcatVersion = configuration.getTomcatInfo().getVersion();
        String vmOptions = configuration.getVmOptions();
        Map<String, String> envOptions = configuration.getEnvOptions();

        Project project = this.configuration.getProject();

        JavaParameters javaParams = new JavaParameters();


        ProjectRootManager manager = ProjectRootManager.getInstance(project);
        javaParams.setJdk(manager.getProjectSdk());

        javaParams.setDefaultCharset(project);

        javaParams.setMainClass(TOMCAT_MAIN_CLASS);
        javaParams.getProgramParametersList().add("start");
        addBinFolder(tomcatInstallationPath, javaParams);
        addLibFolder(tomcatInstallationPath, javaParams);

        File file = new File(configuration.getDocBase());
        VirtualFile fileByIoFile = LocalFileSystem.getInstance().findFileByIoFile(file);
        Module module = ModuleUtilCore.findModuleForFile(fileByIoFile, configuration.getProject());


        if (module == null) {
            throw new ExecutionException("The Module Root specified is not a module according to Intellij");
        }

        String userHome = System.getProperty("user.home");
        Path workPath = Paths.get(userHome, ".SmartTomcat", project.getName(), module.getName());
        Path confPath = workPath.resolve("conf");
        if (!confPath.toFile().exists()) {
            confPath.toFile().mkdirs();
        }


        FileUtil.copyFileOrDir(tomcatInstallationPath.resolve("conf").toFile(), confPath.toFile());

        javaParams.setWorkingDirectory(workPath.toFile());


        updateServerConf(tomcatVersion, module, confPath, contextPath, configuration);


        javaParams.setPassParentEnvs(configuration.getPassParentEnvironmentVariables());
        if (envOptions != null) {
            javaParams.setEnv(envOptions);
        }
        javaParams.getVMParametersList().addParametersString(vmOptions);
        return javaParams;

    } catch (Exception e) {
        throw new RuntimeException(e.getMessage(), e);
    }


}