@NotNull
  private static Sdk getJdk(
      @Nullable Project project, MavenRunnerSettings runnerSettings, boolean isGlobalRunnerSettings)
      throws ExecutionException {
    String name = runnerSettings.getJreName();
    if (name.equals(MavenRunnerSettings.USE_INTERNAL_JAVA)) {
      return JavaAwareProjectJdkTableImpl.getInstanceEx().getInternalJdk();
    }

    if (name.equals(MavenRunnerSettings.USE_PROJECT_JDK)) {
      if (project != null) {
        Sdk res = ProjectRootManager.getInstance(project).getProjectSdk();
        if (res != null) {
          return res;
        }
      }

      if (project == null) {
        Sdk recent = ProjectJdkTable.getInstance().findMostRecentSdkOfType(JavaSdk.getInstance());
        if (recent != null) return recent;
        return JavaAwareProjectJdkTableImpl.getInstanceEx().getInternalJdk();
      }

      throw new ProjectJdkSettingsOpenerExecutionException(
          "Project JDK is not specified. <a href='#'>Configure</a>", project);
    }

    if (name.equals(MavenRunnerSettings.USE_JAVA_HOME)) {
      final String javaHome = System.getenv(JAVA_HOME);
      if (StringUtil.isEmptyOrSpaces(javaHome)) {
        throw new ExecutionException(RunnerBundle.message("maven.java.home.undefined"));
      }
      final Sdk jdk = JavaSdk.getInstance().createJdk("", javaHome);
      if (jdk == null) {
        throw new ExecutionException(RunnerBundle.message("maven.java.home.invalid", javaHome));
      }
      return jdk;
    }

    for (Sdk projectJdk : ProjectJdkTable.getInstance().getAllJdks()) {
      if (projectJdk.getName().equals(name)) {
        return projectJdk;
      }
    }

    if (isGlobalRunnerSettings) {
      throw new ExecutionException(
          RunnerBundle.message("maven.java.not.found.default.config", name));
    } else {
      throw new ExecutionException(RunnerBundle.message("maven.java.not.found", name));
    }
  }
 @Nullable
 public static Sdk getNewProjectJdk(WizardContext context) {
   if (context.getProjectJdk() != null) {
     return context.getProjectJdk();
   }
   final Project project =
       context.getProject() == null
           ? ProjectManager.getInstance().getDefaultProject()
           : context.getProject();
   final Sdk projectJdk = ProjectRootManager.getInstance(project).getProjectSdk();
   if (projectJdk != null) {
     return projectJdk;
   }
   if (context.getProject() == null) {
     @Nullable final ProjectBuilder projectBuilder = context.getProjectBuilder();
     return ProjectJdkTable.getInstance()
         .findMostRecentSdk(
             new Condition<Sdk>() {
               public boolean value(Sdk sdk) {
                 return projectBuilder == null || projectBuilder.isSuitableSdk(sdk);
               }
             });
   }
   return null;
 }
  public static void selectSdkHome(
      @NotNull final SdkType sdkType, @NotNull final Consumer<String> consumer) {
    final FileChooserDescriptor descriptor = sdkType.getHomeChooserDescriptor();
    if (ApplicationManager.getApplication().isUnitTestMode()) {
      Sdk sdk = ProjectJdkTable.getInstance().findMostRecentSdkOfType(sdkType);
      if (sdk == null) throw new RuntimeException("No SDK of type " + sdkType + " found");
      consumer.consume(sdk.getHomePath());
      return;
    }
    FileChooser.chooseFiles(
        descriptor,
        null,
        getSuggestedSdkRoot(sdkType),
        chosen -> {
          final String path = chosen.get(0).getPath();
          if (sdkType.isValidSdkHome(path)) {
            consumer.consume(path);
            return;
          }

          final String adjustedPath = sdkType.adjustSelectedSdkHome(path);
          if (sdkType.isValidSdkHome(adjustedPath)) {
            consumer.consume(adjustedPath);
          }
        });
  }
  ModuleJdkOrderEntryImpl(
      Element element,
      RootModelImpl rootModel,
      ProjectRootManagerImpl projectRootManager,
      VirtualFilePointerManager filePointerManager)
      throws InvalidDataException {
    super(rootModel, projectRootManager, filePointerManager);
    if (!element.getName().equals(OrderEntryFactory.ORDER_ENTRY_ELEMENT_NAME)) {
      throw new InvalidDataException();
    }
    final Attribute jdkNameAttribute = element.getAttribute(JDK_NAME_ATTR);
    if (jdkNameAttribute == null) {
      throw new InvalidDataException();
    }

    final String jdkName = jdkNameAttribute.getValue();
    final String jdkType = element.getAttributeValue(JDK_TYPE_ATTR);
    final ProjectJdkTable projectJdkTable = ProjectJdkTable.getInstance();
    final Sdk jdkByName = projectJdkTable.findJdk(jdkName, jdkType);
    if (jdkByName == null) {
      init(null, jdkName, jdkType);
    } else {
      init(jdkByName, null, null);
    }
  }
 private static void fillSdks(List<GlobalLibrary> globals) {
   for (Sdk sdk : ProjectJdkTable.getInstance().getAllJdks()) {
     final String name = sdk.getName();
     final String homePath = sdk.getHomePath();
     if (homePath == null) {
       continue;
     }
     final SdkAdditionalData data = sdk.getSdkAdditionalData();
     final String additionalDataXml;
     final SdkType sdkType = (SdkType) sdk.getSdkType();
     if (data == null) {
       additionalDataXml = null;
     } else {
       final Element element = new Element("additional");
       sdkType.saveAdditionalData(data, element);
       additionalDataXml = JDOMUtil.writeElement(element, "\n");
     }
     final List<String> paths =
         convertToLocalPaths(sdk.getRootProvider().getFiles(OrderRootType.CLASSES));
     String versionString = sdk.getVersionString();
     if (versionString != null && sdkType instanceof JavaSdk) {
       final JavaSdkVersion version = ((JavaSdk) sdkType).getVersion(versionString);
       if (version != null) {
         versionString = version.getDescription();
       }
     }
     globals.add(
         new SdkLibrary(
             name, sdkType.getName(), versionString, homePath, paths, additionalDataXml));
   }
 }
 @Nullable
 public static Sdk findOrCreateSdk(
     @Nullable Comparator<Sdk> comparator, final SdkType... sdkTypes) {
   final Project defaultProject = ProjectManager.getInstance().getDefaultProject();
   final Sdk sdk = ProjectRootManager.getInstance(defaultProject).getProjectSdk();
   if (sdk != null) {
     for (SdkType type : sdkTypes) {
       if (sdk.getSdkType() == type) {
         return sdk;
       }
     }
   }
   for (SdkType type : sdkTypes) {
     List<Sdk> sdks = ProjectJdkTable.getInstance().getSdksOfType(type);
     if (!sdks.isEmpty()) {
       if (comparator != null) {
         Collections.sort(sdks, comparator);
       }
       return sdks.get(0);
     }
   }
   for (SdkType sdkType : sdkTypes) {
     final String suggestedHomePath = sdkType.suggestHomePath();
     if (suggestedHomePath != null && sdkType.isValidSdkHome(suggestedHomePath)) {
       Sdk an_sdk = createAndAddSDK(suggestedHomePath, sdkType);
       if (an_sdk != null) return an_sdk;
     }
   }
   return null;
 }
  @Override
  public void consume(@Nullable AbstractProjectSettingsStep settingsStep) {
    if (myRunnable != null) {
      myRunnable.run();
    }
    if (settingsStep == null) return;

    Sdk sdk = settingsStep.getSdk();
    final Project project = ProjectManager.getInstance().getDefaultProject();
    final ProjectSdksModel model = PyConfigurableInterpreterList.getInstance(project).getModel();
    if (sdk instanceof PyDetectedSdk) {
      final String name = sdk.getName();
      VirtualFile sdkHome =
          ApplicationManager.getApplication()
              .runWriteAction(
                  new Computable<VirtualFile>() {
                    @Override
                    public VirtualFile compute() {
                      return LocalFileSystem.getInstance().refreshAndFindFileByPath(name);
                    }
                  });
      PySdkService.getInstance().solidifySdk(sdk);
      sdk =
          SdkConfigurationUtil.setupSdk(
              ProjectJdkTable.getInstance().getAllJdks(),
              sdkHome,
              PythonSdkType.getInstance(),
              true,
              null,
              null);
      model.addSdk(sdk);
      settingsStep.setSdk(sdk);
      try {
        model.apply();
      } catch (ConfigurationException exception) {
        LOG.error("Error adding detected python interpreter " + exception.getMessage());
      }
    }
    Project newProject = generateProject(project, settingsStep);
    if (newProject != null) {
      SdkConfigurationUtil.setDirectoryProjectSdk(newProject, sdk);
      final List<Sdk> sdks = PythonSdkType.getAllSdks();
      for (Sdk s : sdks) {
        final SdkAdditionalData additionalData = s.getSdkAdditionalData();
        if (additionalData instanceof PythonSdkAdditionalData) {
          ((PythonSdkAdditionalData) additionalData).reassociateWithCreatedProject(newProject);
        }
      }
    }
  }
  public void reset() {
    myEnableCompileServer.setSelected(mySettings.COMPILE_SERVER_ENABLED);
    myCompilationServerPort.setText(mySettings.COMPILE_SERVER_PORT);

    Sdk sdk =
        mySettings.COMPILE_SERVER_SDK == null
            ? null
            : ProjectJdkTable.getInstance().findJdk(mySettings.COMPILE_SERVER_SDK);
    myCompilationServerSdk.setSelectedJdk(sdk);

    myCompilationServerMaximumHeapSize.setText(mySettings.COMPILE_SERVER_MAXIMUM_HEAP_SIZE);
    myCompilationServerJvmParameters.setText(mySettings.COMPILE_SERVER_JVM_PARAMETERS);
    showTypeInfoOnCheckBox.setSelected(mySettings.SHOW_TYPE_TOOLTIP_ON_MOUSE_HOVER);
    delaySpinner.setValue(mySettings.SHOW_TYPE_TOOLTIP_DELAY);
  }
  public void rebuildSdksListAndSelectSdk(final Sdk selectedSdk) {
    final List<Sdk> sdks =
        ProjectJdkTable.getInstance().getSdksOfType(AndroidSdkType.getInstance());

    final JComboBox sdksComboBox = getComboBox();
    sdksComboBox.setModel(new DefaultComboBoxModel(sdks.toArray()));

    if (selectedSdk != null) {
      for (Sdk candidateSdk : sdks) {
        if (candidateSdk != null && candidateSdk.getName().equals(selectedSdk.getName())) {
          sdksComboBox.setSelectedItem(candidateSdk);
          return;
        }
      }
    }
    sdksComboBox.setSelectedItem(null);
  }
 @Nullable
 private static Sdk fixProjectSdk(@NotNull Project project) {
   final ProjectRootManagerEx projectRootMgr = ProjectRootManagerEx.getInstanceEx(project);
   Sdk selectedSdk = projectRootMgr.getProjectSdk();
   if (selectedSdk == null || selectedSdk.getSdkType() != ErlangSdkType.getInstance()) {
     final Sdk moreSuitableSdk =
         ProjectJdkTable.getInstance().findMostRecentSdkOfType(ErlangSdkType.getInstance());
     ApplicationManager.getApplication()
         .runWriteAction(
             new Runnable() {
               @Override
               public void run() {
                 projectRootMgr.setProjectSdk(moreSuitableSdk);
               }
             });
     return moreSuitableSdk;
   }
   return selectedSdk;
 }
 @Override
 protected void setUpModuleJdk(
     ModifiableRootModel rootModel,
     Collection<String> unknownJdks,
     EclipseModuleManager eclipseModuleManager,
     String jdkName) {
   if (jdkName == null) {
     rootModel.inheritSdk();
   } else {
     final Sdk moduleJdk = ProjectJdkTable.getInstance().findJdk(jdkName);
     if (moduleJdk != null) {
       rootModel.setSdk(moduleJdk);
     } else {
       rootModel.setInvalidSdk(jdkName, IdeaXml.JAVA_SDK_TYPE);
       eclipseModuleManager.setInvalidJdk(jdkName);
       unknownJdks.add(jdkName);
     }
   }
   rearrangeOrderEntryOfType(rootModel, JdkOrderEntry.class);
 }
 /**
  * Tries to create an SDK identified by path; if successful, add the SDK to the global SDK table.
  *
  * @param path identifies the SDK
  * @param sdkType
  * @return newly created SDK, or null.
  */
 @Nullable
 public static Sdk createAndAddSDK(final String path, SdkType sdkType) {
   VirtualFile sdkHome =
       ApplicationManager.getApplication()
           .runWriteAction(
               new Computable<VirtualFile>() {
                 @Override
                 public VirtualFile compute() {
                   return LocalFileSystem.getInstance().refreshAndFindFileByPath(path);
                 }
               });
   if (sdkHome != null) {
     final Sdk newSdk =
         setupSdk(ProjectJdkTable.getInstance().getAllJdks(), sdkHome, sdkType, true, null, null);
     if (newSdk != null) {
       addSdk(newSdk);
     }
     return newSdk;
   }
   return null;
 }
  @Override
  public void initComponent() {
    ProjectJdkTable jdkTable = ProjectJdkTable.getInstance();
    List<Sdk> sdkList = new ArrayList<Sdk>();

    sdkList.addAll(GoSdkUtil.getSdkOfType(GoSdkType.getInstance(), jdkTable));

    for (Sdk sdk : sdkList) {
      GoSdkData sdkData = (GoSdkData) sdk.getSdkAdditionalData();

      boolean needsUpgrade = sdkData == null;
      try {
        if (!needsUpgrade) {
          sdkData.checkValid();
        }
      } catch (ConfigurationException ex) {
        needsUpgrade = true;
      }

      if (!needsUpgrade) continue;

      needsUpgrade = false;
      GoSdkData data = GoSdkUtil.testGoogleGoSdk(sdk.getHomePath());

      if (data == null) needsUpgrade = true;

      try {
        if (data != null) {
          data.checkValid();
        }
      } catch (ConfigurationException ex) {
        needsUpgrade = true;
      }

      if (needsUpgrade) {
        Notifications.Bus.notify(
            new Notification(
                "Go SDK validator",
                "Corrupt Go SDK",
                getContent("Go", sdk.getName()),
                NotificationType.WARNING),
            myProject);
      }

      SdkModificator sdkModificator = sdk.getSdkModificator();
      sdkModificator.setSdkAdditionalData(data);
      sdkModificator.commitChanges();
    }

    sdkList.clear();
    sdkList.addAll(GoSdkUtil.getSdkOfType(GoAppEngineSdkType.getInstance(), jdkTable));

    Boolean hasGAESdk = sdkList.size() > 0;

    for (Sdk sdk : sdkList) {
      GoAppEngineSdkData sdkData = (GoAppEngineSdkData) sdk.getSdkAdditionalData();

      if (sdkData == null || sdkData.TARGET_ARCH == null || sdkData.TARGET_OS == null) {
        Notifications.Bus.notify(
            new Notification(
                "Go AppEngine SDK validator",
                "Corrupt Go App Engine SDK",
                getContent("Go App Engine", sdk.getName()),
                NotificationType.WARNING),
            myProject);

        continue;
      }

      boolean needsUpgrade = false;
      try {
        sdkData.checkValid();
      } catch (ConfigurationException ex) {
        needsUpgrade = true;
      }

      if (!needsUpgrade) continue;

      needsUpgrade = false;
      GoAppEngineSdkData data = GoSdkUtil.testGoAppEngineSdk(sdk.getHomePath());

      if (data == null) needsUpgrade = true;

      try {
        if (data != null) {
          data.checkValid();
        }
      } catch (ConfigurationException ex) {
        needsUpgrade = true;
      }

      // GAE SDK auto-update needs a bit more love
      if (data != null && !(new File(data.GOAPP_BIN_PATH)).exists()) {
        needsUpgrade = true;
      }

      if (needsUpgrade) {
        Notifications.Bus.notify(
            new Notification(
                "Go AppEngine SDK validator",
                "Corrupt Go App Engine SDK",
                getContent("Go AppEngine", sdk.getName()),
                NotificationType.WARNING),
            myProject);
      }

      SdkModificator sdkModificator = sdk.getSdkModificator();
      sdkModificator.setSdkAdditionalData(data);
      sdkModificator.commitChanges();
    }

    if (hasGAESdk) {
      String sysAppEngineDevServerPath = GoSdkUtil.getAppEngineDevServer();
      if (sysAppEngineDevServerPath.isEmpty())
        Notifications.Bus.notify(
            new Notification(
                "Go AppEngine SDK validator",
                "Problem with env variables",
                getInvalidAPPENGINE_DEV_APPSERVEREnvMessage(),
                NotificationType.WARNING,
                NotificationListener.URL_OPENING_LISTENER),
            myProject);
    }

    PluginDescriptor pluginDescriptor =
        PluginManager.getPlugin(PluginId.getId("ro.redeul.google.go"));
    if (pluginDescriptor != null) {
      String version = ((IdeaPluginDescriptorImpl) pluginDescriptor).getVersion();

      if (version.endsWith("-dev")
          && !System.getProperty("go.skip.dev.warn", "false").equals("true")) {
        Notifications.Bus.notify(
            new Notification(
                "Go plugin notice",
                "Development version detected",
                getDevVersionMessage(),
                NotificationType.WARNING,
                null),
            myProject);
      }
    }

    super.initComponent();
  }
 public static void removeSdk(final Sdk sdk) {
   ApplicationManager.getApplication()
       .runWriteAction(() -> ProjectJdkTable.getInstance().removeJdk(sdk));
 }
 public static void addSdk(@NotNull final Sdk sdk) {
   ApplicationManager.getApplication()
       .runWriteAction(() -> ProjectJdkTable.getInstance().addJdk(sdk));
 }