public void testTwoPlatformsoverSameSDK() throws Exception {
    final File binDir = new File(getWorkDir(), "boot"); // NOI18N
    binDir.mkdir();
    final File jdocFile1 = new File(getWorkDir(), "jdoc1"); // NOI18N
    jdocFile1.mkdir();
    final File jdocFile2 = new File(getWorkDir(), "jdoc2"); // NOI18N
    jdocFile2.mkdir();
    JavaPlatformProviderImpl provider = Lookup.getDefault().lookup(JavaPlatformProviderImpl.class);
    final URL binRoot = Utilities.toURI(binDir).toURL();
    final ClassPath bootCp = ClassPathSupport.createClassPath(binRoot);
    final List<URL> javadoc1 = Collections.singletonList(Utilities.toURI(jdocFile1).toURL());
    final List<URL> javadoc2 = Collections.singletonList(Utilities.toURI(jdocFile2).toURL());
    final TestJavaPlatform platform1 = new TestJavaPlatform("platform1", bootCp); // NOI18N
    final TestJavaPlatform platform2 = new TestJavaPlatform("platform2", bootCp); // NOI18N
    platform2.setJavadoc(javadoc2);
    provider.addPlatform(platform1);
    provider.addPlatform(platform2);

    final JavadocForBinaryQuery.Result result1 = JavadocForBinaryQuery.findJavadoc(binRoot);
    assertEquals(javadoc2, Arrays.asList(result1.getRoots()));

    platform1.setJavadoc(javadoc1);
    assertEquals(javadoc1, Arrays.asList(result1.getRoots()));

    final JavadocForBinaryQuery.Result result2 = JavadocForBinaryQuery.findJavadoc(binRoot);
    assertEquals(javadoc1, Arrays.asList(result2.getRoots()));

    platform1.setJavadoc(Collections.<URL>emptyList());
    assertEquals(javadoc2, Arrays.asList(result1.getRoots()));
    assertEquals(javadoc2, Arrays.asList(result2.getRoots()));
  }
  public void testQuery() throws Exception {
    JavaPlatform platform = JavaPlatform.getDefault();
    ClassPath cp = platform.getBootstrapLibraries();
    FileObject pfo = cp.getRoots()[0];
    URL u = URLMapper.findURL(pfo, URLMapper.EXTERNAL);
    URL urls[] = JavadocForBinaryQuery.findJavadoc(u).getRoots();
    assertEquals(1, urls.length);
    assertTrue(urls[0].toString(), urls[0].toString().startsWith("http://download.oracle.com/"));

    List<URL> l = new ArrayList<URL>();
    File javadocFile = getBaseDir();
    File api = new File(javadocFile, "api");
    File index = new File(api, "index-files");
    FileUtil.toFileObject(index);
    index.mkdirs();
    l.add(Utilities.toURI(javadocFile).toURL());
    J2SEPlatformImpl platformImpl = (J2SEPlatformImpl) platform;
    platformImpl.setJavadocFolders(l);
    urls = JavadocForBinaryQuery.findJavadoc(u).getRoots();
    assertEquals(1, urls.length);
    assertEquals(Utilities.toURI(api).toURL(), urls[0]);
  }
 private void writeCatalog() throws IOException {
   String res =
       "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
           + "<!DOCTYPE module_updates PUBLIC \"-//NetBeans//DTD Autoupdate Catalog 2.5//EN\" \"http://www.netbeans.org/dtds/autoupdate-catalog-2_5.dtd\">"
           + "<module_updates timestamp=\"00/00/19/08/03/2006\">\n";
   for (String element : moduleElements) {
     res += element;
   }
   res += "</module_updates>\n";
   if (catalogFile == null) {
     catalogFile = File.createTempFile("catalog-", ".xml", tmpDirectory);
     catalogURL = Utilities.toURI(catalogFile).toURL();
   }
   PrintWriter pw =
       new PrintWriter(new OutputStreamWriter(new FileOutputStream(catalogFile), "UTF-8"));
   pw.write(res);
   pw.close();
 }
  /**
   * Test of getSharability method, of class
   * org.netbeans.modules.masterfs.GlobalSharabilityQueryImpl.
   */
  public void testGetSharability() {
    File[] all =
        new File[] {
          new File("/myroot/mydirectory/myfile.java"),
          new File("/myroot/mydirectory/myfile.class"),
          new File("/myroot/mydirectory/myfile.xml"),
          new File("/myroot/mydirectory/.cvsignore"),
          new File("/myroot/mydirectory/CVS"),
          new File("/myroot/mydirectory/.DS_Store"),
          new File("/myroot/mydirectory/.svn"),
          new File("/myroot/mydirectory/_svn")
        };

    for (int i = 0; i < all.length; i++) {
      boolean isNotSharable =
          sq.getSharability(Utilities.toURI(all[i])) == SharabilityQuery.Sharability.NOT_SHARABLE;
      boolean isNotVisible = !vq.isVisible(all[i].getName());
      assertEquals(isNotSharable, isNotVisible);
    }
  }
 public void testFileOwner() throws Exception {
   assertEquals("correct project from projfile FileObject", p, FileOwnerQuery.getOwner(projfile));
   URI u = Utilities.toURI(FileUtil.toFile(projfile));
   assertEquals("correct project from projfile URI " + u, p, FileOwnerQuery.getOwner(u));
   assertEquals(
       "correct project from projfile2 FileObject", p, FileOwnerQuery.getOwner(projfile2));
   assertEquals(
       "correct project from projfile2 URI",
       p,
       FileOwnerQuery.getOwner(Utilities.toURI(FileUtil.toFile(projfile2))));
   assertEquals("correct project from projdir FileObject", p, FileOwnerQuery.getOwner(projdir));
   assertEquals(
       "correct project from projdir URI",
       p,
       FileOwnerQuery.getOwner(Utilities.toURI(FileUtil.toFile(projdir))));
   // Check that it loads the project even though we have not touched it yet:
   Project p2 = FileOwnerQuery.getOwner(subprojfile);
   Project subproj = ProjectManager.getDefault().findProject(subprojdir);
   assertEquals("correct project from subprojdir FileObject", subproj, p2);
   assertEquals(
       "correct project from subprojdir URI",
       subproj,
       FileOwnerQuery.getOwner(Utilities.toURI(FileUtil.toFile(subprojdir))));
   assertEquals(
       "correct project from subprojfile FileObject",
       subproj,
       FileOwnerQuery.getOwner(subprojfile));
   assertEquals(
       "correct project from subprojfile URI",
       subproj,
       FileOwnerQuery.getOwner(Utilities.toURI(FileUtil.toFile(subprojfile))));
   assertEquals(
       "no project from randomfile FileObject", null, FileOwnerQuery.getOwner(randomfile));
   assertEquals(
       "no project from randomfile URI",
       null,
       FileOwnerQuery.getOwner(Utilities.toURI(FileUtil.toFile(randomfile))));
   assertEquals("no project in C:\\", null, FileOwnerQuery.getOwner(URI.create("file:/C:/")));
 }
  private File prepareNBM(
      String codeName,
      String releaseVersion,
      String implVersion,
      String specVersion,
      boolean visible,
      String dependency)
      throws Exception {
    String moduleName = codeName.substring(codeName.lastIndexOf(".") + 1);
    String moduleFile = codeName.replace(".", "-");
    String moduleDir = codeName.replace(".", "/") + "/";
    File nbm = File.createTempFile(moduleFile + "-", ".nbm", tmpDirectory);

    final String MODULE_NAME_PROP = "OpenIDE-Module-Name";

    File jar = new File(tmpDirectory, "x.jar");
    jar.getParentFile().mkdirs();
    JarOutputStream jos = new JarOutputStream(new FileOutputStream(jar));
    int idx = moduleDir.indexOf("/");
    while (idx != -1) {
      jos.putNextEntry(new ZipEntry(moduleDir.substring(0, idx + 1)));
      idx = moduleDir.indexOf("/", idx + 1);
    }

    jos.putNextEntry(new ZipEntry(moduleDir + "Bundle.properties"));
    jos.write(new String(MODULE_NAME_PROP + "=" + moduleName).getBytes("UTF-8"));
    jos.putNextEntry(new ZipEntry("META-INF/"));
    jos.putNextEntry(new ZipEntry("META-INF/manifest.mf"));
    jos.write(
        getManifest(
                codeName, releaseVersion, implVersion, moduleDir, specVersion, visible, dependency)
            .getBytes("UTF-8"));
    jos.close();
    File ext = new File(jar.getParentFile(), jar.getName() + ".external");
    FileOutputStream os = new FileOutputStream(ext);
    os.write(("CRC: " + UpdateTracking.getFileCRC(jar) + "\n").getBytes());
    os.write(("URL: " + Utilities.toURI(jar).toString() + "\n").getBytes());
    os.close();

    Manifest mf = new Manifest();
    mf.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1.0");

    jos = new JarOutputStream(new FileOutputStream(nbm), mf);
    jos.putNextEntry(new ZipEntry("Info/"));
    jos.putNextEntry(new ZipEntry("Info/info.xml"));
    jos.write(
        createInfoXML(
                visible,
                codeName,
                releaseVersion,
                implVersion,
                moduleName,
                Utilities.toURI(nbm).toURL().toString(),
                specVersion,
                dependency)
            .getBytes("UTF-8"));

    jos.putNextEntry(new ZipEntry("netbeans/"));
    jos.putNextEntry(new ZipEntry("netbeans/modules/"));
    jos.putNextEntry(new ZipEntry("netbeans/config/"));
    jos.putNextEntry(new ZipEntry("netbeans/config/Modules/"));
    jos.putNextEntry(new ZipEntry("netbeans/config/Modules/" + moduleFile + ".xml"));

    jos.write(getConfigXML(codeName, moduleFile, specVersion).getBytes("UTF-8"));

    jos.putNextEntry(new ZipEntry("netbeans/modules/" + moduleFile + ".jar.external"));

    FileInputStream fis = new FileInputStream(ext);
    FileUtil.copy(fis, jos);
    fis.close();
    ext.delete();
    jos.close();
    nbms.add(nbm);

    return nbm;
  }
  public static DotClassPath parse(File dotClasspath, List<Link> links) throws IOException {
    Document dotClasspathXml;
    try {
      dotClasspathXml =
          XMLUtil.parse(
              new InputSource(Utilities.toURI(dotClasspath).toString()),
              false,
              true,
              XMLUtil.defaultErrorHandler(),
              null);
    } catch (SAXException e) {
      IOException ioe =
          (IOException) new IOException(dotClasspath + ": " + e.toString()).initCause(e); // NOI18N
      throw ioe;
    }
    Element classpathEl = dotClasspathXml.getDocumentElement();
    if (!"classpath".equals(classpathEl.getLocalName())) { // NOI18N
      return empty();
    }
    List<Element> classpathEntryEls;
    try {
      classpathEntryEls = XMLUtil.findSubElements(classpathEl);
    } catch (IllegalArgumentException x) {
      throw new IOException(x);
    }
    if (classpathEntryEls == null) {
      return empty();
    }

    // accessrules are ignored as they are not supported in NB anyway, eg:
    /*
    <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER">
        <accessrules>
            <accessrule kind="accessible" pattern="com/sun/management/*"/>
            <accessrule kind="nonaccessible" pattern="com/sun/**"/>
        </accessrules>
    </classpathentry>
     */

    List<DotClassPathEntry> classpath = new ArrayList<DotClassPathEntry>();
    List<DotClassPathEntry> sources = new ArrayList<DotClassPathEntry>();
    DotClassPathEntry output = null;
    DotClassPathEntry jre = null;
    for (Element classpathEntry : classpathEntryEls) {
      Map<String, String> props = new HashMap<String, String>();
      NamedNodeMap attrs = classpathEntry.getAttributes();
      String linkName = null;
      for (int i = 0; i < attrs.getLength(); i++) {
        Node n = attrs.item(i);
        String key = n.getNodeName();
        String value = classpathEntry.getAttribute(n.getNodeName());
        if (DotClassPathEntry.ATTRIBUTE_PATH.equals(key)) {
          String resolvedLink = resolveLink(value, links);
          if (resolvedLink != null) {
            linkName = value;
            value = resolvedLink;
          }
        }
        props.put(key, value);
      }
      Element entryAttrs = XMLUtil.findElement(classpathEntry, "attributes", null); // NOI18N
      if (entryAttrs != null) {
        /*
        <classpathentry kind="lib" path="/home/dev/hibernate-annotations-3.3.1.GA/lib/hibernate-commons-annotations.jar" sourcepath="/home/dev/hibernate-annotations-3.3.1.GA/src">
            <attributes>
                <attribute name="javadoc_location" value="file:/home/dev/hibernate-annotations-3.3.1.GA/doc/api/"/>
            </attributes>
        </classpathentry>
         */
        List<Element> attrsList = XMLUtil.findSubElements(entryAttrs);
        if (attrsList != null) {
          for (Element e : attrsList) {
            props.put(e.getAttribute("name"), e.getAttribute("value")); // NOI18N
          }
        }
      }
      DotClassPathEntry entry = new DotClassPathEntry(props, linkName);
      if (entry.getKind() == DotClassPathEntry.Kind.SOURCE) {
        sources.add(entry);
      } else if (entry.getKind() == DotClassPathEntry.Kind.OUTPUT) {
        assert output == null : "there should be always just one default output"; // NOI18N
        output = entry;
      } else if (entry.getKind() == DotClassPathEntry.Kind.CONTAINER
          && entry.getRawPath().startsWith(Workspace.DEFAULT_JRE_CONTAINER)) {
        jre = entry;
      } else {
        classpath.add(entry);
      }
    }
    return new DotClassPath(classpath, sources, output, jre);
  }
  public void testForeignClassBundler() throws Exception { // #155091 and deps
    TestFileUtils.writeFile(
        d,
        "a/pom.xml",
        "<project xmlns='http://maven.apache.org/POM/4.0.0'>"
            + "<modelVersion>4.0.0</modelVersion>"
            + "<groupId>grp</groupId>"
            + "<artifactId>art</artifactId>"
            + "<packaging>jar</packaging>"
            + "<version>0</version>"
            + "</project>");
    FileObject src = FileUtil.createFolder(d, "a/src/main/java");

    File repo = EmbedderFactory.getProjectEmbedder().getLocalRepositoryFile();
    File art =
        new File(
            repo,
            "grp" + File.separator + "art" + File.separator + "0" + File.separator + "art-0.jar");
    URL root = FileUtil.getArchiveRoot(Utilities.toURI(art).toURL());
    Project p = ProjectManager.getDefault().findProject(d.getFileObject("a"));
    FileOwnerQuery.markExternalOwner(
        Utilities.toURI(art), p, FileOwnerQuery.EXTERNAL_ALGORITHM_TRANSIENT);
    MavenFileOwnerQueryImpl.getInstance()
        .registerCoordinates("grp", "art", "0", d.getFileObject("a").toURL());

    SourceForBinaryQuery.Result2 r = SourceForBinaryQuery.findSourceRoots2(root);
    assertEquals(Collections.singletonList(src), Arrays.asList(r.getRoots()));
    assertTrue(r.preferSources());
    TestFileUtils.writeFile(
        d,
        "b/pom.xml",
        "<project xmlns='http://maven.apache.org/POM/4.0.0'>"
            + "<modelVersion>4.0.0</modelVersion>"
            + "<groupId>grp</groupId>"
            + "<artifactId>art</artifactId>"
            + "<packaging>war</packaging>"
            + "<version>0</version>"
            + "</project>");
    src = FileUtil.createFolder(d, "b/src/main/java");

    art =
        new File(
            repo,
            "grp" + File.separator + "art" + File.separator + "0" + File.separator + "art-0.jar");
    FileOwnerQuery.markExternalOwner(
        Utilities.toURI(art),
        ProjectManager.getDefault().findProject(d.getFileObject("b")),
        FileOwnerQuery.EXTERNAL_ALGORITHM_TRANSIENT);
    root = FileUtil.getArchiveRoot(Utilities.toURI(art).toURL());
    p = ProjectManager.getDefault().findProject(d.getFileObject("b"));
    FileOwnerQuery.markExternalOwner(
        Utilities.toURI(art), p, FileOwnerQuery.EXTERNAL_ALGORITHM_TRANSIENT);
    MavenFileOwnerQueryImpl.getInstance()
        .registerCoordinates("grp", "art", "0", d.getFileObject("b").toURL());

    r = SourceForBinaryQuery.findSourceRoots2(root);
    assertEquals(Collections.singletonList(src), Arrays.asList(r.getRoots()));
    assertFalse(r.preferSources());

    // 215242 assert that output dir does prefer sources
    r = SourceForBinaryQuery.findSourceRoots2(new URL(d.toURL(), "b/target/classes/"));
    assertEquals(Collections.singletonList(src), Arrays.asList(r.getRoots()));
    assertTrue(r.preferSources());
  }