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);
          }
        });
  }
 @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;
 }
 /* Remoting */
 private static void checkTargetJPDAInstalled(JavaParameters parameters)
     throws ExecutionException {
   final Sdk jdk = parameters.getJdk();
   if (jdk == null) {
     throw new ExecutionException(DebuggerBundle.message("error.jdk.not.specified"));
   }
   final JavaSdkVersion version = JavaSdk.getInstance().getVersion(jdk);
   String versionString = jdk.getVersionString();
   if (version == JavaSdkVersion.JDK_1_0 || version == JavaSdkVersion.JDK_1_1) {
     throw new ExecutionException(
         DebuggerBundle.message("error.unsupported.jdk.version", versionString));
   }
   if (SystemInfo.isWindows && version == JavaSdkVersion.JDK_1_2) {
     final VirtualFile homeDirectory = jdk.getHomeDirectory();
     if (homeDirectory == null || !homeDirectory.isValid()) {
       throw new ExecutionException(
           DebuggerBundle.message("error.invalid.jdk.home", versionString));
     }
     //noinspection HardCodedStringLiteral
     File dllFile =
         new File(
             homeDirectory.getPath().replace('/', File.separatorChar)
                 + File.separator
                 + "bin"
                 + File.separator
                 + "jdwp.dll");
     if (!dllFile.exists()) {
       GetJPDADialog dialog = new GetJPDADialog();
       dialog.show();
       throw new ExecutionException(DebuggerBundle.message("error.debug.libraries.missing"));
     }
   }
 }
  @Nullable
  @Override
  protected String getHelperPath(String helper) throws ExecutionException {
    final Sdk sdk = getSdk();

    final SdkAdditionalData sdkData = sdk.getSdkAdditionalData();
    if (sdkData instanceof PyRemoteSdkAdditionalDataBase) {
      final PyRemoteSdkAdditionalDataBase remoteSdkData = (PyRemoteSdkAdditionalDataBase) sdkData;
      try {
        String helpersPath;
        if (CaseCollector.useRemoteCredentials(remoteSdkData)) {
          final RemoteSdkCredentials remoteSdkCredentials =
              remoteSdkData.getRemoteSdkCredentials(false);
          helpersPath = remoteSdkCredentials.getHelpersPath();
        } else {
          helpersPath = remoteSdkData.getHelpersPath();
        }
        if (!StringUtil.isEmpty(helpersPath)) {
          return new RemoteFile(helpersPath, helper).getPath();
        } else {
          return null;
        }
      } catch (InterruptedException e) {
        LOG.error(e);
      } catch (ExecutionException e) {
        throw analyzeException(e, helper, Collections.<String>emptyList());
      }
    }
    return null;
  }
Example #5
0
 /** Adds new CLASSES entries found in sys.path. */
 private static boolean addNewSysPathEntries(
     @NotNull Sdk sdk, @NotNull SdkModificator modificator, @NotNull List<String> sysPath) {
   final List<VirtualFile> oldRoots =
       Arrays.asList(sdk.getRootProvider().getFiles(OrderRootType.CLASSES));
   PythonSdkAdditionalData additionalData =
       sdk.getSdkAdditionalData() instanceof PythonSdkAdditionalData
           ? (PythonSdkAdditionalData) sdk.getSdkAdditionalData()
           : null;
   List<String> newRoots = new ArrayList<String>();
   for (String root : sysPath) {
     if (new File(root).exists()
         && !FileUtilRt.extensionEquals(root, "egg-info")
         && (additionalData == null || !wasOldRoot(root, additionalData.getExcludedPathFiles()))
         && !wasOldRoot(root, oldRoots)) {
       newRoots.add(root);
     }
   }
   if (!newRoots.isEmpty()) {
     for (String root : newRoots) {
       PythonSdkType.addSdkRoot(modificator, root);
     }
     return true;
   }
   return false;
 }
 private static String getSdkHome(Project project) {
   Sdk sdk = ProjectRootManagerImpl.getInstance(project).getProjectSdk();
   if (sdk == null) {
     return null;
   }
   return sdk.getHomePath();
 }
  private static CommandLineArgumentsProvider createCommandLineArgumentsProvider(
      final Sdk sdk, final Map<String, String> environmentVariables, int[] ports) {
    final ArrayList<String> args = new ArrayList<String>();
    args.add(sdk.getHomePath());
    final String versionString = sdk.getVersionString();
    if (versionString == null || !versionString.toLowerCase().contains("jython")) {
      args.add("-u");
    }
    args.add(
        FileUtil.toSystemDependentName(PythonHelpersLocator.getHelperPath(PYDEV_PYDEVCONSOLE_PY)));
    for (int port : ports) {
      args.add(String.valueOf(port));
    }
    return new CommandLineArgumentsProvider() {
      @Override
      public String[] getArguments() {
        return ArrayUtil.toStringArray(args);
      }

      @Override
      public boolean passParentEnvs() {
        return false;
      }

      @Override
      public Map<String, String> getAdditionalEnvs() {
        return addDefaultEnvironments(sdk, environmentVariables);
      }
    };
  }
  protected void appendForkInfo(Executor executor) throws ExecutionException {
    final String forkMode = getForkMode();
    if (Comparing.strEqual(forkMode, "none")) {
      if (forkPerModule()) {
        if (isExecutorDisabledInForkedMode()) {
          final String actionName = UIUtil.removeMnemonic(executor.getStartActionText());
          throw new CantRunException(
              "'"
                  + actionName
                  + "' is disabled when per-module working directory is configured.<br/>"
                  + "Please specify single working directory, or change test scope to single module.");
        }
      } else {
        return;
      }
    } else if (isExecutorDisabledInForkedMode()) {
      final String actionName = executor.getActionName();
      throw new CantRunException(
          actionName
              + " is disabled in fork mode.<br/>Please change fork mode to &lt;none&gt; to "
              + actionName.toLowerCase(Locale.ENGLISH)
              + ".");
    }

    final JavaParameters javaParameters = getJavaParameters();
    final Sdk jdk = javaParameters.getJdk();
    if (jdk == null) {
      throw new ExecutionException(
          ExecutionBundle.message("run.configuration.error.no.jdk.specified"));
    }

    try {
      final File tempFile = FileUtil.createTempFile("command.line", "", true);
      final PrintWriter writer = new PrintWriter(tempFile, CharsetToolkit.UTF8);
      try {
        if (JdkUtil.useDynamicClasspath(getConfiguration().getProject())) {
          String classpath = PathUtil.getJarPathForClass(CommandLineWrapper.class);
          final String utilRtPath = PathUtil.getJarPathForClass(StringUtilRt.class);
          if (!classpath.equals(utilRtPath)) {
            classpath += File.pathSeparator + utilRtPath;
          }
          writer.println(classpath);
        } else {
          writer.println("");
        }

        writer.println(((JavaSdkType) jdk.getSdkType()).getVMExecutablePath(jdk));
        for (String vmParameter : javaParameters.getVMParametersList().getList()) {
          writer.println(vmParameter);
        }
      } finally {
        writer.close();
      }

      passForkMode(forkMode, tempFile);
    } catch (Exception e) {
      LOG.error(e);
    }
  }
Example #9
0
 public void jdkRemoved(Sdk jdk) {
   if (jdk == myJdk) {
     setJdkName(myJdk.getName());
     setJdkType(myJdk.getSdkType().getName());
     myJdk = null;
     updateFromRootProviderAndSubscribe(getRootProvider());
   }
 }
 @Nullable
 public String getToolsPath(Sdk sdk) {
   final Sdk jdk = getInternalJavaSdk(sdk);
   if (jdk != null && jdk.getVersionString() != null) {
     return JavaSdk.getInstance().getToolsPath(jdk);
   }
   return null;
 }
Example #11
0
 public String getJdkName() {
   if (myJdkName != null) return myJdkName;
   Sdk jdk = getJdk();
   if (jdk != null) {
     return jdk.getName();
   }
   return null;
 }
 protected static void setToolsJar(JavaParameters params) {
   Sdk jdk = params.getJdk();
   if (jdk != null && jdk.getSdkType() instanceof JavaSdkType) {
     String toolsPath = ((JavaSdkType) jdk.getSdkType()).getToolsPath(jdk);
     if (toolsPath != null) {
       params.getVMParametersList().add("-Dtools.jar=" + toolsPath);
     }
   }
 }
 public static void addJavaHome(@NotNull JavaParameters params, @NotNull Module module) {
   final Sdk sdk = ModuleRootManager.getInstance(module).getSdk();
   if (sdk != null && sdk.getSdkType() instanceof JavaSdkType) {
     String path = StringUtil.trimEnd(sdk.getHomePath(), File.separator);
     if (StringUtil.isNotEmpty(path)) {
       params.addEnv("JAVA_HOME", FileUtil.toSystemDependentName(path));
     }
   }
 }
  @Override
  public void patchJavaParameters(@Nullable final Module module, JavaParameters javaParameters) {
    if (module != null
        && PsiUtil.isIdeaProject(module.getProject())
        && !javaParameters.getVMParametersList().hasParameter(SYSTEM_CL_PROPERTY)) {
      final JavaPsiFacade psiFacade = JavaPsiFacade.getInstance(module.getProject());
      final String qualifiedName = UrlClassLoader.class.getName();
      final PsiClass urlLoaderClass =
          ApplicationManager.getApplication()
              .runReadAction(
                  new Computable<PsiClass>() {
                    @Override
                    public PsiClass compute() {
                      return psiFacade.findClass(
                          qualifiedName,
                          GlobalSearchScope.moduleWithDependenciesAndLibrariesScope(module));
                    }
                  });
      if (urlLoaderClass != null) {
        javaParameters.getVMParametersList().addProperty(SYSTEM_CL_PROPERTY, qualifiedName);
      }
    }

    Sdk jdk = javaParameters.getJdk();
    jdk = IdeaJdk.findIdeaJdk(jdk);
    if (jdk == null) return;

    String libPath = jdk.getHomePath() + File.separator + "lib";

    final ParametersList vm = javaParameters.getVMParametersList();
    vm.add("-Xbootclasspath/a:" + libPath + File.separator + "boot.jar");
    if (!vm.hasProperty("idea.load.plugins.id")
        && module != null
        && PluginModuleType.isOfType(module)) {
      final String id = DescriptorUtil.getPluginId(module);
      if (id != null) {
        vm.defineProperty("idea.load.plugins.id", id);
      }
    }

    final File sandboxHome = getSandboxPath(jdk);
    if (sandboxHome != null) {
      if (!vm.hasProperty("idea.home.path")) {
        File homeDir = new File(sandboxHome, "test");
        FileUtil.createDirectory(homeDir);
        vm.defineProperty("idea.home.path", homeDir.getAbsolutePath());
      }
      if (!vm.hasProperty("idea.plugins.path")) {
        vm.defineProperty("idea.plugins.path", new File(sandboxHome, "plugins").getAbsolutePath());
      }
    }

    javaParameters.getClassPath().addFirst(libPath + File.separator + "idea.jar");
    javaParameters.getClassPath().addFirst(libPath + File.separator + "resources.jar");
    javaParameters.getClassPath().addFirst(((JavaSdkType) jdk.getSdkType()).getToolsPath(jdk));
  }
 private void editSdk() {
   final Sdk currentSdk = getSelectedSdk();
   if (currentSdk != null) {
     if (currentSdk.getSdkAdditionalData() instanceof RemoteSdkAdditionalData) {
       editRemoteSdk(currentSdk);
     } else {
       editSdk(currentSdk);
     }
   }
 }
 public void updateDataModel() {
   final Sdk chosenJdk = myPanel.getValue().getChosenJdk();
   if (chosenJdk != null && chosenJdk.getSdkType().equals(LuaSdkType.getInstance())) {
     if (myContext.getProjectJdk() == null) {
       myContext.setProjectJdk(chosenJdk);
     } else {
       myModuleBuilder.setSdk(chosenJdk);
     }
   }
 }
 public boolean isModified() {
   Sdk projectSdk = getSdk();
   if (projectSdk != null) {
     projectSdk = myProjectSdksModel.findSdk(projectSdk.getName());
   }
   return getSelectedSdk() != projectSdk
       || mySdkListChanged
       || myProjectSdksModel.isModified()
       || !myModifiedModificators.isEmpty();
 }
  @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 String extractJdkVersion(@NotNull Module module) {
    String jdkVersion = null;
    Sdk sdk = ModuleRootManager.getInstance(module).getSdk();
    if (sdk != null && (jdkVersion = sdk.getVersionString()) != null) {
      final int quoteIndex = jdkVersion.indexOf('"');
      if (quoteIndex != -1) {
        jdkVersion = jdkVersion.substring(quoteIndex + 1, jdkVersion.length() - 1);
      }
    }

    return jdkVersion;
  }
  /**
   * @param project
   * @return perl's executable file full path
   */
  public static String getPerlPath(Project project) {
    String path = null;
    if (project != null) {
      Sdk sdk = ProjectRootManagerImpl.getInstance(project).getProjectSdk();
      if (sdk != null) {
        return getPerlPath(sdk.getHomePath());
      } else {
        getPerlPath("");
      }
    }

    return path;
  }
  @Nullable
  public static String getInterpreterPath(Project project, PythonRunParams config) {
    String sdkHome = config.getSdkHome();
    if (config.isUseModuleSdk() || StringUtil.isEmpty(sdkHome)) {
      Module module = getModule(project, config);

      Sdk sdk = PythonSdkType.findPythonSdk(module);
      if (sdk == null) return null;
      sdkHome = sdk.getHomePath();
    }

    return sdkHome;
  }
 public void updateJdks(Sdk sdk, String previousName) {
   final Sdk[] sdks = _sdkModel.getSdks();
   for (Sdk currentSdk : sdks) {
     if (currentSdk.getSdkType().equals(GosuSdkType.getInstance())) {
       final GosuSdkAdditionalData data =
           (GosuSdkAdditionalData) currentSdk.getSdkAdditionalData();
       final Sdk internalJava = data != null ? data.getJavaSdk() : null;
       if (internalJava != null && Comparing.equal(internalJava.getName(), previousName)) {
         data.setJavaSdk(sdk);
       }
     }
   }
   updateJdks();
 }
  @NotNull
  public File[] getFilesForLibraries() {
    Sdk sdk = getSdk();
    if (sdk == null) {
      return EMPTY_FILE_ARRAY;
    }

    String homePath = sdk.getHomePath();
    if (homePath == null) {
      return EMPTY_FILE_ARRAY;
    }
    File[] files = new File(homePath).listFiles();
    return files == null ? EMPTY_FILE_ARRAY : files;
  }
 @Nullable
 private static Sdk findByPath(
     @NotNull SdkType sdkType, @NotNull Sdk[] sdks, @NotNull String sdkHome) {
   for (Sdk sdk : sdks) {
     final String path = sdk.getHomePath();
     if (sdk.getSdkType() == sdkType
         && path != null
         && FileUtil.pathsEqual(
             FileUtil.toSystemIndependentName(path), FileUtil.toSystemIndependentName(sdkHome))) {
       return sdk;
     }
   }
   return null;
 }
  public static void configureDirectoryProjectSdk(
      final Project project,
      @Nullable Comparator<Sdk> preferredSdkComparator,
      final SdkType... sdkTypes) {
    Sdk existingSdk = ProjectRootManager.getInstance(project).getProjectSdk();
    if (existingSdk != null && ArrayUtil.contains(existingSdk.getSdkType(), sdkTypes)) {
      return;
    }

    Sdk sdk = findOrCreateSdk(preferredSdkComparator, sdkTypes);
    if (sdk != null) {
      setDirectoryProjectSdk(project, sdk);
    }
  }
  @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);
        }
      }
    }
  }
 @NotNull
 public static String createUniqueSdkName(
     @NotNull String suggestedName, @NotNull Collection<Sdk> sdks) {
   final Set<String> names = new HashSet<>();
   for (Sdk jdk : sdks) {
     names.add(jdk.getName());
   }
   String newSdkName = suggestedName;
   int i = 0;
   while (names.contains(newSdkName)) {
     newSdkName = suggestedName + " (" + (++i) + ")";
   }
   return newSdkName;
 }
Example #28
0
  @Override
  public void setupSdkPaths(Sdk sdk) {
    final SdkModificator modificator = sdk.getSdkModificator();

    SdkAdditionalData data = sdk.getSdkAdditionalData();
    if (data == null) {
      data = DartSdkUtil.testDartSdk(sdk.getHomePath());
      modificator.setSdkAdditionalData(data);
    }

    DartSdkUtil.setupSdkPaths(sdk.getHomeDirectory(), modificator);

    modificator.commitChanges();
    super.setupSdkPaths(sdk);
  }
Example #29
0
  public static void addJavaHome(@NotNull JavaParameters params, @NotNull Module module) {
    final Sdk sdk = ModuleUtilCore.getSdk(module, JavaModuleExtensionImpl.class);
    if (sdk != null && sdk.getSdkType() instanceof JavaSdkType) {
      String path = StringUtil.trimEnd(sdk.getHomePath(), File.separator);
      if (StringUtil.isNotEmpty(path)) {
        Map<String, String> env = params.getEnv();
        if (env == null) {
          env = new HashMap<String, String>();
          params.setEnv(env);
        }

        env.put("JAVA_HOME", FileUtil.toSystemDependentName(path));
      }
    }
  }
  public static JavaParameters createJavaParametersWithSdk(@Nullable Module module) {
    JavaParameters params = new JavaParameters();
    params.setCharset(null);

    if (module != null) {
      final Sdk sdk = ModuleRootManager.getInstance(module).getSdk();
      if (sdk != null && sdk.getSdkType() instanceof JavaSdkType) {
        params.setJdk(sdk);
      }
    }
    if (params.getJdk() == null) {
      params.setJdk(new SimpleJavaSdkType().createJdk("tmp", SystemProperties.getJavaHome()));
    }
    return params;
  }