public void testAllInPackageForProject() throws IOException, ExecutionException {
    // module1 -> module2 -> module3
    // module5
    addModule("module5");
    addDependency(getModule1(), getModule2());
    addDependency(getModule2(), getModule3());
    String[][] outputs = new String[4][];
    for (int i = 0; i < 4; i++) {
      outputs[i] = addOutputs(getModule(i), i + 1);
    }

    PsiPackage defaultPackage = JavaPsiFacade.getInstance(myProject).findPackage("");
    JUnitConfiguration configuration =
        createJUnitConfiguration(
            defaultPackage, AllInPackageConfigurationProducer.class, new MapDataContext());
    configuration.getPersistentData().setScope(TestSearchScope.WHOLE_PROJECT);
    JavaParameters javaParameters = checkCanRun(configuration);
    String classPath = javaParameters.getClassPath().getPathsString();
    assertEquals(-1, classPath.indexOf(JarFileSystem.PROTOCOL_PREFIX));
    assertEquals(-1, classPath.indexOf(LocalFileSystem.PROTOCOL_PREFIX));
    for (int i = 0; i < 4; i++) {
      checkContains(classPath, outputs[i][0]);
      checkContains(classPath, outputs[i][1]);
    }
  }
  public void testTestClassPathWhenRunningConfigurations() throws IOException, ExecutionException {
    addModule("module4", false);
    Module module4 = getModule4();
    assignJdk(module4);
    addSourcePath(module4, "testSrc", true);
    addSourcePath(module4, "src", false);
    String output = setCompilerOutput(module4, "classes", false);
    String testOuput = setCompilerOutput(module4, "testClasses", true);

    ApplicationConfiguration applicationConfiguration =
        createConfiguration(findClass(module4, "Application"));
    JavaParameters parameters = checkCanRun(applicationConfiguration);
    String classPath = parameters.getClassPath().getPathsString();
    checkDoesNotContain(classPath, testOuput);
    checkContains(classPath, output);

    JUnitConfiguration junitConfiguration =
        createJUnitConfiguration(
            findClass(module4, "TestApplication"),
            TestClassConfigurationProducer.class,
            new MapDataContext());
    parameters = checkCanRun(junitConfiguration);
    classPath = parameters.getClassPath().getPathsString();
    checkContains(classPath, testOuput);
    checkContains(classPath, output);

    applicationConfiguration.MAIN_CLASS_NAME =
        junitConfiguration.getPersistentData().getMainClassName();
    classPath = checkCanRun(applicationConfiguration).getClassPath().getPathsString();
    checkContains(classPath, testOuput);
    checkContains(classPath, output);
  }
  @Nullable
  public static PathsList getClassPathFromRootModel(
      Module module,
      boolean isTests,
      JavaParameters params,
      boolean allowDuplication,
      PathsList pathList)
      throws CantRunException {
    if (module == null) {
      return null;
    }

    final JavaParameters tmp = new JavaParameters();
    tmp.configureByModule(
        module, isTests ? JavaParameters.CLASSES_AND_TESTS : JavaParameters.CLASSES_ONLY);
    if (tmp.getClassPath().getVirtualFiles().isEmpty()) {
      return null;
    }

    Set<VirtualFile> core = new HashSet<VirtualFile>(params.getClassPath().getVirtualFiles());

    for (VirtualFile virtualFile : tmp.getClassPath().getVirtualFiles()) {
      if (allowDuplication || !core.contains(virtualFile)) {
        pathList.add(virtualFile);
      }
    }
    return pathList;
  }
 public void testClasspathConfiguration() throws CantRunException {
   JavaParameters parameters = new JavaParameters();
   RunConfigurationModule module = new JavaRunConfigurationModule(myProject, false);
   Module module1 = getModule1();
   Module module2 = getModule2();
   addDependency(module1, module2);
   Module module3 = getModule3();
   addDependency(module2, module3);
   addDependency(module1, module3);
   addOutputs(module1, 1);
   addOutputs(module2, 2);
   addOutputs(module3, 3);
   module.setModule(module1);
   parameters.configureByModule(module.getModule(), JavaParameters.JDK_AND_CLASSES_AND_TESTS);
   ArrayList<String> classPath = new ArrayList<>();
   StringTokenizer tokenizer =
       new StringTokenizer(parameters.getClassPath().getPathsString(), File.pathSeparator);
   while (tokenizer.hasMoreTokens()) {
     String token = tokenizer.nextToken();
     classPath.add(token);
   }
   CHECK.singleOccurence(classPath, getOutput(module1, false));
   CHECK.singleOccurence(classPath, getOutput(module1, false));
   CHECK.singleOccurence(classPath, getOutput(module1, true));
   CHECK.singleOccurence(classPath, getOutput(module2, false));
   CHECK.singleOccurence(classPath, getOutput(module2, true));
   CHECK.singleOccurence(classPath, getOutput(module3, false));
   CHECK.singleOccurence(classPath, getOutput(module3, true));
   CHECK.singleOccurence(classPath, getFSPath(findFile(MOCK_JUNIT)));
 }
  private JavaParameters createJavaParameters() throws ExecutionException {
    JavaParameters parameters = new JavaParameters();
    Sdk sdk = JavaAwareProjectJdkTableImpl.getInstanceEx().getInternalJdk();
    if (sdk == null) {
      throw new ExecutionException("No Java SDK available.");
    }
    parameters.setJdk(sdk);
    parameters.setMainClass(AbstractPaxBasedFrameworkRunner.PaxRunnerMainClass);
    PathsList classpath = parameters.getClassPath();
    for (VirtualFile libraryFile : AbstractPaxBasedFrameworkRunner.getPaxLibraries()) {
      classpath.add(libraryFile);
    }

    ParametersList parametersList = parameters.getProgramParametersList();
    parametersList.add("--p=" + myFrameworkType);
    if (!StringUtil.isEmpty(myVersion)) {
      parametersList.add("--v=" + myVersion);
    }
    parametersList.add("--nologo=true");
    parametersList.add("--executor=noop");
    parametersList.add("--workingDirectory=" + myTargetFolder);
    if (myClearDownloadFolder) {
      parametersList.add("--clean");
    }
    if (!StringUtil.isEmpty(myProfiles)) {
      parametersList.add("--profiles=" + myProfiles);
    }
    return parameters;
  }
  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);
    }
  }
 protected JavaParameters createJavaParameters(String mainClass) {
   JavaParameters parameters = new JavaParameters();
   parameters.getClassPath().add(getAppOutputPath());
   parameters.setMainClass(mainClass);
   parameters.setJdk(JavaAwareProjectJdkTableImpl.getInstanceEx().getInternalJdk());
   parameters.setWorkingDirectory(getTestAppPath());
   return parameters;
 }
 public static void setGroovyHome(JavaParameters params, @NotNull String groovyHome) {
   params.getVMParametersList().add("-Dgroovy.home=" + groovyHome);
   if (groovyHome.contains("grails")) { // a bit of a hack
     params.getVMParametersList().add("-Dgrails.home=" + groovyHome);
   }
   if (groovyHome.contains("griffon")) { // a bit of a hack
     params.getVMParametersList().add("-Dgriffon.home=" + groovyHome);
   }
 }
 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 void updateJavaParameters(
     RunConfigurationBase configuration, JavaParameters params, RunnerSettings runnerSettings) {
   if (runnerSettings != null || !isApplicableFor(configuration)) {
     return;
   }
   StringBuilder argument = new StringBuilder("-javaagent:");
   final String agentPath = PathUtil.getJarPathForClass(ProjectData.class); // todo spaces
   argument.append(agentPath);
   params.getVMParametersList().add(argument.toString());
   params.getClassPath().add(agentPath);
   params
       .getVMParametersList()
       .addProperty(ProjectData.TRACE_DIR, getTracesDirectory(configuration));
 }
Exemplo n.º 11
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;
  }
 /* 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"));
     }
   }
 }
 protected void createServerSocket(JavaParameters javaParameters) {
   try {
     myServerSocket = new ServerSocket(0, 0, InetAddress.getByName("127.0.0.1"));
     javaParameters.getProgramParametersList().add("-socket" + myServerSocket.getLocalPort());
   } catch (IOException e) {
     LOG.error(e);
   }
 }
  public void testSameTestAndCommonOutput() throws IOException, ExecutionException {
    addModule("module4", false);
    Module module = getModule4();
    assignJdk(module);
    addSourcePath(module, "src", false);
    addSourcePath(module, "testSrc", false);
    String output = setCompilerOutput(module, "classes", false);
    assertEquals(output, setCompilerOutput(module, "classes", true));

    RunConfiguration configuration = createConfiguration(findClass(module, "Application"));
    JavaParameters javaParameters = checkCanRun(configuration);
    checkContains(javaParameters.getClassPath().getPathsString(), output);

    configuration = createConfiguration(findClass(module, "TestApplication"));
    javaParameters = checkCanRun(configuration);
    checkContains(javaParameters.getClassPath().getPathsString(), output);
  }
 protected void createTempFiles(JavaParameters javaParameters) {
   try {
     myTempFile = FileUtil.createTempFile("idea_" + getFrameworkId(), ".tmp");
     myTempFile.deleteOnExit();
     passTempFile(javaParameters.getProgramParametersList(), myTempFile.getAbsolutePath());
   } catch (IOException e) {
     LOG.error(e);
   }
 }
 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));
     }
   }
 }
Exemplo n.º 18
0
  private void appendForkInfo(Executor executor) throws ExecutionException {
    final String forkMode = myConfiguration.getForkMode();
    if (Comparing.strEqual(forkMode, "none")) {
      return;
    }

    if (getRunnerSettings().getData() != null) {
      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()
              + ".");
    }

    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, "UTF-8");
      try {
        writer.println(((JavaSdkType) jdk.getSdkType()).getVMExecutablePath(jdk));
        for (String vmParameter : javaParameters.getVMParametersList().getList()) {
          writer.println(vmParameter);
        }
        writer.println("-classpath");
        writer.println(javaParameters.getClassPath().getPathsString());
      } finally {
        writer.close();
      }

      myJavaParameters
          .getProgramParametersList()
          .add("@@@" + forkMode + ',' + tempFile.getAbsolutePath());
    } catch (Exception e) {
      LOG.error(e);
    }
  }
  protected static void addClasspathFromRootModel(
      @Nullable Module module, boolean isTests, JavaParameters params, boolean allowDuplication)
      throws CantRunException {
    PathsList nonCore = new PathsList();
    getClassPathFromRootModel(module, isTests, params, allowDuplication, nonCore);
    nonCore.add(".");

    final String cp = nonCore.getPathsString();
    if (!StringUtil.isEmptyOrSpaces(cp)) {
      params.getProgramParametersList().add("--classpath");
      params.getProgramParametersList().add(cp);
    }
  }
  @Override
  protected JavaParameters createJavaParameters() throws ExecutionException {
    final JavaParameters javaParameters = new JavaParameters();
    final Module module = getConfiguration().getConfigurationModule().getModule();

    Project project = getConfiguration().getProject();
    Sdk jdk =
        module == null
            ? ProjectRootManager.getInstance(project).getProjectSdk()
            : ModuleRootManager.getInstance(module).getSdk();
    javaParameters.setJdk(jdk);

    final Object[] patchers = Extensions.getExtensions(ExtensionPoints.JUNIT_PATCHER);
    for (Object patcher : patchers) {
      ((JUnitPatcher) patcher).patchJavaParameters(module, javaParameters);
    }

    // Append coverage parameters if appropriate
    for (RunConfigurationExtension ext :
        Extensions.getExtensions(RunConfigurationExtension.EP_NAME)) {
      ext.updateJavaParameters(getConfiguration(), javaParameters, getRunnerSettings());
    }

    final String parameters = getConfiguration().getProgramParameters();
    getConfiguration().setProgramParameters(null);
    try {
      JavaParametersUtil.configureConfiguration(javaParameters, getConfiguration());
    } finally {
      getConfiguration().setProgramParameters(parameters);
    }
    javaParameters.getClassPath().addFirst(JavaSdkUtil.getIdeaRtJarPath());
    configureClasspath(javaParameters);

    if (!StringUtil.isEmptyOrSpaces(parameters)) {
      javaParameters.getProgramParametersList().add("@name" + parameters);
    }

    return javaParameters;
  }
  private void assertClasspath(String moduleName, Scope scope, Type type, String... expectedPaths)
      throws Exception {
    createOutputDirectories();

    PathsList actualPathsList;
    Module module = getModule(moduleName);

    if (scope == Scope.RUNTIME) {
      JavaParameters params = new JavaParameters();
      params.configureByModule(
          module,
          type == Type.TESTS ? JavaParameters.CLASSES_AND_TESTS : JavaParameters.CLASSES_ONLY);
      actualPathsList = params.getClassPath();
    } else {
      OrderEnumerator en =
          OrderEnumerator.orderEntries(module).recursively().withoutSdk().compileOnly();
      if (type == Type.PRODUCTION) en.productionOnly();
      actualPathsList = en.classes().getPathsList();
    }

    assertPaths(expectedPaths, actualPathsList.getPathList());
  }
 private static List<String> extractAllInPackageTests(
     JavaParameters parameters, PsiPackage psiPackage) throws IOException {
   String filePath =
       ContainerUtil.find(
               parameters.getProgramParametersList().getArray(),
               value ->
                   StringUtil.startsWithChar(value, '@') && !StringUtil.startsWith(value, "@w@"))
           .substring(1);
   List<String> lines = readLinesFrom(new File(filePath));
   assertEquals(psiPackage.getQualifiedName(), lines.get(0));
   // lines.remove(0);
   lines.remove(0);
   return lines;
 }
  @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));
  }
Exemplo n.º 24
0
  protected void initialize() throws ExecutionException {
    JavaParametersUtil.configureConfiguration(myJavaParameters, myConfiguration);
    myJavaParameters.setMainClass(JUnitConfiguration.JUNIT_START_CLASS);
    final Module module = myConfiguration.getConfigurationModule().getModule();
    if (myJavaParameters.getJdk() == null) {
      myJavaParameters.setJdk(
          module != null
              ? ModuleRootManager.getInstance(module).getSdk()
              : ProjectRootManager.getInstance(myProject).getProjectSdk());
    }

    myJavaParameters.getClassPath().add(JavaSdkUtil.getIdeaRtJarPath());
    myJavaParameters.getClassPath().add(PathUtil.getJarPathForClass(JUnitStarter.class));
    myJavaParameters
        .getProgramParametersList()
        .add(JUnitStarter.IDE_VERSION + JUnitStarter.VERSION);
    for (RunConfigurationExtension ext :
        Extensions.getExtensions(RunConfigurationExtension.EP_NAME)) {
      ext.updateJavaParameters(myConfiguration, myJavaParameters, getRunnerSettings());
    }

    final Object[] listeners = Extensions.getExtensions(IDEAJUnitListener.EP_NAME);
    final StringBuilder buf = new StringBuilder();
    for (final Object listener : listeners) {
      boolean enabled = true;
      for (RunConfigurationExtension ext :
          Extensions.getExtensions(RunConfigurationExtension.EP_NAME)) {
        if (ext.isListenerDisabled(myConfiguration, listener, getRunnerSettings())) {
          enabled = false;
          break;
        }
      }
      if (enabled) {
        final Class classListener = listener.getClass();
        buf.append(classListener.getName()).append("\n");
        myJavaParameters.getClassPath().add(PathUtil.getJarPathForClass(classListener));
      }
    }
    if (buf.length() > 0) {
      try {
        myListenersFile = FileUtil.createTempFile("junit_listeners_", "");
        myListenersFile.deleteOnExit();
        myJavaParameters.getProgramParametersList().add("@@" + myListenersFile.getPath());
        FileUtil.writeToFile(myListenersFile, buf.toString().getBytes());
      } catch (IOException e) {
        LOG.error(e);
      }
    }
  }
 public void testRunningJUnit() throws ExecutionException {
   PsiClass testA = findTestA(getModule1());
   JUnitConfiguration configuration = createConfiguration(testA);
   JavaParameters parameters = checkCanRun(configuration);
   assertEmpty(parameters.getVMParametersList().getList());
   final SegmentedOutputStream notifications = new SegmentedOutputStream(System.out);
   assertTrue(
       JUnitStarter.checkVersion(
           parameters.getProgramParametersList().getArray(), new PrintStream(notifications)));
   assertTrue(parameters.getProgramParametersList().getList().contains(testA.getQualifiedName()));
   assertEquals(JUnitStarter.class.getName(), parameters.getMainClass());
   assertEquals(myJdk.getHomeDirectory().getPresentableUrl(), parameters.getJdkPath());
 }
  protected DebuggerSession createRemoteProcess(
      final int transport, final boolean serverMode, JavaParameters javaParameters)
      throws ExecutionException, InterruptedException, InvocationTargetException {
    boolean useSockets = transport == DebuggerSettings.SOCKET_TRANSPORT;

    RemoteConnection remoteConnection =
        new RemoteConnection(useSockets, "127.0.0.1", String.valueOf(DEFAULT_ADDRESS), serverMode);

    String launchCommandLine = remoteConnection.getLaunchCommandLine();

    launchCommandLine = StringUtil.replace(launchCommandLine, RemoteConnection.ONTHROW, "");
    launchCommandLine = StringUtil.replace(launchCommandLine, RemoteConnection.ONUNCAUGHT, "");

    launchCommandLine = StringUtil.replace(launchCommandLine, "suspend=n", "suspend=y");

    println(launchCommandLine, ProcessOutputTypes.SYSTEM);

    for (StringTokenizer tokenizer = new StringTokenizer(launchCommandLine);
        tokenizer.hasMoreTokens(); ) {
      String token = tokenizer.nextToken();
      javaParameters.getVMParametersList().add(token);
    }

    GeneralCommandLine commandLine = CommandLineBuilder.createFromJavaParameters(javaParameters);

    DebuggerSession debuggerSession;

    if (serverMode) {
      debuggerSession = attachVM(remoteConnection, false);
      commandLine.createProcess();
    } else {
      commandLine.createProcess();
      debuggerSession = attachVM(remoteConnection, true);
    }

    ProcessHandler processHandler = debuggerSession.getProcess().getProcessHandler();
    DebugProcessImpl process =
        (DebugProcessImpl)
            DebuggerManagerEx.getInstanceEx(myProject).getDebugProcess(processHandler);

    assertNotNull(process);
    return debuggerSession;
  }
 protected void collectListeners(
     JavaParameters javaParameters, StringBuilder buf, String epName, String delimiter) {
   final T configuration = getConfiguration();
   final Object[] listeners = Extensions.getExtensions(epName);
   for (final Object listener : listeners) {
     boolean enabled = true;
     for (RunConfigurationExtension ext :
         Extensions.getExtensions(RunConfigurationExtension.EP_NAME)) {
       if (ext.isListenerDisabled(configuration, listener, getRunnerSettings())) {
         enabled = false;
         break;
       }
     }
     if (enabled) {
       if (buf.length() > 0) buf.append(delimiter);
       final Class classListener = listener.getClass();
       buf.append(classListener.getName());
       javaParameters.getClassPath().add(PathUtil.getJarPathForClass(classListener));
     }
   }
 }
Exemplo n.º 28
0
  protected <T> void addClassesListToJavaParameters(
      Collection<? extends T> elements,
      Function<T, String> nameFunction,
      String packageName,
      boolean createTempFile,
      boolean junit4) {
    try {
      if (createTempFile) {
        myTempFile = FileUtil.createTempFile("idea_junit", ".tmp");
        myTempFile.deleteOnExit();
        myJavaParameters.getProgramParametersList().add("@" + myTempFile.getAbsolutePath());
      }

      final PrintWriter writer = new PrintWriter(myTempFile, "UTF-8");
      try {
        writer.println(packageName);
        final List<String> testNames = new ArrayList<String>();
        for (final T element : elements) {
          final String name = nameFunction.fun(element);
          if (name == null) {
            LOG.error("invalid element " + element);
            return;
          }
          testNames.add(name);
        }
        Collections.sort(testNames); // sort tests in FQN order
        for (String testName : testNames) {
          writer.println(testName);
        }
      } finally {
        writer.close();
      }
    } catch (IOException e) {
      LOG.error(e);
    }
  }
  @Override
  public JavaParameters createJavaParameters(
      @NotNull Module module,
      boolean forCreation,
      boolean forTests,
      boolean classpathFromDependencies,
      @Nullable String jvmParams,
      @NotNull MvcCommand command)
      throws ExecutionException {
    JavaParameters params = new JavaParameters();

    Sdk sdk = ModuleRootManager.getInstance(module).getSdk();

    params.setJdk(sdk);
    final VirtualFile sdkRoot = getSdkRoot(module);
    if (sdkRoot == null) {
      return params;
    }

    Map<String, String> env = params.getEnv();
    if (env == null) {
      env = new HashMap<String, String>();
      params.setEnv(env);
    }
    env.put(getSdkHomePropertyName(), FileUtil.toSystemDependentName(sdkRoot.getPath()));

    final VirtualFile lib = sdkRoot.findChild("lib");
    if (lib != null) {
      for (final VirtualFile child : lib.getChildren()) {
        final String name = child.getName();
        if (name.startsWith("groovy-all-") && name.endsWith(".jar")) {
          params.getClassPath().add(child);
        }
      }
    }
    final VirtualFile dist = sdkRoot.findChild("dist");
    if (dist != null) {
      for (final VirtualFile child : dist.getChildren()) {
        final String name = child.getName();
        if (name.endsWith(".jar")) {
          if (name.startsWith("griffon-cli-")
              || name.startsWith("griffon-rt-")
              || name.startsWith("griffon-resources-")) {
            params.getClassPath().add(child);
          }
        }
      }
    }

    /////////////////////////////////////////////////////////////

    params.setMainClass("org.codehaus.griffon.cli.support.GriffonStarter");

    final VirtualFile rootFile;

    if (forCreation) {
      VirtualFile[] roots = ModuleRootManager.getInstance(module).getContentRoots();
      if (roots.length != 1) {
        throw new ExecutionException(
            "Failed to initialize griffon module: module "
                + module.getName()
                + " contains more than one root");
      }

      command.getArgs().add(0, roots[0].getName());

      rootFile = roots[0].getParent();
    } else {
      rootFile = findAppRoot(module);
      if (rootFile == null) {
        throw new ExecutionException(
            "Failed to run griffon command: module "
                + module.getName()
                + " is not a Griffon module");
      }
    }

    String workDir = VfsUtilCore.virtualToIoFile(rootFile).getAbsolutePath();

    if (jvmParams != null) {
      params.getVMParametersList().addParametersString(jvmParams);
    }

    if (!params.getVMParametersList().getParametersString().contains(XMX_JVM_PARAMETER)) {
      params.getVMParametersList().add("-Xmx256M");
    }

    final String griffonHomePath = FileUtil.toSystemDependentName(sdkRoot.getPath());
    params.getVMParametersList().add("-Dgriffon.home=" + griffonHomePath);
    params.getVMParametersList().add("-Dbase.dir=" + workDir);

    assert sdk != null;
    params
        .getVMParametersList()
        .add("-Dtools.jar=" + ((JavaSdkType) sdk.getSdkType()).getToolsPath(sdk));

    final String confpath = griffonHomePath + GROOVY_STARTER_CONF;
    params.getVMParametersList().add("-Dgroovy.starter.conf=" + confpath);

    params
        .getVMParametersList()
        .add(
            "-Dgroovy.sanitized.stacktraces=\"groovy., org.codehaus.groovy., java., javax., sun., gjdk.groovy., gant., org.codehaus.gant.\"");

    params.getProgramParametersList().add("--main");
    params.getProgramParametersList().add("org.codehaus.griffon.cli.GriffonScriptRunner");
    params.getProgramParametersList().add("--conf");
    params.getProgramParametersList().add(confpath);
    if (!forCreation && classpathFromDependencies) {
      final String path = getApplicationClassPath(module).getPathsString();
      if (StringUtil.isNotEmpty(path)) {
        params.getProgramParametersList().add("--classpath");
        params.getProgramParametersList().add(path);
      }
    }

    params.setWorkingDirectory(workDir);

    ParametersList paramList = new ParametersList();
    command.addToParametersList(paramList);
    params.getProgramParametersList().add(paramList.getParametersString());

    params.setDefaultCharset(module.getProject());

    return params;
  }
  /**
   * @param project
   * @param parameters
   * @param coreSettings
   * @param runnerSettings
   * @param runConfiguration used to creation fix if maven home not found
   * @return
   * @throws ExecutionException
   */
  public static JavaParameters createJavaParameters(
      @Nullable final Project project,
      @NotNull final MavenRunnerParameters parameters,
      @Nullable MavenGeneralSettings coreSettings,
      @Nullable MavenRunnerSettings runnerSettings,
      @Nullable MavenRunConfiguration runConfiguration)
      throws ExecutionException {
    final JavaParameters params = new JavaParameters();

    ApplicationManager.getApplication().assertReadAccessAllowed();

    if (coreSettings == null) {
      coreSettings =
          project == null
              ? new MavenGeneralSettings()
              : MavenProjectsManager.getInstance(project).getGeneralSettings();
    }
    if (runnerSettings == null) {
      runnerSettings =
          project == null ? new MavenRunnerSettings() : MavenRunner.getInstance(project).getState();
    }

    params.setWorkingDirectory(parameters.getWorkingDirFile());

    params.setJdk(
        getJdk(
            project,
            runnerSettings,
            project != null && MavenRunner.getInstance(project).getState() == runnerSettings));

    final String mavenHome = resolveMavenHome(coreSettings, project, runConfiguration);

    addVMParameters(params.getVMParametersList(), mavenHome, runnerSettings);

    File confFile = MavenUtil.getMavenConfFile(new File(mavenHome));
    if (!confFile.isFile()) {
      throw new ExecutionException(
          "Configuration file is not exists in maven home: " + confFile.getAbsolutePath());
    }

    if (project != null && parameters.isResolveToWorkspace()) {
      try {
        String resolverJar = getArtifactResolverJar(MavenUtil.isMaven3(mavenHome));
        confFile = patchConfFile(confFile, resolverJar);

        File modulesPathsFile = dumpModulesPaths(project);
        params
            .getVMParametersList()
            .addProperty(MavenModuleMap.PATHS_FILE_PROPERTY, modulesPathsFile.getAbsolutePath());
      } catch (IOException e) {
        LOG.error(e);
        throw new ExecutionException("Failed to run maven configuration", e);
      }
    }

    params.getVMParametersList().addProperty("classworlds.conf", confFile.getPath());

    for (String path : getMavenClasspathEntries(mavenHome)) {
      params.getClassPath().add(path);
    }

    params.setMainClass(MAVEN_LAUNCHER_CLASS);
    EncodingManager encodingManager =
        project == null
            ? EncodingProjectManager.getInstance()
            : EncodingProjectManager.getInstance(project);
    params.setCharset(encodingManager.getDefaultCharset());

    addMavenParameters(
        params.getProgramParametersList(), mavenHome, coreSettings, runnerSettings, parameters);

    return params;
  }