com.intellij.openapi.projectRoots.ProjectJdkTable Java Examples

The following examples show how to use com.intellij.openapi.projectRoots.ProjectJdkTable. 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: SdkUtil.java    From intellij with Apache License 2.0 6 votes vote down vote up
/**
 * Check if sdk is not null and have path to expected files (android.jar and res/). If it does not
 * have expected content, this sdk will be removed from jdktable.
 *
 * @param sdk sdk to check
 * @return true if sdk is valid
 */
public static boolean checkSdkAndRemoveIfInvalid(@Nullable Sdk sdk) {
  if (sdk == null) {
    return false;
  } else if (containsJarAndRes(sdk)) {
    return true;
  } else {
    ProjectJdkTable jdkTable = ProjectJdkTable.getInstance();
    logger.info(
        String.format(
            "Some classes of Sdk %s is missing. Trying to remove and reinstall it.",
            sdk.getName()));
    EventLoggingService.getInstance().logEvent(SdkUtil.class, "Invalid SDK");

    Application application = ApplicationManager.getApplication();
    if (application.isDispatchThread()) {
      WriteAction.run(() -> jdkTable.removeJdk(sdk));
    } else {
      UIUtil.invokeAndWaitIfNeeded(
          (Runnable) () -> WriteAction.run(() -> jdkTable.removeJdk(sdk)));
    }
    return false;
  }
}
 
Example #3
Source File: PantsUtilTest.java    From intellij-pants-plugin with Apache License 2.0 6 votes vote down vote up
public void testFindJdk() {
  final File executable = PantsUtil.findPantsExecutable(getProjectFolder()).get();
  assertEquals(Lists.newArrayList(), getAllJdks().collect(Collectors.toList()));

  final Sdk sdkA = getDefaultJavaSdk(executable.getPath()).get();
  assertEquals(Lists.newArrayList(sdkA), getSameJdks(sdkA));

  final List<Sdk> singleSdkInTable = getSameJdks(sdkA);
  assertTrue(singleSdkInTable.get(0).getName().contains("pants"));

  final List<Sdk> twoEntriesSameSdk = Lists.newArrayList(sdkA, sdkA);
  // manually adding the same jdk to the table should result in two identical
  // entries
  ApplicationManager.getApplication().runWriteAction(() -> {
    // no need to use disposable here, because this should not add a new jdk
    ProjectJdkTable.getInstance().addJdk(sdkA);
  });
  assertEquals(twoEntriesSameSdk, getSameJdks(sdkA));

  // calling getDefaultJavaSdk should only add a new entry to the table if it
  // needs to make one
  final Sdk sdkB = getDefaultJavaSdk(executable.getPath()).get();
  // Make sure they are identical, meaning that no new JDK was created on the 2nd find.
  assertTrue(sdkA == sdkB);
  assertEquals(twoEntriesSameSdk, getSameJdks(sdkA));
}
 
Example #4
Source File: BlazeIntegrationTestCase.java    From intellij with Apache License 2.0 6 votes vote down vote up
@After
public final void tearDown() throws Exception {
  if (!isLightTestCase()) {
    // Workaround to avoid a platform race condition that occurs when we delete a VirtualDirectory
    // whose children were affected by external file system events that RefreshQueue is still
    // processing. We only need this for heavy test cases, since light test cases perform all file
    // operations synchronously through an in-memory file system.
    // See https://youtrack.jetbrains.com/issue/IDEA-218773
    RefreshSession refreshSession = RefreshQueue.getInstance().createSession(false, true, null);
    refreshSession.addFile(fileSystem.findFile(workspaceRoot.directory().getPath()));
    refreshSession.launch();
  }
  SyncCache.getInstance(getProject()).clear();
  runWriteAction(
      () -> {
        ProjectJdkTable table = ProjectJdkTable.getInstance();
        for (Sdk sdk : ProjectJdkTable.getInstance().getAllJdks()) {
          table.removeJdk(sdk);
        }
      });
  testFixture.tearDown();
  testFixture = null;
}
 
Example #5
Source File: BlazeIntellijPluginConfiguration.java    From intellij with Apache License 2.0 6 votes vote down vote up
@Override
public void readExternal(Element element) throws InvalidDataException {
  super.readExternal(element);
  // Target is persisted as a tag to permit multiple targets in the future.
  Element targetElement = element.getChild(TARGET_TAG);
  if (targetElement != null && !Strings.isNullOrEmpty(targetElement.getTextTrim())) {
    target = (Label) TargetExpression.fromStringSafe(targetElement.getTextTrim());
  } else {
    target = null;
  }
  blazeFlags.readExternal(element);
  exeFlags.readExternal(element);

  String sdkName = element.getAttributeValue(SDK_ATTR);
  if (!Strings.isNullOrEmpty(sdkName)) {
    pluginSdk = ProjectJdkTable.getInstance().findJdk(sdkName);
  }
  vmParameters = Strings.emptyToNull(element.getAttributeValue(VM_PARAMS_ATTR));
  programParameters = Strings.emptyToNull(element.getAttributeValue(PROGRAM_PARAMS_ATTR));

  String keepInSyncString = element.getAttributeValue(KEEP_IN_SYNC_TAG);
  keepInSync = keepInSyncString != null ? Boolean.parseBoolean(keepInSyncString) : null;
}
 
Example #6
Source File: AddPythonFacetQuickFix.java    From intellij-pants-plugin with Apache License 2.0 6 votes vote down vote up
@Nullable
private Sdk resolveSdk(Project project, PsiFile file) {
  final AtomicReference<Sdk> pythonSdk = new AtomicReference<>();
  final ProjectJdkTable jdkTable = ProjectJdkTable.getInstance();
  List<Sdk> sdks = jdkTable.getSdksOfType(PythonSdkType.getInstance());

  if (sdks.isEmpty()) {
    final Module module = ModuleUtil.findModuleForPsiElement(file);
    PyAddSdkDialog.show(project, module, sdks, pythonSdk::set);
    if (pythonSdk.get() != null) {
      ApplicationManager.getApplication().runWriteAction(() -> {
        jdkTable.addJdk(pythonSdk.get());
      });
    }

    return pythonSdk.get();
  }
  else {
    return sdks.get(0);
  }
}
 
Example #7
Source File: RoboVmPlugin.java    From robovm-idea with GNU General Public License v2.0 5 votes vote down vote up
public static boolean isAndroidSdkSetup() {
    for (Sdk sdk : ProjectJdkTable.getInstance().getAllJdks()) {
        if (sdk.getSdkType().getName().equals("Android SDK")) {
            return true;
        }
    }
    return false;
}
 
Example #8
Source File: PantsSdkUtil.java    From intellij-pants-plugin with Apache License 2.0 5 votes vote down vote up
private static void registerJdk(Sdk jdk, Disposable disposable) {
  ApplicationManager.getApplication().invokeAndWait(() -> {
    ApplicationManager.getApplication().runWriteAction(() -> {
      if (disposable == null) {
        ProjectJdkTable.getInstance().addJdk(jdk);
      }
      else {
        ProjectJdkTable.getInstance().addJdk(jdk, disposable);
      }
    });
  });
}
 
Example #9
Source File: PantsSdkUtil.java    From intellij-pants-plugin with Apache License 2.0 5 votes vote down vote up
private static void updateJdk(Sdk original, Sdk modified) {
  ApplicationManager.getApplication().invokeAndWait(() -> {
    ApplicationManager.getApplication().runWriteAction(() -> {
      ProjectJdkTable.getInstance().updateJdk(original, modified);
    });
  });
}
 
Example #10
Source File: AddPythonFacetQuickFixTest.java    From intellij-pants-plugin with Apache License 2.0 5 votes vote down vote up
private void injectFakePythonSdk() {
  // Create Sdk in order not to invoke the interpreter choosing modal
  Sdk sdk = new PyDetectedSdk("FakeSdk");
  ApplicationManager.getApplication().runWriteAction(() -> {
    final ProjectJdkTable jdkTable = ProjectJdkTable.getInstance();
    jdkTable.addJdk(sdk, myTestFixture.getTestRootDisposable());
  });
}
 
Example #11
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 #12
Source File: HaskellLightPlatformCodeInsightFixtureTestCase.java    From intellij-haskforce with Apache License 2.0 5 votes vote down vote up
protected void setUpProjectSdk() {
    ApplicationManager.getApplication().runWriteAction(new Runnable() {
        @Override
        public void run() {
            Sdk sdk = getProjectDescriptor().getSdk();
            ProjectJdkTable.getInstance().addJdk(sdk);
            ProjectRootManager.getInstance(myFixture.getProject()).setProjectSdk(sdk);
        }
    });
}
 
Example #13
Source File: PantsProjectImportBuilder.java    From intellij-pants-plugin with Apache License 2.0 5 votes vote down vote up
@Override
protected void applyExtraSettings(@NotNull WizardContext context) {
  Optional.ofNullable(getExternalProjectNode())
    .map(node -> ExternalSystemApiUtil.find(node, ProjectSdkData.KEY))
    .map(DataNode::getData)
    .map(ProjectSdkData::getSdkName)
    .map(ProjectJdkTable.getInstance()::findJdk)
    .ifPresent(context::setProjectJdk);
}
 
Example #14
Source File: PantsIntegrationTestCase.java    From intellij-pants-plugin with Apache License 2.0 5 votes vote down vote up
public static void removeJdks(@NotNull final Predicate<Sdk> pred) {
  getAllJdks().filter(pred).forEach(jdk -> {
    ApplicationManager.getApplication().runWriteAction(() -> {
      ProjectJdkTable.getInstance().removeJdk(jdk);
    });
  });
}
 
Example #15
Source File: DuneFacet.java    From reasonml-idea-plugin with MIT License 5 votes vote down vote up
@Nullable
public Sdk getODK() {
    DuneFacetConfiguration configuration = getConfiguration();
    if (configuration.inheritProjectSdk) {
        return OCamlSdkType.getSDK(getModule().getProject());
    }

    if (configuration.sdkName != null) {
        return ProjectJdkTable.getInstance().findJdk(configuration.sdkName);
    }

    return null;
}
 
Example #16
Source File: RoboVmPlugin.java    From robovm-idea with GNU General Public License v2.0 5 votes vote down vote up
public static Sdk getSdk() {
    RoboVmSdkType sdkType = new RoboVmSdkType();
    for(Sdk sdk: ProjectJdkTable.getInstance().getAllJdks()) {
        if(sdkType.suggestSdkName(null, null).equals(sdk.getName())) {
            return sdk;
        }
    }
    return null;
}
 
Example #17
Source File: RoboVmPlugin.java    From robovm-idea with GNU General Public License v2.0 5 votes vote down vote up
public static File getBestAndroidSdkDir() {
    Sdk bestSdk = null;
    for (Sdk sdk : ProjectJdkTable.getInstance().getAllJdks()) {
        if (sdk.getSdkType().getName().equals("Android SDK")) {
            if(sdk.getHomePath().contains("/Library/RoboVM/")) {
                return new File(sdk.getHomePath());
            } else {
                bestSdk = sdk;
            }
        }
    }
    return new File(bestSdk.getHomePath());
}
 
Example #18
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 #19
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 #20
Source File: XQueryRunProfileState.java    From intellij-xquery with Apache License 2.0 5 votes vote down vote up
private Sdk createAlternativeJdk(@NotNull String jreHome) throws CantRunException {
    final Sdk configuredJdk = ProjectJdkTable.getInstance().findJdk(jreHome);
    if (configuredJdk != null) {
        return configuredJdk;
    }

    if (!JdkUtil.checkForJre(jreHome) && !JdkUtil.checkForJdk(jreHome)) {
        throw new CantRunException(ExecutionBundle.message("jre.path.is.not.valid.jre.home.error.message", jreHome));
    }

    final String versionString = SdkVersionUtil.detectJdkVersion(jreHome);
    final Sdk jdk = new SimpleJavaSdkType().createJdk(versionString != null ? versionString : "", jreHome);
    if (jdk == null) throw CantRunException.noJdkConfigured();
    return jdk;
}
 
Example #21
Source File: IntelliJAndroidSdk.java    From flutter-intellij with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Returns each SDK that's an Android SDK.
 */
@NotNull
private static List<IntelliJAndroidSdk> findAll() {
  final List<IntelliJAndroidSdk> result = new ArrayList<>();
  for (Sdk sdk : ProjectJdkTable.getInstance().getAllJdks()) {
    final IntelliJAndroidSdk candidate = IntelliJAndroidSdk.fromSdk(sdk);
    if (candidate != null) {
      result.add(candidate);
    }
  }
  return result;
}
 
Example #22
Source File: IntelliJAndroidSdk.java    From flutter-intellij with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Returns each SDK that's an Android SDK.
 */
@NotNull
private static List<IntelliJAndroidSdk> findAll() {
  final List<IntelliJAndroidSdk> result = new ArrayList<>();
  for (Sdk sdk : ProjectJdkTable.getInstance().getAllJdks()) {
    final IntelliJAndroidSdk candidate = IntelliJAndroidSdk.fromSdk(sdk);
    if (candidate != null) {
      result.add(candidate);
    }
  }
  return result;
}
 
Example #23
Source File: Utils.java    From android-butterknife-zelezny with Apache License 2.0 5 votes vote down vote up
/**
 * Is using Android SDK?
 */
public static Sdk findAndroidSDK() {
    Sdk[] allJDKs = ProjectJdkTable.getInstance().getAllJdks();
    for (Sdk sdk : allJDKs) {
        if (sdk.getSdkType().getName().toLowerCase().contains("android")) {
            return sdk;
        }
    }

    return null; // no Android SDK found
}
 
Example #24
Source File: PantsIntegrationTestCase.java    From intellij-pants-plugin with Apache License 2.0 4 votes vote down vote up
@NotNull
public static Stream<Sdk> getAllJdks() {
  return Arrays.stream(ProjectJdkTable.getInstance().getAllJdks());
}
 
Example #25
Source File: AlternativeJreValidator.java    From intellij-xquery with Apache License 2.0 4 votes vote down vote up
public static void checkAlternativeJRE(@Nullable String jrePath) throws RuntimeConfigurationWarning {
    if (StringUtil.isEmpty(jrePath) ||
            ProjectJdkTable.getInstance().findJdk(jrePath) == null && !JdkUtil.checkForJre(jrePath)) {
        throw new RuntimeConfigurationWarning(ExecutionBundle.message("jre.path.is.not.valid.jre.home.error.message", jrePath));
    }
}
 
Example #26
Source File: AlternativeJREPanel.java    From intellij-xquery with Apache License 2.0 4 votes vote down vote up
public AlternativeJREPanel() {
    myCbEnabled = new JBCheckBox(ExecutionBundle.message("run.configuration.use.alternate.jre.checkbox"));

    myFieldWithHistory = new TextFieldWithHistory();
    myFieldWithHistory.setHistorySize(-1);
    final List<String> foundJDKs = new ArrayList<>();
    final Sdk[] allJDKs = ProjectJdkTable.getInstance().getAllJdks();

    String javaHomeOfCurrentProcess = System.getProperty("java.home");
    if (javaHomeOfCurrentProcess != null && !javaHomeOfCurrentProcess.isEmpty()) {
        foundJDKs.add(javaHomeOfCurrentProcess);
    }

    for (Sdk sdk : allJDKs) {
        String name = sdk.getName();
        if (!foundJDKs.contains(name)) {
            foundJDKs.add(name);
        }
    }

    for (Sdk jdk : allJDKs) {
        String homePath = jdk.getHomePath();

        if (!SystemInfo.isMac) {
            final File jre = new File(jdk.getHomePath(), "jre");
            if (jre.isDirectory()) {
                homePath = jre.getPath();
            }
        }

        if (!foundJDKs.contains(homePath)) {
            foundJDKs.add(homePath);
        }
    }

    myFieldWithHistory.setHistory(foundJDKs);
    myPathField = new ComponentWithBrowseButton<>(myFieldWithHistory, null);
    myPathField.addBrowseFolderListener(ExecutionBundle.message("run.configuration.select.alternate.jre.label"),
            ExecutionBundle.message("run.configuration.select.jre.dir.label"),
            null, BrowseFilesListener.SINGLE_DIRECTORY_DESCRIPTOR,
            TextComponentAccessor.TEXT_FIELD_WITH_HISTORY_WHOLE_TEXT);

    setLayout(new MigLayout("ins 0, gap 10, fill, flowx"));
    add(myCbEnabled, "shrinkx");
    add(myPathField, "growx, pushx");

    InsertPathAction.addTo(myFieldWithHistory.getTextEditor());

    myCbEnabled.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            enabledChanged();
        }
    });
    enabledChanged();

    setAnchor(myCbEnabled);

    updateUI();
}
 
Example #27
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 #28
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 #29
Source File: BlazeIntegrationTestCase.java    From intellij with Apache License 2.0 4 votes vote down vote up
@Before
public final void setUp() throws Exception {
  testFixture = createTestFixture();
  testFixture.setUp();
  fileSystem =
      new TestFileSystem(getProject(), testFixture.getTempDirFixture(), isLightTestCase());

  runWriteAction(
      () -> {
        ProjectJdkTable.getInstance().addJdk(IdeaTestUtil.getMockJdk18());
        VirtualFile workspaceRootVirtualFile = fileSystem.createDirectory("workspace");
        workspaceRoot = new WorkspaceRoot(new File(workspaceRootVirtualFile.getPath()));
        projectDataDirectory = fileSystem.createDirectory("project-data-dir");
        workspace = new WorkspaceFileSystem(workspaceRoot, fileSystem);
      });

  BlazeImportSettingsManager.getInstance(getProject())
      .setImportSettings(
          new BlazeImportSettings(
              workspaceRoot.toString(),
              "test-project",
              projectDataDirectory.getPath(),
              workspaceRoot.fileForPath(new WorkspacePath("project-view-file")).getPath(),
              buildSystem()));

  registerApplicationService(
      InputStreamProvider.class,
      new InputStreamProvider() {
        @Override
        public InputStream forFile(File file) throws IOException {
          VirtualFile vf = fileSystem.findFile(file.getPath());
          if (vf == null) {
            throw new FileNotFoundException();
          }
          return vf.getInputStream();
        }

        @Override
        public BufferedInputStream forOutputArtifact(BlazeArtifact output) throws IOException {
          if (output instanceof LocalFileArtifact) {
            return new BufferedInputStream(forFile(((LocalFileArtifact) output).getFile()));
          }
          throw new RuntimeException("Can't handle output artifact type: " + output.getClass());
        }
      });

  if (isLightTestCase()) {
    registerApplicationService(
        FileOperationProvider.class, new TestFileSystem.MockFileOperationProvider());
    registerApplicationService(
        VirtualFileSystemProvider.class, new TestFileSystem.TempVirtualFileSystemProvider());
  }

  String requiredPlugins = System.getProperty("idea.required.plugins.id");
  if (requiredPlugins != null) {
    VerifyRequiredPluginsEnabled.runCheck(requiredPlugins.split(","));
  }
}
 
Example #30
Source File: MockSdkUtil.java    From intellij with Apache License 2.0 4 votes vote down vote up
/**
 * Creates a mock SDK and register it in {@link ProjectJdkTable}.
 *
 * <p>Same as {link #registerSdk} but provides user ability to customize root content of SDK and
 * dummy files to create. It can be used to mock corrupt {@link ProjectJdkTable}/ missing SDK in
 * local.
 *
 * @param workspace test file system
 * @param major major version of SDK
 * @param minor minor version of SDK
 * @param roots root content of SDK
 * @param createSubFiles whether create subdirectory and files in file system for SDK. Set this to
 *     false would lead to fail to add SDK to Jdk table and cannot retrieve its repo package
 * @return a mock sdk for the given target and name. The sdk is registered with the {@link
 *     ProjectJdkTable}.
 */
public static Sdk registerSdk(
    WorkspaceFileSystem workspace,
    String major,
    String minor,
    MultiMap<OrderRootType, VirtualFile> roots,
    boolean createSubFiles) {
  String targetHash = String.format(TARGET_HASH, major);
  String sdkName = String.format(SDK_NAME, major);
  WorkspacePath workspacePathToAndroid = new WorkspacePath(PLATFORM_DIR, targetHash);

  if (createSubFiles) {
    workspace.createFile(
        new WorkspacePath(workspacePathToAndroid, "package.xml"),
        "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>",
        "<ns2:repository xmlns:ns2=\"http://schemas.android.com/repository/android/common/01\"",
        " xmlns:ns3=\"http://schemas.android.com/repository/android/generic/01\"",
        " xmlns:ns4=\"http://schemas.android.com/sdk/android/repo/addon2/01\"",
        " xmlns:ns5=\"http://schemas.android.com/sdk/android/repo/repository2/01\"",
        " xmlns:ns6=\"http://schemas.android.com/sdk/android/repo/sys-img2/01\">",
        "<localPackage path=\"platforms;" + targetHash + "\" obsolete=\"false\">",
        "<type-details xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\""
            + " xsi:type=\"ns5:platformDetailsType\">",
        "<api-level>",
        major,
        "</api-level>",
        "<layoutlib api=\"15\"/>",
        "</type-details>",
        "<revision>",
        " <major>",
        major,
        " </major>",
        " <minor>",
        minor,
        " </minor>",
        " <micro>",
        "0",
        " </micro>",
        "</revision>",
        "<display-name>",
        sdkName,
        "</display-name>",
        "</localPackage>",
        "</ns2:repository>");
    workspace.createFile(new WorkspacePath(workspacePathToAndroid, "build.prop"));
    workspace.createFile(new WorkspacePath(workspacePathToAndroid, "android.jar"));
    workspace.createDirectory(new WorkspacePath(workspacePathToAndroid, "data/res"));
    workspace.createFile(new WorkspacePath(workspacePathToAndroid, "data/annotations.zip"));
  }
  String sdkHomeDir = workspace.createDirectory(SDK_DIR).getPath();
  AndroidSdkData.getSdkData(new File(sdkHomeDir), true);
  MockSdk sdk =
      new MockSdk(
          sdkName,
          sdkHomeDir,
          String.format("%s.%s.0", major, minor),
          roots,
          AndroidSdkType.getInstance());
  AndroidSdkAdditionalData data = new AndroidSdkAdditionalData(sdk);
  data.setBuildTargetHashString(targetHash);
  sdk.setSdkAdditionalData(data);
  EdtTestUtil.runInEdtAndWait(
      () ->
          ApplicationManager.getApplication()
              .runWriteAction(() -> ProjectJdkTable.getInstance().addJdk(sdk)));
  return sdk;
}