com.intellij.openapi.projectRoots.JavaSdk Java Examples

The following examples show how to use com.intellij.openapi.projectRoots.JavaSdk. 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: PantsSdkUtil.java    From intellij-pants-plugin with Apache License 2.0 6 votes vote down vote up
/**
 * @param pantsExecutable  path to the pants executable file for the
 *                         project. This function will return erroneous output if you use a directory path. The
 *                         pants executable can be found from a project path with
 *                         {@link com.twitter.intellij.pants.util.PantsUtil#findPantsExecutable(String)}.
 * @param parentDisposable Disposable object to use if a new JDK is added to
 *                         the project jdk table (otherwise null). Integration tests should use getTestRootDisposable() for
 *                         this argument to avoid exceptions during teardown.
 * @return The default Sdk object to use for the project at the given pants
 * executable path.
 * <p>
 * This method will add a JDK to the project JDK table if it needs to create
 * one, which mutates global state (protected by a read/write lock).
 */
public static Optional<Sdk> getDefaultJavaSdk(@NotNull final String pantsExecutable, @Nullable final Disposable parentDisposable) {
  Optional<Sdk> existingSdk = Arrays.stream(ProjectJdkTable.getInstance().getAllJdks())
    // If a JDK belongs to this particular `pantsExecutable`, then its name will contain the path to Pants.
    .filter(sdk -> sdk.getName().contains(pantsExecutable) && sdk.getSdkType() instanceof JavaSdk)
    .findFirst();

  if (existingSdk.isPresent()) {
    return existingSdk;
  }

  Optional<Sdk> pantsJdk = createPantsJdk(pantsExecutable);
  // Finally if we need to create a new JDK, it needs to be registered in the `ProjectJdkTable` on the IDE level
  // before it can be used.
  pantsJdk.ifPresent(jdk -> registerJdk(jdk, parentDisposable));
  return pantsJdk;
}
 
Example #2
Source File: CamelLightCodeInsightFixtureTestCaseIT.java    From camel-idea-plugin with Apache License 2.0 6 votes vote down vote up
@NotNull
@Override
protected LightProjectDescriptor getProjectDescriptor() {
    LanguageLevel languageLevel = LanguageLevel.JDK_1_8;
    return new DefaultLightProjectDescriptor() {
        @Override
        public Sdk getSdk() {
            String compilerOption = JpsJavaSdkType.complianceOption(languageLevel.toJavaVersion());
            return JavaSdk.getInstance().createJdk( "java " + compilerOption, BUILD_MOCK_JDK_DIRECTORY + compilerOption, false );
        }

        @Override
        public void configureModule(@NotNull Module module, @NotNull ModifiableRootModel model, @NotNull ContentEntry contentEntry) {
            model.getModuleExtension( LanguageLevelModuleExtension.class ).setLanguageLevel( languageLevel );
        }
    };
}
 
Example #3
Source File: CamelInspectionTestHelper.java    From camel-idea-plugin with Apache License 2.0 6 votes vote down vote up
@NotNull
@Override
protected LightProjectDescriptor getProjectDescriptor() {
    LanguageLevel languageLevel = LanguageLevel.JDK_1_8;
    return new DefaultLightProjectDescriptor() {
        @Override
        public Sdk getSdk() {
            String compilerOption = JpsJavaSdkType.complianceOption(languageLevel.toJavaVersion());
            return JavaSdk.getInstance().createJdk( "java " + compilerOption, BUILD_MOCK_JDK_DIRECTORY + compilerOption, false );
        }

        @Override
        public void configureModule(@NotNull Module module, @NotNull ModifiableRootModel model, @NotNull ContentEntry contentEntry) {
            model.getModuleExtension( LanguageLevelModuleExtension.class ).setLanguageLevel( languageLevel );
        }
    };
}
 
Example #4
Source File: Jdks.java    From intellij with Apache License 2.0 6 votes vote down vote up
@Nullable
private static String getJdkHomePath(LanguageLevel langLevel) {
  Collection<String> jdkHomePaths = new ArrayList<>(JavaSdk.getInstance().suggestHomePaths());
  if (jdkHomePaths.isEmpty()) {
    return null;
  }
  // prefer jdk path of getJavaHome(), since we have to allow access to it in tests
  // see AndroidProjectDataServiceTest#testImportData()
  final List<String> list = new ArrayList<>();
  String javaHome = SystemProperties.getJavaHome();

  if (javaHome != null && !javaHome.isEmpty()) {
    for (Iterator<String> it = jdkHomePaths.iterator(); it.hasNext(); ) {
      final String path = it.next();

      if (path != null && javaHome.startsWith(path)) {
        it.remove();
        list.add(path);
      }
    }
  }
  list.addAll(jdkHomePaths);
  return getBestJdkHomePath(list, langLevel);
}
 
Example #5
Source File: GodClassTest.java    From IntelliJDeodorant with MIT License 5 votes vote down vote up
@NotNull
@Override
protected LightProjectDescriptor getProjectDescriptor() {
    return new ProjectDescriptor(LanguageLevel.JDK_1_8, false) {
        @Override
        public Sdk getSdk() {
            return JavaSdk.getInstance().createJdk("java 1.8", MOCK_JDK_HOME, false);
        }
    };
}
 
Example #6
Source File: LombokTestUtil.java    From lombok-intellij-plugin with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public static LightProjectDescriptor getProjectDescriptor() {
  return new DefaultLightProjectDescriptor() {
    @Override
    public Sdk getSdk() {
      return JavaSdk.getInstance().createJdk("java 1.8", "lib/mockJDK-1.8", false);
    }

    @Override
    public void configureModule(@NotNull Module module, @NotNull ModifiableRootModel model, @NotNull ContentEntry contentEntry) {
      model.getModuleExtension(LanguageLevelModuleExtension.class).setLanguageLevel(LanguageLevel.JDK_1_8);
    }
  };
}
 
Example #7
Source File: JdksTest.java    From intellij with Apache License 2.0 5 votes vote down vote up
private void setJdks(List<Sdk> jdks) {
  List<Sdk> currentJdks =
      ReadAction.compute(
          () -> ProjectJdkTable.getInstance().getSdksOfType(JavaSdk.getInstance()));
  WriteAction.run(
      () -> {
        currentJdks.forEach(jdk -> ProjectJdkTable.getInstance().removeJdk(jdk));
        jdks.forEach(jdk -> ProjectJdkTable.getInstance().addJdk(jdk));
      });
}
 
Example #8
Source File: Jdks.java    From intellij with Apache License 2.0 5 votes vote down vote up
@Nullable
private static Sdk createJdk(String jdkHomePath) {
  Sdk jdk = SdkConfigurationUtil.createAndAddSDK(jdkHomePath, JavaSdk.getInstance());
  if (jdk == null) {
    logger.error(String.format("Unable to create JDK from path '%1$s'", jdkHomePath));
  }
  return jdk;
}
 
Example #9
Source File: Jdks.java    From intellij with Apache License 2.0 5 votes vote down vote up
private static JavaSdkVersion getVersion(String jdkRoot) {
  String version = JavaSdk.getInstance().getVersionString(jdkRoot);
  if (version == null) {
    return JavaSdkVersion.JDK_1_0;
  }
  JavaSdkVersion sdkVersion = JavaSdk.getInstance().getVersion(version);
  return sdkVersion == null ? JavaSdkVersion.JDK_1_0 : sdkVersion;
}
 
Example #10
Source File: Jdks.java    From intellij with Apache License 2.0 5 votes vote down vote up
@Nullable
private static String getBestJdk(List<String> jdkRoots, LanguageLevel langLevel) {
  return jdkRoots
      .stream()
      .filter(root -> JavaSdk.getInstance().isValidSdkHome(root))
      .filter(root -> getVersion(root).getMaxLanguageLevel().isAtLeast(langLevel))
      .min(Comparator.comparing(o -> getVersion(o).getMaxLanguageLevel()))
      .orElse(null);
}
 
Example #11
Source File: Jdks.java    From intellij with Apache License 2.0 5 votes vote down vote up
/**
 * Returns null if the SDK is not a java JDK, or doesn't have a recognized java langauge level.
 */
@Nullable
private static LanguageLevel getJavaLanguageLevel(Sdk sdk) {
  if (!(sdk.getSdkType() instanceof JavaSdk)) {
    return null;
  }
  JavaSdkVersion version = JavaSdk.getInstance().getVersion(sdk);
  return version != null ? version.getMaxLanguageLevel() : null;
}
 
Example #12
Source File: Jdks.java    From intellij with Apache License 2.0 5 votes vote down vote up
@Nullable
@VisibleForTesting
static Sdk findClosestMatch(LanguageLevel langLevel) {
  return ProjectJdkTable.getInstance().getSdksOfType(JavaSdk.getInstance()).stream()
      .filter(
          sdk -> {
            LanguageLevel level = getJavaLanguageLevel(sdk);
            return level != null && level.isAtLeast(langLevel);
          })
      .filter(Jdks::isValid)
      .min(Comparator.comparing(Jdks::getJavaLanguageLevel))
      .orElse(null);
}
 
Example #13
Source File: TypeStateCheckingTest.java    From IntelliJDeodorant with MIT License 5 votes vote down vote up
@NotNull
@Override
protected LightProjectDescriptor getProjectDescriptor() {
    return new ProjectDescriptor(LanguageLevel.JDK_1_8, false) {
        @Override
        public Sdk getSdk() {
            return JavaSdk.getInstance().createJdk("java 1.8", MOCK_JDK_HOME, false);
        }
    };
}
 
Example #14
Source File: Jdks.java    From intellij with Apache License 2.0 4 votes vote down vote up
private static Sdk getOrCreateSdk(String homePath) {
  return ProjectJdkTable.getInstance().getSdksOfType(JavaSdk.getInstance()).stream()
      .filter(jdk -> jdkPathMatches(jdk, homePath))
      .findFirst()
      .orElseGet(() -> createJdk(homePath));
}
 
Example #15
Source File: NutzBootModuleBuilder.java    From NutzCodeInsight with Apache License 2.0 4 votes vote down vote up
@Override
public boolean isSuitableSdkType(SdkTypeId sdkType) {
    return sdkType == JavaSdk.getInstance();
}
 
Example #16
Source File: SlingMavenModuleBuilder.java    From aem-ide-tooling-4-intellij with Apache License 2.0 4 votes vote down vote up
@Override
public boolean isSuitableSdkType(SdkTypeId sdk) {
    return sdk == JavaSdk.getInstance();
}
 
Example #17
Source File: RoboVmModuleBuilder.java    From robovm-idea with GNU General Public License v2.0 4 votes vote down vote up
@Override
public void setupRootModel(final ModifiableRootModel modifiableRootModel) throws ConfigurationException {
    // set the Java SDK
    myJdk = RoboVmPlugin.getSdk();
    if (myJdk == null || !robovmDir.isEmpty()) {
        myJdk = RoboVmSdkType.findBestJdk();
    }

    // set a project jdk if none is set
    ProjectRootManager manager = ProjectRootManager.getInstance(modifiableRootModel.getProject());
    if (manager.getProjectSdk() == null) {
        manager.setProjectSdk(RoboVmSdkType.findBestJdk());
    }

    if (buildSystem != BuildSystem.None) {
        // apply the template
        final Project project = modifiableRootModel.getProject();
        StartupManager.getInstance(project).runWhenProjectIsInitialized(new DumbAwareRunnable() {
            public void run() {
                DumbService.getInstance(project).smartInvokeLater(new Runnable() {
                    public void run() {
                        ApplicationManager.getApplication().runWriteAction(new Runnable() {
                            public void run() {
                                RoboVmModuleBuilder.this.applyTemplate(project);
                            }
                        });
                    }
                });
            }
        });

        // apply the build system
        StartupManager.getInstance(project).registerPostStartupActivity(new DumbAwareRunnable() {
            public void run() {
                DumbService.getInstance(project).smartInvokeLater(new Runnable() {
                    public void run() {
                        RoboVmModuleBuilder.this.applyBuildSystem(project);
                    }
                });
            }
        });
    } else {
        Sdk jdk = RoboVmSdkType.findBestJdk();
        LanguageLevel langLevel = ((JavaSdk) jdk.getSdkType()).getVersion(jdk).getMaxLanguageLevel();
        modifiableRootModel.getModuleExtension(LanguageLevelModuleExtension.class).setLanguageLevel(langLevel);
        super.setupRootModel(modifiableRootModel);

        final VirtualFile contentRoot = LocalFileSystem.getInstance()
                .findFileByIoFile(new File(modifiableRootModel.getProject().getBasePath()));
        applyTemplate(modifiableRootModel.getProject());
        contentRoot.refresh(false, true);
        for (ContentEntry entry : modifiableRootModel.getContentEntries()) {
            for (SourceFolder srcFolder : entry.getSourceFolders()) {
                entry.removeSourceFolder(srcFolder);
            }
            if (robovmDir.isEmpty()) {
                entry.addSourceFolder(contentRoot.findFileByRelativePath("/src/main/java"), false);
            }
            new File(entry.getFile().getCanonicalPath()).delete();
        }
    }
}
 
Example #18
Source File: OSSPantsIdeaPluginGoalIntegrationTest.java    From intellij-pants-plugin with Apache License 2.0 4 votes vote down vote up
public void testPantsIdeaPluginGoal() throws Throwable {
  assertEmpty(ModuleManager.getInstance(myProject).getModules());

  /**
   * Check whether Pants supports `idea-plugin` goal.
   */
  final GeneralCommandLine commandLinePantsGoals = PantsUtil.defaultCommandLine(getProjectFolder().getPath());
  commandLinePantsGoals.addParameter("goals");
  final ProcessOutput cmdOutputGoals = PantsUtil.getCmdOutput(commandLinePantsGoals.withWorkDirectory(getProjectFolder()), null);
  assertEquals(commandLinePantsGoals.toString() + " failed", 0, cmdOutputGoals.getExitCode());
  if (!cmdOutputGoals.getStdout().contains("idea-plugin")) {
    return;
  }

  /**
   * Generate idea project via `idea-plugin` goal.
   */
  final GeneralCommandLine commandLine = PantsUtil.defaultCommandLine(getProjectFolder().getPath());
  final File outputFile = FileUtil.createTempFile("project_dir_location", ".out");
  String targetToImport = "testprojects/tests/java/org/pantsbuild/testproject/matcher:matcher";
  commandLine.addParameters(
    "idea-plugin",
    "--no-open",
    "--output-file=" + outputFile.getPath(),
    targetToImport
  );
  final ProcessOutput cmdOutput = PantsUtil.getCmdOutput(commandLine.withWorkDirectory(getProjectFolder()), null);
  assertEquals(commandLine.toString() + " failed", 0, cmdOutput.getExitCode());
  // `outputFile` contains the path to the project directory.
  String projectDir = FileUtil.loadFile(outputFile);

  // Search the directory for ipr file.
  File[] files = new File(projectDir).listFiles();
  assertNotNull(files);
  Optional<String> iprFile = Arrays.stream(files)
    .map(File::getPath)
    .filter(s -> s.endsWith(ProjectFileType.DOT_DEFAULT_EXTENSION))
    .findFirst();
  assertTrue(iprFile.isPresent());

  myProject = ProjectUtil.openProject(iprFile.get(), myProject, false);
  // Invoke post startup activities.
  UIUtil.dispatchAllInvocationEvents();
  /**
   * Under unit test mode, {@link com.intellij.ide.impl.ProjectUtil#openProject} will force open a project in a new window,
   * so Project SDK has to be reset. In practice, this is not needed.
   */
  ApplicationManager.getApplication().runWriteAction(new Runnable() {
    @Override
    public void run() {
      final JavaSdk javaSdk = JavaSdk.getInstance();
      ProjectRootManager.getInstance(myProject).setProjectSdk(ProjectJdkTable.getInstance().getSdksOfType(javaSdk).iterator().next());
    }
  });

  assertSuccessfulTest(PantsUtil.getCanonicalModuleName(targetToImport), "org.pantsbuild.testproject.matcher.MatcherTest");
  assertTrue(ProjectUtil.closeAndDispose(myProject));
}
 
Example #19
Source File: DubboPluginModuleBuilder.java    From intellij-idea-plugin with Apache License 2.0 4 votes vote down vote up
@Override
public boolean isSuitableSdkType(SdkTypeId sdkType) {
    return sdkType == JavaSdk.getInstance();
}
 
Example #20
Source File: PantsSdkUtil.java    From intellij-pants-plugin with Apache License 2.0 4 votes vote down vote up
@NotNull
private static Sdk createJdk(String name, String home) {
  return JavaSdk.getInstance().createJdk(name, home, false);
}
 
Example #21
Source File: SneakyThrowsTest.java    From lombok-intellij-plugin with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
@Override
protected Sdk getProjectJDK() {
  return JavaSdk.getInstance().createJdk("java 1.8", "lib/mockJDK-1.8", false);
}