private static String getArtifactResolverJar(boolean isMaven3) throws IOException {
    Class marker =
        isMaven3 ? MavenArtifactResolvedM3RtMarker.class : MavenArtifactResolvedM2RtMarker.class;

    File classDirOrJar = new File(PathUtil.getJarPathForClass(marker));

    if (!classDirOrJar.isDirectory()) {
      return classDirOrJar.getAbsolutePath(); // it's a jar in IDEA installation.
    }

    // it's a classes directory, we are in development mode.
    File tempFile = FileUtil.createTempFile("idea-", "-artifactResolver.jar");
    tempFile.deleteOnExit();

    ZipOutputStream zipOutput = new ZipOutputStream(new FileOutputStream(tempFile));
    try {
      ZipUtil.addDirToZipRecursively(zipOutput, null, classDirOrJar, "", null, null);

      if (isMaven3) {
        File m2Module = new File(PathUtil.getJarPathForClass(MavenModuleMap.class));

        String commonClassesPath = MavenModuleMap.class.getPackage().getName().replace('.', '/');
        ZipUtil.addDirToZipRecursively(
            zipOutput, null, new File(m2Module, commonClassesPath), commonClassesPath, null, null);
      }
    } finally {
      zipOutput.close();
    }

    return tempFile.getAbsolutePath();
  }
 @Override
 protected void tuneFixture(JavaModuleFixtureBuilder moduleBuilder) throws Exception {
   String pathForClass = PathUtil.getJarPathForClass(LocalInspectionEP.class);
   moduleBuilder.addLibrary("lang-api", pathForClass);
   String platformApiJar = PathUtil.getJarPathForClass(JBList.class);
   moduleBuilder.addLibrary("platform-api", platformApiJar);
 }
  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);
    }
  }
 public void testExtractDirectoryFromExcludedJar() throws IOException {
   String jarPath = createFile("dir/lib/j.jar");
   FileUtil.copy(new File(getJUnitJarPath()), new File(jarPath));
   JpsModule module = addModule("m");
   String libDir = PathUtil.getParentPath(jarPath);
   module.getContentRootsList().addUrl(JpsPathUtil.pathToUrl(PathUtil.getParentPath(libDir)));
   module.getExcludeRootsList().addUrl(JpsPathUtil.pathToUrl(libDir));
   final JpsArtifact a = addArtifact("a", root().extractedDir(jarPath, "/junit/textui/"));
   buildAll();
   assertOutput(a, fs().file("ResultPrinter.class").file("TestRunner.class"));
 }
 public void testBuildModuleBeforeArtifactIfSomeDirectoryInsideModuleOutputIsCopiedToArtifact() {
   String src =
       PathUtil.getParentPath(
           PathUtil.getParentPath(createFile("src/x/A.java", "package x; class A{}")));
   JpsModule module = addModule("m", src);
   File output = JpsJavaExtensionService.getInstance().getOutputDirectory(module, false);
   JpsArtifact artifact = addArtifact(root().dirCopy(new File(output, "x").getAbsolutePath()));
   rebuildAll();
   assertOutput(module, fs().dir("x").file("A.class"));
   assertOutput(artifact, fs().file("A.class"));
 }
  public ModuleImpl(@NotNull String filePath, @NotNull Project project) {
    super(project, "Module " + moduleNameByFileName(PathUtil.getFileName(filePath)));

    getPicoContainer().registerComponentInstance(Module.class, this);

    myProject = project;
    myModuleScopeProvider = new ModuleScopeProviderImpl(this);

    myName = moduleNameByFileName(PathUtil.getFileName(filePath));

    VirtualFileManager.getInstance().addVirtualFileListener(new MyVirtualFileListener(), this);
  }
 public void testTwoDirsInArchive() {
   final String dir1 = PathUtil.getParentPath(PathUtil.getParentPath(createFile("dir1/a/x.txt")));
   final String dir2 = PathUtil.getParentPath(PathUtil.getParentPath(createFile("dir2/a/y.txt")));
   final JpsArtifact a =
       addArtifact(
           root()
               .archive("a.jar")
               .dirCopy(dir1)
               .dirCopy(dir2)
               .dir("a")
               .fileCopy(createFile("z.txt")));
   buildAll();
   assertOutput(a, fs().archive("a.jar").dir("a").file("x.txt").file("y.txt").file("z.txt"));
 }
  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 testCopyExcludedFolder() {
    // explicitly added excluded files should be copied (e.g. compile output)
    final String file = createFile("xxx/excluded/a.txt");
    createFile("xxx/excluded/CVS");
    final String excluded = PathUtil.getParentPath(file);
    final String dir = PathUtil.getParentPath(excluded);

    final JpsModule module = addModule("myModule");
    module.getContentRootsList().addUrl(JpsPathUtil.pathToUrl(dir));
    module.getExcludeRootsList().addUrl(JpsPathUtil.pathToUrl(excluded));

    final JpsArtifact a = addArtifact(root().dirCopy(excluded));
    buildAll();
    assertOutput(a, fs().file("a.txt"));
  }
  public void testCopyExcludedFile() {
    // excluded files under non-excluded directory should not be copied
    final String file = createFile("xxx/excluded/a.txt");
    createFile("xxx/b.txt");
    createFile("xxx/CVS");
    final String dir = PathUtil.getParentPath(PathUtil.getParentPath(file));

    JpsModule module = addModule("myModule");
    module.getContentRootsList().addUrl(JpsPathUtil.pathToUrl(dir));
    module.getExcludeRootsList().addUrl(JpsPathUtil.pathToUrl(PathUtil.getParentPath(file)));

    final JpsArtifact a = addArtifact(root().dirCopy(dir));
    buildAll();
    assertOutput(a, fs().file("b.txt"));
  }
  @NotNull
  private static Map<Module, String> collectJpsPluginModules(@NotNull Module module) {
    XmlFile pluginXml = PluginModuleType.getPluginXml(module);
    if (pluginXml == null) return Collections.emptyMap();

    DomFileElement<IdeaPlugin> fileElement =
        DomManager.getDomManager(module.getProject()).getFileElement(pluginXml, IdeaPlugin.class);
    if (fileElement == null) return Collections.emptyMap();

    Map<Module, String> jpsPluginToOutputPath = new HashMap<Module, String>();
    IdeaPlugin plugin = fileElement.getRootElement();
    List<Extensions> extensions = plugin.getExtensions();
    for (Extensions extensionGroup : extensions) {
      XmlTag extensionsTag = extensionGroup.getXmlTag();
      String defaultExtensionNs = extensionsTag.getAttributeValue("defaultExtensionNs");
      for (XmlTag tag : extensionsTag.getSubTags()) {
        String name = tag.getLocalName();
        String qualifiedName = defaultExtensionNs != null ? defaultExtensionNs + "." + name : name;
        if (CompileServerPlugin.EP_NAME.getName().equals(qualifiedName)) {
          String classpath = tag.getAttributeValue("classpath");
          if (classpath != null) {
            for (String path : StringUtil.split(classpath, ";")) {
              String moduleName = FileUtil.getNameWithoutExtension(PathUtil.getFileName(path));
              Module jpsModule =
                  ModuleManager.getInstance(module.getProject()).findModuleByName(moduleName);
              if (jpsModule != null) {
                jpsPluginToOutputPath.put(jpsModule, path);
              }
            }
          }
        }
      }
    }
    return jpsPluginToOutputPath;
  }
 public void testIgnoredFileInArchive() {
   final String file = createFile("a/.svn/a.txt");
   createFile("a/svn/b.txt");
   final JpsArtifact a = addArtifact(archive("a.jar").parentDirCopy(PathUtil.getParentPath(file)));
   buildAll();
   assertOutput(a, fs().archive("a.jar").dir("svn").file("b.txt"));
 }
 public AntHectorConfigurable(XmlFile file) {
   myFile = file;
   myProject = file.getProject();
   final VirtualFile selfVFile = myFile.getVirtualFile();
   myLocalPath = PathUtil.getLocalPath(selfVFile);
   myFileFilter = GlobalSearchScope.projectScope(myProject);
 }
Beispiel #14
0
    @Override
    public void run(@NotNull ProgressIndicator indicator) {
      try {
        SAXTransformerFactory transformerFactory =
            (SAXTransformerFactory) TransformerFactory.newInstance();
        TransformerHandler handler = transformerFactory.newTransformerHandler();
        handler.getTransformer().setOutputProperty(OutputKeys.INDENT, "yes");
        handler
            .getTransformer()
            .setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");

        final String configurationNameIncludedDate =
            PathUtil.suggestFileName(myConfiguration.getName())
                + " - "
                + new SimpleDateFormat(HISTORY_DATE_FORMAT).format(new Date());

        myOutputFile =
            new File(
                AbstractImportTestsAction.getTestHistoryRoot(myProject),
                configurationNameIncludedDate + ".xml");
        FileUtilRt.createParentDirs(myOutputFile);
        handler.setResult(new StreamResult(new FileWriter(myOutputFile)));
        final SMTestProxy.SMRootTestProxy root = myRoot;
        final RunConfiguration configuration = myConfiguration;
        if (root != null && configuration != null) {
          TestResultsXmlFormatter.execute(root, configuration, myConsoleProperties, handler);
        }
      } catch (ProcessCanceledException e) {
        throw e;
      } catch (Exception e) {
        LOG.info("Export to history failed", e);
      }
    }
  @Override
  protected void setUp() throws Exception {
    if (ourOutputRoot == null) {
      ourOutputRoot = FileUtil.createTempDirectory("ExecutionTestCase", null, true);
    }
    myModuleOutputDir = new File(ourOutputRoot, PathUtil.getFileName(getTestAppPath()));
    myChecker = initOutputChecker();
    EdtTestUtil.runInEdtAndWait(
        new ThrowableRunnable<Throwable>() {
          @Override
          public void run() throws Throwable {
            ExecutionTestCase.super.setUp();
          }
        });
    if (!myModuleOutputDir.exists()) {
      VirtualFile vDir = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(ourOutputRoot);
      assertNotNull(ourOutputRoot.getAbsolutePath(), vDir);
      vDir
          .getChildren(); // we need this to load children to VFS to fire VFileCreatedEvent for the
                          // output directory

      myCompilerTester =
          new CompilerTester(
              myProject, Arrays.asList(ModuleManager.getInstance(myProject).getModules()));
      List<CompilerMessage> messages = myCompilerTester.rebuild();
      for (CompilerMessage message : messages) {
        if (message.getCategory() == CompilerMessageCategory.ERROR) {
          FileUtil.delete(myModuleOutputDir);
          fail("Compilation failed: " + message);
        }
      }
    }
  }
  public void testModuleOutput() {
    final String file = createFile("src/A.java", "public class A {}");
    final JpsModule module = addModule("a", PathUtil.getParentPath(file));
    final JpsArtifact artifact = addArtifact(root().module(module));

    buildArtifacts(artifact);
    assertOutput(artifact, fs().file("A.class"));
  }
 public static File getCompilerSystemDirectory() {
   //noinspection HardCodedStringLiteral
   final String systemPath =
       ourSystemPath != null
           ? ourSystemPath
           : (ourSystemPath = PathUtil.getCanonicalPath(PathManager.getSystemPath()));
   return new File(systemPath, "compiler");
 }
  private void doTestFor(
      Map<String, PsiFile> pathToFile, final IntentionAction intentionAction, String fileText)
      throws Exception {
    String isApplicableString =
        InTextDirectivesUtils.findStringWithPrefixes(fileText, "// IS_APPLICABLE: ");
    boolean isApplicableExpected = isApplicableString == null || isApplicableString.equals("true");

    Assert.assertTrue(
        "isAvailable() for "
            + intentionAction.getClass()
            + " should return "
            + isApplicableExpected,
        isApplicableExpected == intentionAction.isAvailable(getProject(), getEditor(), getFile()));

    String intentionTextString =
        InTextDirectivesUtils.findStringWithPrefixes(fileText, "// INTENTION_TEXT: ");

    if (intentionTextString != null) {
      assertEquals("Intention text mismatch.", intentionTextString, intentionAction.getText());
    }

    String shouldFailString =
        InTextDirectivesUtils.findStringWithPrefixes(fileText, "// SHOULD_FAIL_WITH: ");

    try {
      if (isApplicableExpected) {
        ApplicationPackage.executeWriteCommand(
            getProject(),
            intentionAction.getText(),
            new Function0<Object>() {
              @Override
              public Object invoke() {
                intentionAction.invoke(getProject(), getEditor(), getFile());
                return null;
              }
            });
        // Don't bother checking if it should have failed.
        if (shouldFailString == null) {
          for (Map.Entry<String, PsiFile> entry : pathToFile.entrySet()) {
            //noinspection AssignmentToStaticFieldFromInstanceMethod
            myFile = entry.getValue();
            String canonicalPathToExpectedFile =
                PathUtil.getCanonicalPath(entry.getKey() + ".after");

            checkResultByFile(canonicalPathToExpectedFile);
          }
        }
      }
      assertNull("Expected test to fail.", shouldFailString);
    } catch (IntentionTestException e) {
      assertEquals("Failure message mismatch.", shouldFailString, e.getMessage());
    } catch (BaseRefactoringProcessor.ConflictsInTestsException e) {
      assertEquals(
          "Failure message mismatch.", shouldFailString, StringUtil.join(e.getMessages(), ", "));
    }
  }
 public void testCopyResourcesFromModuleOutput() {
   String file = createFile("src/a.xml", "");
   JpsJavaExtensionService.getInstance()
       .getOrCreateCompilerConfiguration(myProject)
       .addResourcePattern("*.xml");
   JpsModule module = addModule("a", PathUtil.getParentPath(file));
   JpsArtifact artifact = addArtifact(root().module(module));
   buildArtifacts(artifact);
   assertOutput(artifact, fs().file("a.xml"));
 }
 private static GradleProject populateProject(
     @NotNull IdeaProject project, @NotNull String projectPath) {
   String projectDirPath = GradleUtil.toCanonicalPath(PathUtil.getParentPath(projectPath));
   // Gradle API doesn't expose project compile output path yet.
   GradleProject result = new GradleProject(projectDirPath, projectDirPath + "/out");
   result.setName(project.getName());
   result.setJdkVersion(project.getJdkName());
   result.setLanguageLevel(project.getLanguageLevel().getLevel());
   return result;
 }
  @Test
  public void testSourceSetOutputDirsAsRuntimeDependencies() throws Exception {
    importProject(
        "apply plugin: 'java'\n"
            + "sourceSets.main.output.dir file(\"$buildDir/generated-resources/main\")");

    assertModules("project", "project_main", "project_test");
    final String path = pathFromBasedir("build/generated-resources/main");
    final String depName = PathUtil.toPresentableUrl(path);
    assertModuleLibDep("project_main", depName, "file://" + path);
    assertModuleLibDepScope("project_main", depName, DependencyScope.RUNTIME);
  }
  public static String getPathInConf(String fileName) {
    try {
      final String jarPath = PathUtil.getJarPathForClass(GroovyScriptRunner.class);
      if (new File(jarPath).isFile()) { // jar; distribution mode
        return new File(jarPath, "../" + fileName).getCanonicalPath();
      }

      // else, it's directory in out, development mode
      return new File(jarPath, "conf/" + fileName).getCanonicalPath();
    } catch (IOException e) {
      throw new RuntimeException(e);
    }
  }
  private static boolean isPathOutsideProjectContent(
      @NotNull final ProjectFileIndex fileIndex, @NotNull String path) {
    while (!path.isEmpty()) {
      final VirtualFile file = LocalFileSystem.getInstance().findFileByPath(path);
      if (file == null) {
        path = PathUtil.getParentPath(path);
      } else {
        return !fileIndex.isInContent(file);
      }
    }

    return false;
  }
 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));
 }
 protected Module createModule(final String name) {
   final Module module = super.createModule(name);
   final ModifiableRootModel model = ModuleRootManager.getInstance(module).getModifiableModel();
   final LibraryTable.ModifiableModel modifiableModel =
       model.getModuleLibraryTable().getModifiableModel();
   final Library library = modifiableModel.createLibrary("junit");
   final Library.ModifiableModel libModel = library.getModifiableModel();
   libModel.addRoot(
       VfsUtil.getUrlForLibraryRoot(new File(PathUtil.getJarPathForClass(Before.class))),
       OrderRootType.CLASSES);
   libModel.commit();
   model.commit();
   return module;
 }
    @Nullable
    @Override
    protected ValidationInfo doValidate() {
      for (String fileName : myComponent.getFileNamesToCreate()) {
        if (!PathUtil.isValidFileName(fileName)) {
          return new ValidationInfo(
              String.format("File name for properties file '%s' is invalid", fileName));
        } else {
          if (myDirectory.findFile(fileName) != null) {
            return new ValidationInfo(String.format("File with name '%s' already exist", fileName));
          }
        }
      }

      return null;
    }
  @Test
  public void testSourceSetOutputDirsAsRuntimeDependenciesOfDependantModules() throws Exception {
    createSettingsFile("include 'projectA', 'projectB', 'projectC' ");
    importProject(
        "project(':projectA') {\n"
            + "  apply plugin: 'java'\n"
            + "  sourceSets.main.output.dir file(\"$buildDir/generated-resources/main\")\n"
            + "}\n"
            + "project(':projectB') {\n"
            + "  apply plugin: 'java'\n"
            + "  dependencies {\n"
            + "    compile project(':projectA')\n"
            + "  }\n"
            + "}\n"
            + "project(':projectC') {\n"
            + "  apply plugin: 'java'\n"
            + "  dependencies {\n"
            + "    runtime project(':projectB')\n"
            + "  }\n"
            + "}");

    assertModules(
        "project",
        "projectA",
        "projectA_main",
        "projectA_test",
        "projectB",
        "projectB_main",
        "projectB_test",
        "projectC",
        "projectC_main",
        "projectC_test");

    assertModuleModuleDepScope("projectB_main", "projectA_main", DependencyScope.COMPILE);
    assertModuleModuleDepScope("projectC_main", "projectA_main", DependencyScope.RUNTIME);
    assertModuleModuleDepScope("projectC_main", "projectB_main", DependencyScope.RUNTIME);

    final String path = pathFromBasedir("projectA/build/generated-resources/main");
    final String classesPath = "file://" + path;
    final String depName = PathUtil.toPresentableUrl(path);
    assertModuleLibDep("projectA_main", depName, classesPath);
    assertModuleLibDepScope("projectA_main", depName, DependencyScope.RUNTIME);
    assertModuleLibDep("projectB_main", depName, classesPath);
    assertModuleLibDepScope("projectB_main", depName, DependencyScope.COMPILE);
    assertModuleLibDep("projectC_main", depName, classesPath);
    assertModuleLibDepScope("projectC_main", depName, DependencyScope.RUNTIME);
  }
  @TestOnly
  private static void assertAccessInTests(
      @NotNull VirtualFileSystemEntry child, @NotNull NewVirtualFileSystem delegate) {
    final Application application = ApplicationManager.getApplication();
    if (IS_UNDER_TEAMCITY
        && SHOULD_PERFORM_ACCESS_CHECK
        && application.isUnitTestMode()
        && application instanceof ApplicationImpl
        && ((ApplicationImpl) application).isComponentsCreated()) {
      if (delegate != LocalFileSystem.getInstance() && delegate != JarFileSystem.getInstance()) {
        return;
      }
      // root' children are loaded always
      if (child.getParent() == null || child.getParent().getParent() == null) return;

      Set<String> allowed = allowedRoots();
      boolean isUnder = allowed == null;
      if (!isUnder) {
        String childPath = child.getPath();
        if (delegate == JarFileSystem.getInstance()) {
          VirtualFile local = JarFileSystem.getInstance().getVirtualFileForJar(child);
          assert local != null : child;
          childPath = local.getPath();
        }
        for (String root : allowed) {
          if (FileUtil.startsWith(childPath, root)) {
            isUnder = true;
            break;
          }
          if (root.startsWith(JarFileSystem.PROTOCOL_PREFIX)) {
            String rootLocalPath =
                FileUtil.toSystemIndependentName(PathUtil.toPresentableUrl(root));
            isUnder = FileUtil.startsWith(childPath, rootLocalPath);
            if (isUnder) break;
          }
        }
      }

      assert isUnder || allowed.isEmpty()
          : "File accessed outside allowed roots: "
              + child
              + ";\nAllowed roots: "
              + new ArrayList<String>(allowed);
    }
  }
Beispiel #29
0
  public TOSDialog() {
    super(null, false, IdeModalityType.IDE);
    init();
    setTitle("eddy - Logging preferences");
    setCrossClosesWindow(false);
    // get TOS page out of our jar or directory
    final String pathname = PathUtil.getJarPathForClass(TOSDialog.class);
    final File path = new File(pathname);
    try {
      final URL url;
      if (path.isDirectory()) {
        url = new File(path, "intro.html").toURI().toURL();
      } else {
        url = ResourceUtil.getResource(TOSDialog.class, "", "intro.html");
      }
      TOSTextPane.setPage(url);
    } catch (MalformedURLException e) {
      throw new RuntimeException("Cannot load intro text. Please try reinstalling.", e);
    } catch (IOException e) {
      throw new RuntimeException("Cannot load intro text. Please try reinstalling.", e);
    }

    HyperlinkListener l =
        new HyperlinkListener() {
          @Override
          public void hyperlinkUpdate(HyperlinkEvent e) {
            log("got link event: " + e);
            if (HyperlinkEvent.EventType.ACTIVATED == e.getEventType()) {
              try {
                java.awt.Desktop.getDesktop().browse(e.getURL().toURI());
              } catch (IOException e1) {
                // wtf, do nothing
                log("exception: " + e1);
              } catch (URISyntaxException e2) {
                // broken link, do nothing
                log("exception: " + e2);
              }
            }
          }
        };
    TOSTextPane.addHyperlinkListener(l);
  }
  @Nullable
  protected VirtualFile findCoreJar(@Nullable Module module) {
    if (module == null) return null;

    JavaPsiFacade javaFacade = JavaPsiFacade.getInstance(module.getProject());

    for (PsiClass aClass :
        javaFacade.findClasses(
            getSomeFrameworkClass(), GlobalSearchScope.moduleWithLibrariesScope(module))) {
      VirtualFile virtualFile = aClass.getContainingFile().getVirtualFile();
      if (virtualFile != null && virtualFile.getFileSystem() instanceof JarFileSystem) {
        VirtualFile localFile = PathUtil.getLocalFile(virtualFile);
        if (isCoreJar(localFile)) {
          return localFile;
        }
      }
    }

    return null;
  }