Search in sources :

Example 16 with CantRunException

use of com.intellij.execution.CantRunException in project intellij-community by JetBrains.

the class GradleApplicationEnvironmentProvider method createExecutionEnvironment.

@Nullable
public ExecutionEnvironment createExecutionEnvironment(@NotNull Project project, @NotNull ExecuteRunConfigurationTask executeRunConfigurationTask, @Nullable Executor executor) {
    if (!isApplicable(executeRunConfigurationTask))
        return null;
    ApplicationConfiguration applicationConfiguration = (ApplicationConfiguration) executeRunConfigurationTask.getRunProfile();
    PsiClass mainClass = applicationConfiguration.getMainClass();
    if (mainClass == null)
        return null;
    VirtualFile virtualFile = mainClass.getContainingFile().getVirtualFile();
    Module module = ProjectFileIndex.SERVICE.getInstance(project).getModuleForFile(virtualFile);
    if (module == null)
        return null;
    final JavaParameters params = new JavaParameters();
    JavaParametersUtil.configureConfiguration(params, applicationConfiguration);
    params.getVMParametersList().addParametersString(applicationConfiguration.getVMParameters());
    String javaExePath = null;
    try {
        final Sdk jdk = JavaParametersUtil.createProjectJdk(project, applicationConfiguration.getAlternativeJrePath());
        if (jdk == null)
            throw new RuntimeException(ExecutionBundle.message("run.configuration.error.no.jdk.specified"));
        final SdkTypeId type = jdk.getSdkType();
        if (!(type instanceof JavaSdkType))
            throw new RuntimeException(ExecutionBundle.message("run.configuration.error.no.jdk.specified"));
        javaExePath = ((JavaSdkType) type).getVMExecutablePath(jdk);
        if (javaExePath == null)
            throw new RuntimeException(ExecutionBundle.message("run.configuration.cannot.find.vm.executable"));
        javaExePath = FileUtil.toSystemIndependentName(javaExePath);
    } catch (CantRunException e) {
        ExecutionErrorDialog.show(e, "Cannot use specified JRE", project);
    }
    StringBuilder parametersString = new StringBuilder();
    for (String parameter : params.getProgramParametersList().getParameters()) {
        parametersString.append("args '").append(parameter).append("'\n");
    }
    StringBuilder vmParametersString = new StringBuilder();
    for (String parameter : params.getVMParametersList().getParameters()) {
        vmParametersString.append("jvmArgs '").append(parameter).append("'\n");
    }
    ExternalSystemTaskExecutionSettings taskSettings = new ExternalSystemTaskExecutionSettings();
    taskSettings.setExternalSystemIdString(GradleConstants.SYSTEM_ID.getId());
    taskSettings.setExternalProjectPath(ExternalSystemApiUtil.getExternalProjectPath(module));
    final String runAppTaskName = "run " + mainClass.getName();
    taskSettings.setTaskNames(Collections.singletonList(runAppTaskName));
    String executorId = executor == null ? DefaultRunExecutor.EXECUTOR_ID : executor.getId();
    ExecutionEnvironment environment = ExternalSystemUtil.createExecutionEnvironment(project, GradleConstants.SYSTEM_ID, taskSettings, executorId);
    if (environment != null) {
        RunnerAndConfigurationSettings runnerAndConfigurationSettings = environment.getRunnerAndConfigurationSettings();
        assert runnerAndConfigurationSettings != null;
        ExternalSystemRunConfiguration runConfiguration = (ExternalSystemRunConfiguration) runnerAndConfigurationSettings.getConfiguration();
        final String gradlePath = GradleProjectResolverUtil.getGradlePath(module);
        if (gradlePath == null)
            return null;
        final String sourceSetName;
        if (GradleConstants.GRADLE_SOURCE_SET_MODULE_TYPE_KEY.equals(ExternalSystemApiUtil.getExternalModuleType(module))) {
            sourceSetName = GradleProjectResolverUtil.getSourceSetName(module);
        } else {
            sourceSetName = ModuleRootManager.getInstance(module).getFileIndex().isInTestSourceContent(virtualFile) ? "test" : "main";
        }
        if (sourceSetName == null)
            return null;
        @Language("Groovy") String initScript = "projectsEvaluated {\n" + "  rootProject.allprojects {\n" + "    if(project.path == '" + gradlePath + "' && project.sourceSets) {\n" + "      project.tasks.create(name: '" + runAppTaskName + "', overwrite: true, type: JavaExec) {\n" + (javaExePath != null ? "        executable = '" + javaExePath + "'\n" : "") + "        classpath = project.sourceSets.'" + sourceSetName + "'.runtimeClasspath\n" + "        main = '" + mainClass.getQualifiedName() + "'\n" + parametersString.toString() + vmParametersString.toString() + "      }\n" + "    }\n" + "  }\n" + "}\n";
        runConfiguration.putUserData(GradleTaskManager.INIT_SCRIPT_KEY, initScript);
        return environment;
    } else {
        return null;
    }
}
Also used : VirtualFile(com.intellij.openapi.vfs.VirtualFile) ExecutionEnvironment(com.intellij.execution.runners.ExecutionEnvironment) PsiClass(com.intellij.psi.PsiClass) ExternalSystemRunConfiguration(com.intellij.openapi.externalSystem.service.execution.ExternalSystemRunConfiguration) JavaSdkType(com.intellij.openapi.projectRoots.JavaSdkType) CantRunException(com.intellij.execution.CantRunException) Language(org.intellij.lang.annotations.Language) JavaParameters(com.intellij.execution.configurations.JavaParameters) RunnerAndConfigurationSettings(com.intellij.execution.RunnerAndConfigurationSettings) Sdk(com.intellij.openapi.projectRoots.Sdk) SdkTypeId(com.intellij.openapi.projectRoots.SdkTypeId) Module(com.intellij.openapi.module.Module) ApplicationConfiguration(com.intellij.execution.application.ApplicationConfiguration) ExternalSystemTaskExecutionSettings(com.intellij.openapi.externalSystem.model.execution.ExternalSystemTaskExecutionSettings) Nullable(org.jetbrains.annotations.Nullable)

Example 17 with CantRunException

use of com.intellij.execution.CantRunException in project intellij-community by JetBrains.

the class SearchingForTestsTask method composeTestSuiteFromXml.

private void composeTestSuiteFromXml() throws CantRunException {
    final Map<String, String> buildTestParams = buildTestParameters();
    try {
        if (buildTestParams.isEmpty()) {
            String path = new File(myData.getSuiteName()).getAbsolutePath() + "\n";
            FileUtil.writeToFile(myTempFile, path.getBytes(CharsetToolkit.UTF8_CHARSET), true);
            return;
        }
        final Parser parser = new Parser(myData.getSuiteName());
        parser.setLoadClasses(false);
        final Collection<XmlSuite> suites = parser.parse();
        for (XmlSuite suite : suites) {
            Map<String, String> params = suite.getParameters();
            params.putAll(buildTestParams);
            final String fileId = FileUtil.sanitizeFileName(myProject.getName() + '_' + suite.getName() + '_' + Integer.toHexString(suite.getName().hashCode()) + ".xml");
            final File suiteFile = new File(PathManager.getSystemPath(), fileId);
            FileWriter fileWriter = new FileWriter(suiteFile);
            try {
                fileWriter.write(suite.toXml());
            } finally {
                fileWriter.close();
            }
            String path = suiteFile.getAbsolutePath() + "\n";
            FileUtil.writeToFile(myTempFile, path.getBytes(CharsetToolkit.UTF8_CHARSET), true);
        }
    } catch (Exception e) {
        throw new CantRunException("Unable to parse suite: " + e.getMessage());
    }
}
Also used : CantRunException(com.intellij.execution.CantRunException) XmlSuite(org.testng.xml.XmlSuite) ExecutionException(com.intellij.execution.ExecutionException) CantRunException(com.intellij.execution.CantRunException) Parser(org.testng.xml.Parser)

Example 18 with CantRunException

use of com.intellij.execution.CantRunException in project intellij-community by JetBrains.

the class TestDirectory method getPackage.

@Override
protected PsiPackage getPackage(JUnitConfiguration.Data data) throws CantRunException {
    final String dirName = data.getDirName();
    final VirtualFile file = LocalFileSystem.getInstance().findFileByPath(FileUtil.toSystemIndependentName(dirName));
    if (file == null) {
        throw new CantRunException("Directory \'" + dirName + "\' is not found");
    }
    final PsiDirectory directory = PsiManager.getInstance(getConfiguration().getProject()).findDirectory(file);
    if (directory == null) {
        throw new CantRunException("Directory \'" + dirName + "\' is not found");
    }
    return null;
}
Also used : VirtualFile(com.intellij.openapi.vfs.VirtualFile) CantRunException(com.intellij.execution.CantRunException)

Example 19 with CantRunException

use of com.intellij.execution.CantRunException in project intellij-community by JetBrains.

the class TestNGTestPattern method fillTestObjects.

public static void fillTestObjects(final Map<PsiClass, Map<PsiMethod, List<String>>> classes, final Set<String> patterns, final TestSearchScope testSearchScope, final ModuleBasedConfiguration config, final GlobalSearchScope searchScope) throws CantRunException {
    for (final String pattern : patterns) {
        final String className;
        final String methodName;
        if (pattern.contains(",")) {
            methodName = StringUtil.getShortName(pattern, ',');
            className = StringUtil.getPackageName(pattern, ',');
        } else {
            className = pattern;
            methodName = null;
        }
        final PsiClass psiClass = ApplicationManager.getApplication().runReadAction(new Computable<PsiClass>() {

            @Nullable
            @Override
            public PsiClass compute() {
                return ClassUtil.findPsiClass(PsiManager.getInstance(config.getProject()), className.replace('/', '.'), null, true, searchScope);
            }
        });
        if (psiClass != null) {
            final Boolean hasTest = ApplicationManager.getApplication().runReadAction(new Computable<Boolean>() {

                @Override
                public Boolean compute() {
                    return TestNGUtil.hasTest(psiClass);
                }
            });
            if (hasTest) {
                if (StringUtil.isEmpty(methodName)) {
                    calculateDependencies(null, classes, searchScope, psiClass);
                } else {
                    collectTestMethods(classes, psiClass, methodName, searchScope);
                }
            } else {
                throw new CantRunException("No tests found in class " + className);
            }
        }
    }
    if (classes.size() != patterns.size()) {
        final List<Pattern> compilePatterns = new ArrayList<>();
        for (String p : patterns) {
            final Pattern compilePattern;
            try {
                compilePattern = Pattern.compile(p);
            } catch (PatternSyntaxException e) {
                continue;
            }
            compilePatterns.add(compilePattern);
        }
        final SourceScope sourceScope = testSearchScope.getSourceScope(config);
        TestClassFilter projectFilter = new TestClassFilter(sourceScope != null ? sourceScope.getGlobalSearchScope() : GlobalSearchScope.allScope(config.getProject()), config.getProject(), true, true) {

            @Override
            public boolean isAccepted(PsiClass psiClass) {
                if (super.isAccepted(psiClass)) {
                    final String qualifiedName = ReadAction.compute(psiClass::getQualifiedName);
                    LOG.assertTrue(qualifiedName != null);
                    for (Pattern pattern : compilePatterns) {
                        if (pattern.matcher(qualifiedName).matches())
                            return true;
                    }
                }
                return false;
            }
        };
        calculateDependencies(null, classes, searchScope, TestNGUtil.getAllTestClasses(projectFilter, false));
        if (classes.size() == 0) {
            throw new CantRunException("No tests found in for patterns \"" + StringUtil.join(patterns, " || ") + '\"');
        }
    }
}
Also used : Pattern(java.util.regex.Pattern) PsiClass(com.intellij.psi.PsiClass) ArrayList(java.util.ArrayList) CantRunException(com.intellij.execution.CantRunException) SourceScope(com.intellij.execution.testframework.SourceScope) Nullable(org.jetbrains.annotations.Nullable) PatternSyntaxException(java.util.regex.PatternSyntaxException)

Example 20 with CantRunException

use of com.intellij.execution.CantRunException in project intellij-community by JetBrains.

the class JavaParameters method getJdkPath.

public String getJdkPath() throws CantRunException {
    final Sdk jdk = getJdk();
    if (jdk == null) {
        throw new CantRunException(ExecutionBundle.message("no.jdk.specified..error.message"));
    }
    final VirtualFile jdkHome = jdk.getHomeDirectory();
    if (jdkHome == null) {
        throw new CantRunException(ExecutionBundle.message("home.directory.not.specified.for.jdk.error.message"));
    }
    return jdkHome.getPresentableUrl();
}
Also used : VirtualFile(com.intellij.openapi.vfs.VirtualFile) CantRunException(com.intellij.execution.CantRunException) Sdk(com.intellij.openapi.projectRoots.Sdk)

Aggregations

CantRunException (com.intellij.execution.CantRunException)22 VirtualFile (com.intellij.openapi.vfs.VirtualFile)10 Sdk (com.intellij.openapi.projectRoots.Sdk)7 Module (com.intellij.openapi.module.Module)5 File (java.io.File)5 Nullable (org.jetbrains.annotations.Nullable)5 ExecutionException (com.intellij.execution.ExecutionException)4 GeneralCommandLine (com.intellij.execution.configurations.GeneralCommandLine)4 JavaParameters (com.intellij.execution.configurations.JavaParameters)4 IOException (java.io.IOException)4 ParametersList (com.intellij.execution.configurations.ParametersList)3 ProgressIndicator (com.intellij.openapi.progress.ProgressIndicator)3 Task (com.intellij.openapi.progress.Task)3 SourceScope (com.intellij.execution.testframework.SourceScope)2 IdeaPluginDescriptor (com.intellij.ide.plugins.IdeaPluginDescriptor)2 PluginId (com.intellij.openapi.extensions.PluginId)2 Project (com.intellij.openapi.project.Project)2 JavaSdkType (com.intellij.openapi.projectRoots.JavaSdkType)2 SdkTypeId (com.intellij.openapi.projectRoots.SdkTypeId)2 PsiClass (com.intellij.psi.PsiClass)2