Ejemplo n.º 1
0
  /**
   * Gets the library path name.
   *
   * @param containingJarName the containing jar name
   * @return the library path name
   */
  public String getLibraryPathName(final String containingJarName) {

    String result = null;
    final URLClassLoader sysLoader = getURLClassLoader();

    /* Recherche répertoire lib */
    final String startClass = ClasspathBooter.class.getName().replace('.', '/');
    if (sysLoader != null) {
      final URL startClassUrl = sysLoader.getResource(startClass + SUFFIX_CLASS);
      if (startClassUrl != null) {
        final String path = startClassUrl.getPath();
        if (!isEmpty(path) && !isEmpty(containingJarName)) { // Ne
          if (path.matches(".*" + containingJarName + ".*")) {
            result = path;
            int p = result.indexOf("!");
            if (p != -1) {
              result = result.substring(0, p);
            }
            p = result.lastIndexOf("/");
            result = path.substring(0, p + 1);
          }
        }
      }
    }

    return result;
  }
 /** Maybe connect, if not keep track of the problem. */
 private synchronized void tryToConnect() {
   if (connected || exception != null) {
     return;
   }
   try {
     URLClassLoader l;
     String cnb = url.getHost();
     if (cnb.isEmpty()) {
       l = globalClassLoader.get();
     } else {
       l = classLoaderMap.get().get(cnb);
       if (l == null) {
         throw new IOException("no loader for " + cnb);
       }
     }
     String path = url.getPath().substring(1);
     URL u = l.getResource(path);
     if (u == null) {
       throw new FileNotFoundException(path + " in " + Arrays.toString(l.getURLs()));
     }
     real = u.openConnection();
     real.connect();
     connected = true;
   } catch (IOException ioe) {
     exception = ioe;
   }
 }
Ejemplo n.º 3
0
 @Test
 public void jdkJarFile() throws Exception {
   // Sanity checks to see how the default jar file operates
   java.util.jar.JarFile jarFile = new java.util.jar.JarFile(this.rootJarFile);
   Enumeration<java.util.jar.JarEntry> entries = jarFile.entries();
   assertThat(entries.nextElement().getName()).isEqualTo("META-INF/");
   assertThat(entries.nextElement().getName()).isEqualTo("META-INF/MANIFEST.MF");
   assertThat(entries.nextElement().getName()).isEqualTo("1.dat");
   assertThat(entries.nextElement().getName()).isEqualTo("2.dat");
   assertThat(entries.nextElement().getName()).isEqualTo("d/");
   assertThat(entries.nextElement().getName()).isEqualTo("d/9.dat");
   assertThat(entries.nextElement().getName()).isEqualTo("special/");
   assertThat(entries.nextElement().getName()).isEqualTo("special/\u00EB.dat");
   assertThat(entries.nextElement().getName()).isEqualTo("nested.jar");
   assertThat(entries.nextElement().getName()).isEqualTo("another-nested.jar");
   assertThat(entries.hasMoreElements()).isFalse();
   URL jarUrl = new URL("jar:" + this.rootJarFile.toURI() + "!/");
   URLClassLoader urlClassLoader = new URLClassLoader(new URL[] {jarUrl});
   assertThat(urlClassLoader.getResource("special/\u00EB.dat")).isNotNull();
   assertThat(urlClassLoader.getResource("d/9.dat")).isNotNull();
   jarFile.close();
   urlClassLoader.close();
 }
Ejemplo n.º 4
0
  public static String resolveRelativeUrl(ApplicationID appId, String relativeUrl) {
    validateAppId(appId);
    if (StringUtilities.isEmpty(relativeUrl)) {
      throw new IllegalArgumentException(
          "Cannot resolve relative url - relative url cannot be null or empty string.");
    }
    final String loUrl = relativeUrl.toLowerCase();
    if (loUrl.startsWith("http:") || loUrl.startsWith("https:") || loUrl.startsWith("file:")) {
      return relativeUrl;
    }

    URLClassLoader classLoader = getUrlClassLoader(appId, new HashMap());
    URL absUrl = classLoader.getResource(relativeUrl);
    return absUrl != null ? absUrl.toString() : null;
  }
Ejemplo n.º 5
0
 @Test
 public void getSpecialResourceViaClassLoader() throws Exception {
   URLClassLoader urlClassLoader = new URLClassLoader(new URL[] {this.jarFile.getUrl()});
   assertThat(urlClassLoader.getResource("special/\u00EB.dat")).isNotNull();
   urlClassLoader.close();
 }
  public @Override void execute() throws BuildException {
    String p = getProject().getProperty("javahelpbin.exclude.modules");
    excludedModulesSet = parseExcludeModulesProperty(p);
    for (FileSet fs : filesets) {
      FileScanner scanner = fs.getDirectoryScanner(getProject());
      File dir = scanner.getBasedir();
      String[] files = scanner.getIncludedFiles();

      URLClassLoader globalClassLoader;
      Map<String, URLClassLoader> classLoaderMap;
      try {
        globalClassLoader = createGlobalClassLoader(dir, files);
        classLoaderMap = createClassLoaderMap(dir, files);
        NbDocsStreamHandler.NbDocsURLConnection.globalClassLoader.set(globalClassLoader);
        NbDocsStreamHandler.NbDocsURLConnection.classLoaderMap.set(classLoaderMap);
        CheckLinks.handlerFactory.set(new NbDocsStreamHandler.Factory());
        for (Map.Entry<String, URLClassLoader> entry : classLoaderMap.entrySet()) {
          String cnb = entry.getKey();
          if (excludedModulesSet.contains(cnb)) {
            log("skipping module: " + cnb, Project.MSG_INFO);
            continue;
          }
          URLClassLoader l = entry.getValue();
          Manifest m;
          InputStream is = l.getResourceAsStream("META-INF/MANIFEST.MF");
          if (is != null) {
            try {
              m = new Manifest(is);
            } finally {
              is.close();
            }
          } else {
            log("No manifest in " + Arrays.toString(l.getURLs()), Project.MSG_WARN);
            continue;
          }
          for (String resource :
              new String[] {
                m.getMainAttributes().getValue("OpenIDE-Module-Layer"),
                "META-INF/generated-layer.xml"
              }) {
            if (resource == null) {
              continue;
            }
            URL layer = l.getResource(resource);
            if (layer == null) {
              log("No layer " + resource, Project.MSG_VERBOSE);
              continue;
            }
            Document doc;
            try {
              doc = XMLUtil.parse(new InputSource(layer.toString()), false, false, null, NO_DTDS);
            } catch (SAXException x) {
              log("Could not parse " + layer, x, Project.MSG_WARN);
              continue;
            }
            for (Element services : XMLUtil.findSubElements(doc.getDocumentElement())) {
              if (!services.getTagName().equals("folder")
                  || !services.getAttribute("name").equals("Services")) {
                continue;
              }
              for (Element javahelp : XMLUtil.findSubElements(services)) {
                if (!javahelp.getTagName().equals("folder")
                    || !javahelp.getAttribute("name").equals("JavaHelp")) {
                  continue;
                }
                JAVAHELP:
                for (Element registration : XMLUtil.findSubElements(javahelp)) {
                  if (!registration.getTagName().equals("file")) {
                    continue;
                  }
                  InputSource input = null;
                  String url = registration.getAttribute("url");
                  if (!url.isEmpty()) {
                    input = new InputSource(new URL(layer, url).toString());
                  } else {
                    NodeList nl = registration.getChildNodes();
                    for (int i = 0; i < nl.getLength(); i++) {
                      if (nl.item(i).getNodeType() == Node.CDATA_SECTION_NODE) {
                        if (input == null) {
                          input = new InputSource(new StringReader(nl.item(i).getNodeValue()));
                        } else {
                          log(
                              "Multiple content for "
                                  + registration.getAttribute("name")
                                  + " in "
                                  + layer,
                              Project.MSG_WARN);
                          continue JAVAHELP;
                        }
                      }
                    }
                    if (input == null) {
                      log(
                          "No content for " + registration.getAttribute("name") + " in " + layer,
                          Project.MSG_WARN);
                    }
                  }
                  Document doc2;
                  try {
                    doc2 = XMLUtil.parse(input, false, false, null, NO_DTDS);
                  } catch (SAXException x) {
                    log(
                        "Could not parse " + registration.getAttribute("name") + " in " + layer,
                        x,
                        Project.MSG_WARN);
                    continue;
                  }
                  URI helpsetref = URI.create(doc2.getDocumentElement().getAttribute("url"));
                  if ("nbdocs".equals(helpsetref.getScheme())
                      && helpsetref.getAuthority() == null) {
                    try {
                      helpsetref =
                          new URI(
                              helpsetref.getScheme(),
                              cnb,
                              helpsetref.getPath(),
                              helpsetref.getQuery(),
                              helpsetref.getFragment());
                    } catch (URISyntaxException x) {
                      throw new BuildException(x);
                    }
                  }
                  log("checking: " + helpsetref, Project.MSG_INFO);
                  checkHelpSetURL(
                      CheckLinks.toURL(helpsetref), globalClassLoader, l, classLoaderMap, cnb);
                }
              }
            }
          }
        }
      } catch (IOException x) {
        throw new BuildException(x);
      } finally {
        NbDocsStreamHandler.NbDocsURLConnection.globalClassLoader.set(null);
        NbDocsStreamHandler.NbDocsURLConnection.classLoaderMap.set(null);
        CheckLinks.handlerFactory.set(null);
      }
    }
  }
Ejemplo n.º 7
0
  /**
   * Constructs a new BinaryFile with the specified file as the input. The byte-order is undefined.
   * Reads start at the first byte of the file. This constructor looks for the file with the string
   * given, and will call the correct constructor as appropriate. If the string represents a file
   * available locally, then the BinaryFile will be accessed with a FileInputReader using a
   * RandomAccessFile. If it's only available as a resource, then a StreamInputReader will be used.
   * The name should be a path to a file, or the name of a resource that can be found in the
   * classpath, or a URL.
   *
   * @param name the name of the file to be opened for reading
   * @exception IOException pass-through errors from opening the file.
   */
  public BinaryFile(final String name) throws IOException {
    boolean showDebug = false;
    if (Debug.debugging("binaryfile")) {
      showDebug = true;
    }

    if (showDebug) {
      Debug.output("BinaryFile: trying to figure out how to handle " + name);
    }

    try {
      File file = null;
      URL url = null;

      if (!Environment.isApplet()) {
        file = new File(name);
      }

      if (file != null && file.exists()) {
        // If the string represents a file, then we want to
        // use the RandomAccessFile aspect of the BinaryFile.
        setInputReader(new FileInputReader(file));
      } else {
        // url = ClassLoader.getSystemResource(name);
        url = Thread.currentThread().getContextClassLoader().getResource(name);

        // OK, now we want to look around for the file, in the
        // classpaths, and as a resource. It may be a file in
        // a classpath, available for direct access.
        if (url != null) {

          final String newname = url.getFile();
          if (showDebug) {
            Debug.output("BinaryFile: looking for " + newname);
          }

          if (!Environment.isApplet()) {
            file = new File(newname);
          }

          if (file != null && file.exists()) {
            // It's still a file, available directly.
            // Access it with the RandomAccessFile
            setInputReader(new FileInputReader(file));
          } else {
            // Need to get it as a resource. Needs
            // special handling if it's coming in a jar
            // file. Jar file references have a "!" in
            // them
            if (!setJarInputReader(newname)) {
              if (showDebug) {
                Debug.output(" trying as url: " + url);
              }
              setInputReader(new URLInputReader(url));
            }
          }

        } else if (Environment.isApplet()) {
          if (showDebug) {
            Debug.output(" As applet, checking codebase...");
          }
          // Look in the codebase for applets...
          final URL[] cba = new URL[1];
          cba[0] = Environment.getApplet().getCodeBase();

          final URLClassLoader ucl = URLClassLoader.newInstance(cba);
          url = ucl.getResource(name);

          if (url != null) {
            setInputReader(new URLInputReader(url));
          }
        }

        // It's not in the classpath, so try it as a URL.
        if (inputReader == null) {

          if (showDebug) {
            Debug.output(" lastly, trying as URL: " + name);
          }
          try {
            setInputReader(new URLInputReader(new URL(name)));
          } catch (final java.security.AccessControlException ace) {
            Debug.output("BinaryFile: " + name + " couldn't be accessed.");
            throw new IOException("AccessControlException trying to fetch " + name + " as a URL");
          }
        }
      }

      if (inputReader == null) {
        throw new FileNotFoundException("BinaryFile can't find: " + name);
      }

    } catch (final IOException ioe) {
      throw ioe;
    }
  }
Ejemplo n.º 8
0
  /**
   * A simple test method to determine if a file or directory, represented by a string, can be found
   * by the current Java environment. Uses the same tests as BinaryFile constructor for tracking
   * down a file.
   *
   * @param name A path to a file, a URL, or a path to a jar file entry.
   */
  public static boolean exists(final String name) {
    boolean exists = false;
    try {
      File file = null;
      URL url = null;

      if (!Environment.isApplet()) {
        file = new File(name);
      }

      if (file != null && file.exists()) {
        exists = true;
      } else {
        // url = ClassLoader.getSystemResource(name);
        url = Thread.currentThread().getContextClassLoader().getResource(name);

        // OK, now we want to look around for the file, in the
        // classpaths, and as a resource. It may be a file in
        // a classpath, available for direct access.
        if (url != null) {
          exists = true;
        } else if (Environment.isApplet()) {
          if (Debug.debugging("binaryfile")) {
            Debug.output(" As applet, checking codebase...");
          }
          // Look in the codebase for applets...
          final URL[] cba = new URL[1];
          cba[0] = Environment.getApplet().getCodeBase();

          final URLClassLoader ucl = URLClassLoader.newInstance(cba);
          if (ucl.getResource(name) != null) {
            exists = true;

            // This has been commented out because the
            // AppletDataNugget has been deprecated, and
            // is not needed.

            // } else {
            // url = AppletDataNugget.findResource(name);

            // if (url != null) {
            // exists = true;
            // }
          }
        }

        // It's not in the classpath, so try it as a URL to a
        // webserver.
        if (!exists && name.indexOf("http:") != -1) {

          try {
            final InputStream stream = new URL(name).openStream();
            stream.close();
            exists = true;
          } catch (final java.security.AccessControlException ace) {
            exists = false;
          }
        }
      }

    } catch (final IOException ioe) {
      Debug.message("binaryfile", "BinaryFile.exists() caught IOException");
      exists = false;
    }

    if (Debug.debugging("binaryfile")) {
      Debug.output("BinaryFile.exists(" + name + ") = " + exists);
    }

    return exists;
  }
Ejemplo n.º 9
0
  /**
   * Returns a URL that names either a resource, a local file, or an internet URL.
   *
   * @param askingClass the class asking for the URL. Can be null.
   * @param name name of the resource, file or URL.
   * @throws java.net.MalformedURLException
   * @return URL
   */
  public static URL getResourceOrFileOrURL(Class askingClass, String name)
      throws java.net.MalformedURLException {

    boolean DEBUG = Debug.debugging("proputils");

    if (name == null) {
      if (DEBUG) Debug.output("PropUtils.getROFOU(): null file name");
      return null;
    }

    URL retval = null;
    if (DEBUG) Debug.output("PropUtils.getROFOU(): looking for " + name);

    if (askingClass != null) {
      // First see if we have a resource by that name
      if (DEBUG) Debug.output("PropUtils.getROFOU(): checking as resource");

      retval = askingClass.getResource(name);
    }
    if (retval == null) {
      // Check the general classpath...
      if (DEBUG) Debug.output("PropUtils.getROFOU(): checking in general classpath");
      retval = Thread.currentThread().getContextClassLoader().getResource(name);
    }
    if (retval == null && !Environment.isApplet()) {
      // Check the classpath plus the share directory, which may
      // be in the openmap.jar file or in the development
      // environment.
      if (DEBUG) Debug.output("PropUtils.getROFOU(): checking with ClassLoader");
      retval = ClassLoader.getSystemResource("share/" + name);
    }

    if (retval == null && Environment.isApplet()) {
      if (DEBUG) Debug.output("PropUtils.getROFOU(): checking with URLClassLoader");
      URL[] cba = new URL[1];
      cba[0] = Environment.getApplet().getCodeBase();
      URLClassLoader ucl = URLClassLoader.newInstance(cba);
      retval = ucl.getResource(name);
    }

    // If there was no resource by that name available
    if (retval == null) {
      if (DEBUG) Debug.output("PropUtils.getROFOU(): not found as resource");

      try {
        java.io.File file = new java.io.File(name);
        if (file.exists()) {
          retval = file.toURL();
          if (DEBUG) Debug.output("PropUtils.getROFOU(): found as file :)");
        } else {
          // Otherwise treat it as a raw URL.
          if (DEBUG) Debug.output("PropUtils.getROFOU(): Not a file, checking as URL");
          retval = new URL(name);
          java.io.InputStream is = retval.openStream();
          is.close();
          if (DEBUG) Debug.output("PropUtils.getROFOU(): OK as URL :)");
        }
      } catch (java.io.IOException ioe) {
        retval = null;
      } catch (java.security.AccessControlException ace) {
        Debug.error("PropUtils: AccessControlException trying to access " + name);
        retval = null;
      } catch (Exception e) {
        Debug.error("PropUtils: caught exception " + e.getMessage());
        retval = null;
      }
    }

    if (DEBUG) {
      if (retval != null) {
        Debug.output("Resource " + name + "=" + retval.toString());
      } else {
        Debug.output("Resource " + name + " can't be found...");
      }
    }

    return retval;
  }