Beispiel #1
0
  /*
   * (non-Javadoc)
   *
   * @see
   * net.xeoh.plugins.base.impl.classpath.locator.AbstractClassPathLocation
   * #getInputStream(java.lang.String)
   */
  @Override
  public InputStream getInputStream(String file) {

    try {
      final JarURLConnection connection =
          (JarURLConnection) new URI("jar:" + this.location + "!/").toURL().openConnection();
      final JarFile jarFile = connection.getJarFile();

      final Enumeration<JarEntry> entries = jarFile.entries();

      while (entries.hasMoreElements()) {
        final JarEntry entry = entries.nextElement();

        // We only search for class file entries
        if (entry.isDirectory()) continue;

        String name = entry.getName();

        if (name.equals(file)) return jarFile.getInputStream(entry);
      }
    } catch (MalformedURLException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    } catch (URISyntaxException e) {
      e.printStackTrace();
    }

    return null;
  }
  private List<JavaFileObject> processJar(URL packageFolderURL) {
    List<JavaFileObject> result = new ArrayList<JavaFileObject>();
    try {
      String jarUri = packageFolderURL.toExternalForm().split("!")[0];

      JarURLConnection jarConn = (JarURLConnection) packageFolderURL.openConnection();
      String rootEntryName = jarConn.getEntryName();
      int rootEnd = rootEntryName.length() + 1;

      Enumeration<JarEntry> entryEnum = jarConn.getJarFile().entries();
      while (entryEnum.hasMoreElements()) {
        JarEntry jarEntry = entryEnum.nextElement();
        String name = jarEntry.getName();
        if (name.startsWith(rootEntryName)
            && name.indexOf('/', rootEnd) == -1
            && name.endsWith(CLASS_FILE_EXTENSION)) {
          URI uri = URI.create(jarUri + "!/" + name);
          String binaryName = name.replaceAll("/", ".");
          binaryName = binaryName.replaceAll(CLASS_FILE_EXTENSION + "$", "");

          result.add(new CustomJavaFileObject(binaryName, uri));
        }
      }
    } catch (Exception e) {
      throw new RuntimeException("Wasn't able to open " + packageFolderURL + " as a jar file", e);
    }
    return result;
  }
Beispiel #3
0
 /**
  * @param jarFileUri jar:file:/some/path/gluegen-rt.jar!/
  * @return JarFile as named by Uri within the given ClassLoader
  * @throws IllegalArgumentException null arguments
  * @throws IOException if the Jar file could not been found
  * @throws URISyntaxException
  */
 public static JarFile getJarFile(final Uri jarFileUri)
     throws IOException, IllegalArgumentException, URISyntaxException {
   if (null == jarFileUri) {
     throw new IllegalArgumentException("null jarFileUri");
   }
   if (DEBUG) {
     System.err.println("getJarFile.0: " + jarFileUri.toString());
   }
   final URL jarFileURL = jarFileUri.toURL();
   if (DEBUG) {
     System.err.println("getJarFile.1: " + jarFileURL.toString());
   }
   final URLConnection urlc = jarFileURL.openConnection();
   if (urlc instanceof JarURLConnection) {
     final JarURLConnection jarConnection = (JarURLConnection) jarFileURL.openConnection();
     final JarFile jarFile = jarConnection.getJarFile();
     if (DEBUG) {
       System.err.println("getJarFile res: " + jarFile.getName());
     }
     return jarFile;
   }
   if (DEBUG) {
     System.err.println("getJarFile res: NULL");
   }
   return null;
 }
Beispiel #4
0
 private void checkManifestConnection(URL url) throws Exception {
   final URLConnection urlConnection = url.openConnection();
   final JarURLConnection jarURLConnection = (JarURLConnection) urlConnection;
   final Manifest manifest = jarURLConnection.getManifest();
   Assert.assertEquals("1.0", ManifestU.getAttribute(manifest, "Manifest-Version"));
   Assert.assertNotNull(ManifestU.getImplementationBuild(manifest));
 }
Beispiel #5
0
 /**
  * Create an OAR
  *
  * @param url The URL for the OperationalString Archive
  * @throws OARException If the manifest cannot be read
  * @throws IllegalArgumentException If the url is null
  */
 public OAR(URL url) throws OARException {
   if (url == null) throw new IllegalArgumentException("url cannot be null");
   JarFile jar = null;
   try {
     URL oarURL;
     if (url.getProtocol().equals("jar")) {
       oarURL = url;
     } else {
       StringBuilder sb = new StringBuilder();
       sb.append("jar:").append(url.toExternalForm()).append("!/");
       oarURL = new URL(sb.toString());
     }
     JarURLConnection conn = (JarURLConnection) oarURL.openConnection();
     jar = conn.getJarFile();
     Manifest man = jar.getManifest();
     getManifestAttributes(man);
     loadRepositories(jar);
     jar.close();
     this.url = url;
   } catch (Exception e) {
     throw new OARException("Problem processing " + url.toExternalForm(), e);
   } finally {
     try {
       if (jar != null) jar.close();
     } catch (IOException e) {
       e.printStackTrace();
     }
   }
 }
Beispiel #6
0
  public void connect() throws IOException {
    if (!connected) {
      String path = url.getPath();
      Matcher matcher = urlPattern.matcher(path);
      if (matcher.matches()) {
        path = matcher.group(1);
        String subPath = matcher.group(2);
        JarURLConnection jarURLConnection =
            (JarURLConnection) new URL("jar:" + path).openConnection();
        inputStream = jarURLConnection.getInputStream();
        if (subPath.isEmpty() == false) {
          JarFile jar = retrieve(new URL(path), inputStream);
          String[] nodes = nestingSeparatorPattern.split(subPath);
          int i;
          for (i = 0; i < nodes.length - 1; i++) {
            path += "!/" + nodes[i];
            jar = retrieve(new URL(path), inputStream);
          }
          ZipEntry entry = jar.getEntry(nodes[i]);
          entrySize = entry.getSize();
          inputStream = jar.getInputStream(entry);
        }
      } else {
        throw new MalformedURLException("Invalid JAP URL path: " + path);
      }

      connected = true;
    }
  }
Beispiel #7
0
    public static void copyJarResourcesRecursively(File destination, JarURLConnection jarConnection) {
        JarFile jarFile;
        try {
            jarFile = jarConnection.getJarFile();
        } catch (Exception e) {
            _.die("Failed to get jar file)");
            return;
        }

        Enumeration<JarEntry> em = jarFile.entries();
        while (em.hasMoreElements()) {
            JarEntry entry = em.nextElement();
            if (entry.getName().startsWith(jarConnection.getEntryName())) {
                String fileName = StringUtils.removeStart(entry.getName(), jarConnection.getEntryName());
                if (!fileName.equals("/")) {  // exclude the directory
                    InputStream entryInputStream = null;
                    try {
                        entryInputStream = jarFile.getInputStream(entry);
                        FileUtils.copyInputStreamToFile(entryInputStream, new File(destination, fileName));
                    } catch (Exception e) {
                        die("Failed to copy resource: " + fileName);
                    } finally {
                        if (entryInputStream != null) {
                            try {
                                entryInputStream.close();
                            } catch (Exception e) {
                            }
                        }
                    }
                }
            }
        }
    }
Beispiel #8
0
 @Nullable
 public static String getMainClassName(URL url) throws IOException {
   @NotNull URL u = new URL("jar", "", url + "!/");
   @NotNull JarURLConnection uc = (JarURLConnection) u.openConnection();
   Attributes attr = uc.getMainAttributes();
   return (attr != null) ? attr.getValue(Attributes.Name.MAIN_CLASS) : null;
 }
Beispiel #9
0
  private static void readJarEntries(URL location, String basePath, Map<String, URL> resources)
      throws IOException {
    JarURLConnection conn = (JarURLConnection) location.openConnection();
    JarFile jarfile = null;
    jarfile = conn.getJarFile();

    Enumeration<JarEntry> entries = jarfile.entries();
    while (entries != null && entries.hasMoreElements()) {
      JarEntry entry = entries.nextElement();
      String name = entry.getName();

      if (entry.isDirectory() || !name.startsWith(basePath) || name.length() == basePath.length()) {
        continue;
      }

      name = name.substring(basePath.length());

      if (name.contains("/")) {
        continue;
      }

      URL resource = new URL(location, name);
      resources.put(name, resource);
    }
  }
  protected ByteBuffer doRead(URLConnection connection) throws Exception {
    if (connection == null) {
      String msg = Logging.getMessage("nullValue.ConnectionIsNull");
      Logging.logger().severe(msg);
      throw new IllegalArgumentException(msg);
    }

    JarURLConnection htpc = (JarURLConnection) connection;
    this.responseCode = htpc.getContentLength() >= 0 ? HttpURLConnection.HTTP_OK : -1;
    this.responseMessage = this.responseCode >= 0 ? "OK" : "FAILED";

    String contentType = connection.getContentType();
    Logging.logger()
        .log(
            Level.FINE,
            "HTTPRetriever.ResponseInfo",
            new Object[] {
              this.responseCode,
              connection.getContentLength(),
              contentType != null ? contentType : "content type not returned",
              connection.getURL()
            });

    if (this.responseCode == HttpURLConnection.HTTP_OK) // intentionally re-using HTTP constant
    return super.doRead(connection);

    return null;
  }
Beispiel #11
0
  /**
   * Gets the build teimstamp from the jar manifest
   *
   * @return build timestamp
   */
  private static String getManifestBuildTimestamp() {
    JarURLConnection connection = null;
    JarFile jarFile = null;
    URL url = Commons.class.getClassLoader().getResource("jaligner");
    try {
      // Get jar connection
      connection = (JarURLConnection) url.openConnection();

      // Get the jar file
      jarFile = connection.getJarFile();

      // Get the manifest
      Manifest manifest = jarFile.getManifest();

      // Get the manifest entries
      Attributes attributes = manifest.getMainAttributes();

      Attributes.Name name = new Attributes.Name(BUILD_TIMESTAMP);
      return attributes.getValue(name);
    } catch (Exception e) {
      String message = "Failed getting the current release info: " + e.getMessage();
      logger.log(Level.WARNING, message);
    }
    return null;
  }
Beispiel #12
0
  public static boolean copyJarResourcesRecursively(
      final File destDir, final JarURLConnection jarConnection) throws IOException {

    final JarFile jarFile = jarConnection.getJarFile();

    for (final Enumeration<JarEntry> e = jarFile.entries(); e.hasMoreElements(); ) {
      final JarEntry entry = e.nextElement();
      if (entry.getName().startsWith(jarConnection.getEntryName())) {
        final String filename = entry.getName();

        final File f = new File(destDir, filename);
        if (!entry.isDirectory()) {
          final InputStream entryInputStream = jarFile.getInputStream(entry);
          if (!FileUtils.copyStream(entryInputStream, f)) {
            return false;
          }
          entryInputStream.close();
        } else {
          if (!FileUtils.ensureDirectoryExists(f)) {
            throw new IOException("Could not create directory: " + f.getAbsolutePath());
          }
        }
      }
    }
    return true;
  }
Beispiel #13
0
  /**
   * Lists all entries for the given JAR.
   *
   * @param uri
   * @return .
   */
  public static Collection<String> listAllEntriesFor(URI uri) {
    final Collection<String> rval = new ArrayList<String>();

    try {
      final JarURLConnection connection =
          (JarURLConnection) new URI("jar:" + uri + "!/").toURL().openConnection();
      final JarFile jarFile = connection.getJarFile();

      final Enumeration<JarEntry> entries = jarFile.entries();

      while (entries.hasMoreElements()) {
        final JarEntry entry = entries.nextElement();

        // We only search for class file entries
        if (entry.isDirectory()) continue;

        String name = entry.getName();

        rval.add(name);
      }
    } catch (MalformedURLException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    } catch (URISyntaxException e) {
      e.printStackTrace();
    }
    return rval;
  }
  /**
   * Return the directories in a jar URI, relative to the jar entry, if any. . Jar URLS have several
   * forms, the most common being: <code>jar:file:///foo/bar.jar/!/bif/baz</code>, which means that
   * the jar file /foo/bar.jar has a directory or file name bif/baz. If such a file is passed to
   * this method, then any directories in the jar file directory bif/baz will be returned.
   *
   * @param jarURL The Jar URL for which we are to look for directories.
   * @return An list of Strings that name the directories
   * @exception IOException If opening the connection fails or if getting the jar file from the
   *     connection fails
   */
  public static List<String> jarURLDirectories(URL jarURL) throws IOException {
    List<String> directories = new LinkedList<String>();
    JarURLConnection connection = (JarURLConnection) (jarURL.openConnection());
    String jarEntryName = connection.getEntryName();
    if (jarEntryName.endsWith("/")) {
      jarEntryName = jarEntryName.substring(0, jarEntryName.length() - 1);
    }
    JarFile jarFile = connection.getJarFile();
    Enumeration<JarEntry> entries = jarFile.entries();
    while (entries.hasMoreElements()) {
      JarEntry entry = entries.nextElement();
      String name = entry.getName();
      int jarEntryIndex = name.indexOf(jarEntryName + "/");
      int jarEntrySlashIndex = jarEntryIndex + jarEntryName.length() + 1;

      int nextSlashIndex = name.indexOf("/", jarEntrySlashIndex);
      int lastSlashIndex = name.indexOf("/", jarEntrySlashIndex);

      if (jarEntryIndex > -1
          && jarEntrySlashIndex > -1
          && nextSlashIndex > -1
          && nextSlashIndex == lastSlashIndex
          && nextSlashIndex == name.length() - 1
          && entry.isDirectory()) {
        directories.add(name);
      }
    }
    jarFile.close();
    return directories;
  }
 private JarFile openJar(URL url) {
   try {
     JarURLConnection jarURLConnection = (JarURLConnection) url.openConnection();
     return jarURLConnection.getJarFile();
   } catch (IOException e) {
     throw new RuntimeException("Cannot open jar file: " + url.getFile(), e);
   }
 }
Beispiel #16
0
  /**
   * Lists all top level class entries for the given URL.
   *
   * @param uri
   * @return .
   */
  public static Collection<String> listToplevelClassNamesForURI(URI uri) {
    final Collection<String> rval = new ArrayList<String>();

    // Ensure we have a proper cache entry ...
    // getCacheEntry();

    // Disabled: Not really necessary, is it? And not storing/retrieving
    // these items
    // makes the cache file smaller and saves several ms (~200) loading and
    // storing it
    // if (this.cacheEntry.classesValid) { return this.cacheEntry.classes; }

    try {
      final JarURLConnection connection =
          (JarURLConnection) new URI("jar:" + uri + "!/").toURL().openConnection();
      final JarFile jarFile = connection.getJarFile();

      final Enumeration<JarEntry> entries = jarFile.entries();

      while (entries.hasMoreElements()) {
        final JarEntry entry = entries.nextElement();

        // We only search for class file entries
        if (entry.isDirectory()) {
          continue;
        }
        if (!entry.getName().endsWith(".class")) {
          continue;
        }

        String name = entry.getName();
        name = name.replaceAll("/", ".");

        // Remove trailing .class
        if (name.endsWith("class")) {
          name = name.substring(0, name.length() - 6);
        }

        // Disabled: Not really necessary, is it? And not
        // storing/retrieving these items
        // makes the cache file smaller and saves several ms (~200)
        // loading and storing it
        // Only store something if we have a cache entry
        // if (this.cacheEntry != null)
        // this.cacheEntry.classes.add(name);

        rval.add(name);
      }
    } catch (MalformedURLException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    } catch (URISyntaxException e) {
      e.printStackTrace();
    }

    return rval;
  }
 /**
  * Extracts the entry name for the grammar from a given JAR or ZIP URL. The name is either given
  * in the JAR entry part of the URL, or it is taken to be the name of the archive file.
  *
  * @param url the URL to be parsed; guaranteed to be a JAR or ZIP
  * @return the name; non-null
  * @throws IllegalArgumentException if no name can be found according to the above rules
  * @throws IOException if the URL cannot be opened
  */
 private String extractEntryName(URL url) throws IOException {
   String result;
   JarURLConnection connection = (JarURLConnection) url.openConnection();
   result = connection.getEntryName();
   if (result == null) {
     result = FileType.getPureName(new File(connection.getJarFileURL().getPath()));
   }
   return result;
 }
  /**
   * Returns a stream to a pack, depending on the installation kind.
   *
   * @param n The pack number.
   * @return The stream.
   * @exception Exception Description of the Exception
   */
  private InputStream getPackAsStream(int n) throws Exception {
    InputStream in = null;

    if (idata.kind.equalsIgnoreCase("standard")
        || idata.kind.equalsIgnoreCase("standard-kunststoff"))
      in = getClass().getResourceAsStream("/packs/pack" + n);
    else if (idata.kind.equalsIgnoreCase("web") || idata.kind.equalsIgnoreCase("web-kunststoff")) {
      URL url = new URL("jar:" + jarLocation + "!/packs/pack" + n);
      JarURLConnection jarConnection = (JarURLConnection) url.openConnection();
      in = jarConnection.getInputStream();
    }
    return in;
  }
Beispiel #19
0
  /**
   * Returns the name of the jar file main class, or null if no "Main-Class" manifest attributes was
   * defined.
   */
  public String getMainClassName() throws IOException {
    URL u = new URL("jar", "", url + "!/");
    JarURLConnection uc = (JarURLConnection) u.openConnection();

    if (uc.getEntryName() == null) System.out.println("No Entry Name");
    else System.out.println(uc.getEntryName());
    if (uc == null) System.out.println("Connection is null");
    Attributes attr = uc.getMainAttributes();
    if (attr != null) System.out.println("Attributes has size: " + attr.size());
    // output(attr);

    return attr != null ? attr.getValue(Attributes.Name.MAIN_CLASS) : null;
  }
  /*
   * Scans the given JarURLConnection for TLD files located in META-INF
   * (or a subdirectory of it), adding an implicit map entry to the taglib
   * map for any TLD that has a <uri> element.
   *
   * @param jarConn The JarURLConnection to the JAR file to scan
   *
   * Keep in sync with o.a.c.startup.TldConfig
   */
  private void tldScanJar(JarURLConnection jarConn) throws IOException {

    Jar jar = null;
    InputStream is;
    boolean foundTld = false;

    URL resourceURL = jarConn.getJarFileURL();
    String resourcePath = resourceURL.toString();

    try {
      jar = JarFactory.newInstance(jarConn.getURL());

      jar.nextEntry();
      String entryName = jar.getEntryName();
      while (entryName != null) {
        if (entryName.startsWith("META-INF/") && entryName.endsWith(".tld")) {
          is = null;
          try {
            is = jar.getEntryInputStream();
            foundTld = true;
            tldScanStream(resourcePath, entryName, is);
          } finally {
            if (is != null) {
              try {
                is.close();
              } catch (IOException ioe) {
                // Ignore
              }
            }
          }
        }
        jar.nextEntry();
        entryName = jar.getEntryName();
      }
    } finally {
      if (jar != null) {
        jar.close();
      }
    }

    if (!foundTld) {
      if (log.isDebugEnabled()) {
        log.debug(Localizer.getMessage("jsp.tldCache.noTldInJar", resourcePath));
      } else if (showTldScanWarning) {
        // Not entirely thread-safe but a few duplicate log messages are
        // not a huge issue
        showTldScanWarning = false;
        log.info(Localizer.getMessage("jsp.tldCache.noTldSummary"));
      }
    }
  }
  private static File[] downloadAndSaveResources(
      String extensionSite, ExtensionWrapper ext, File plugInDirectory) {
    // TODO pull down resources from ext and save to pluginDir
    List fileList = new ArrayList(ext.getResourceList().size());

    for (Iterator iter = ext.getResourceList().iterator(); iter.hasNext(); ) {
      String resourceName = (String) iter.next();

      try {
        URL resURL =
            new URL( // + ext.getCategory() + "/"
                "jar:" + extensionSite + resourceName + "!/");

        JarURLConnection juc = (JarURLConnection) resURL.openConnection();
        JarFile jf = juc.getJarFile();

        Enumeration enumer = jf.entries();
        String resourceFile = plugInDirectory + File.separator + resourceName;
        fileList.add(new File(resourceFile));

        FileOutputStream fos = new FileOutputStream(resourceFile);
        System.out.println(":vv " + resourceFile);
        JarOutputStream jos = new JarOutputStream(fos);

        while (enumer.hasMoreElements()) {
          JarEntry je = (JarEntry) enumer.nextElement();
          jos.putNextEntry(new JarEntry(je));

          InputStream in = jf.getInputStream(je);
          int c;
          // TODO FIXME use a buffered reader!!!
          while ((c = in.read()) >= 0) {
            jos.write(c);
          }
          in.close();
        }
        jos.closeEntry();
        jos.close();
        fos.close();

      } catch (MalformedURLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
    }
    return (File[]) fileList.toArray(new File[fileList.size()]);
  }
Beispiel #22
0
  /**
   * Enumerates the resouces in a give package name. This works even if the resources are loaded
   * from a jar file!
   *
   * <p>Adapted from code by mikewse on the java.sun.com message boards.
   * http://forum.java.sun.com/thread.jsp?forum=22&thread=30984
   *
   * @param packageName The package to enumerate
   * @return A Set of Strings for each resouce in the package.
   */
  public static Set getResoucesInPackage(String packageName) throws IOException {
    String localPackageName;
    if (packageName.endsWith("/")) {
      localPackageName = packageName;
    } else {
      localPackageName = packageName + '/';
    }

    Enumeration dirEnum = ClassLoader.getSystemResources(localPackageName);

    Set names = new HashSet();

    // Loop CLASSPATH directories
    while (dirEnum.hasMoreElements()) {
      URL resUrl = (URL) dirEnum.nextElement();

      // Pointing to filesystem directory
      if (resUrl.getProtocol().equals("file")) {
        File dir = new File(resUrl.getFile());
        File[] files = dir.listFiles();
        if (files != null) {
          for (int i = 0; i < files.length; i++) {
            File file = files[i];
            if (file.isDirectory()) continue;
            names.add(localPackageName + file.getName());
          }
        }

        // Pointing to Jar file
      } else if (resUrl.getProtocol().equals("jar")) {
        JarURLConnection jconn = (JarURLConnection) resUrl.openConnection();
        JarFile jfile = jconn.getJarFile();
        Enumeration entryEnum = jfile.entries();
        while (entryEnum.hasMoreElements()) {
          JarEntry entry = (JarEntry) entryEnum.nextElement();
          String entryName = entry.getName();
          // Exclude our own directory
          if (entryName.equals(localPackageName)) continue;
          String parentDirName = entryName.substring(0, entryName.lastIndexOf('/') + 1);
          if (!parentDirName.equals(localPackageName)) continue;
          names.add(entryName);
        }
      } else {
        // Invalid classpath entry
      }
    }

    return names;
  }
 /**
  * Add a jar file to locations - see {@link #classpathLocations}.
  *
  * @param name
  * @param locations
  */
 private static void includeJar(File file, Map<String, URL> locations) {
   try {
     URL url = new URL("file:" + file.getCanonicalPath());
     url = new URL("jar:" + url.toExternalForm() + "!/");
     JarURLConnection conn = (JarURLConnection) url.openConnection();
     JarFile jarFile = conn.getJarFile();
     if (jarFile != null) {
       // the key does not matter here as long as it is unique
       locations.put(url.toString(), url);
     }
   } catch (Exception e) {
     // e.printStackTrace();
     return;
   }
 }
Beispiel #24
0
 public static LifecycleMappingMetadataSource getLifecycleMappingMetadataSource(CatalogItem ci) {
   try {
     URL url = getLifecycleMappingMetadataSourceURL(ci);
     if (url == null) {
       return null;
     }
     // To ensure we can delete the temporary file we need to prevent caching, see
     // http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4386865
     URLConnection conn = url.openConnection();
     if (conn instanceof JarURLConnection) {
       ((JarURLConnection) conn).setDefaultUseCaches(false);
     }
     InputStream is = conn.getInputStream();
     try {
       return LifecycleMappingFactory.createLifecycleMappingMetadataSource(is);
     } finally {
       IOUtil.close(is);
     }
   } catch (FileNotFoundException e) {
     // CatalogItem does not contain lifecycle mapping
   } catch (Exception e) {
     log.warn(NLS.bind(Messages.MavenCatalogViewer_Error_loading_lifecycle, ci.getId()), e);
   }
   return null;
 }
Beispiel #25
0
  /* ------------------------------------------------------------ */
  private List<String> listEntries() {
    checkConnection();

    ArrayList<String> list = new ArrayList<String>(32);
    JarFile jarFile = _jarFile;
    if (jarFile == null) {
      try {
        JarURLConnection jc = (JarURLConnection) ((new URL(_jarUrl)).openConnection());
        jc.setUseCaches(getUseCaches());
        jarFile = jc.getJarFile();
      } catch (Exception e) {

        e.printStackTrace();
        LOG.ignore(e);
      }
      if (jarFile == null) throw new IllegalStateException();
    }

    Enumeration e = jarFile.entries();
    String dir = _urlString.substring(_urlString.indexOf("!/") + 2);
    while (e.hasMoreElements()) {

      JarEntry entry = (JarEntry) e.nextElement();
      String name = entry.getName().replace('\\', '/');
      if (!name.startsWith(dir) || name.length() == dir.length()) {
        continue;
      }
      String listName = name.substring(dir.length());
      int dash = listName.indexOf('/');
      if (dash >= 0) {
        // when listing jar:file urls, you get back one
        // entry for the dir itself, which we ignore
        if (dash == 0 && listName.length() == 1) continue;
        // when listing jar:file urls, all files and
        // subdirs have a leading /, which we remove
        if (dash == 0) listName = listName.substring(dash + 1, listName.length());
        else listName = listName.substring(0, dash + 1);

        if (list.contains(listName)) continue;
      }

      list.add(listName);
    }

    return list;
  }
Beispiel #26
0
  private static List<String> resolveModuleEntriesFromJar(URL url, String _prefix)
      throws IOException {
    final String prefix = _prefix.endsWith("/") ? _prefix : _prefix + "/";

    List<String> resourceList = new ArrayList<String>();

    JarURLConnection conn = (JarURLConnection) url.openConnection();
    Enumeration entries = conn.getJarFile().entries();
    while (entries.hasMoreElements()) {
      JarEntry entry = (JarEntry) entries.nextElement();
      String name = entry.getName();
      if (name.startsWith(prefix) && !entry.isDirectory()) {
        resourceList.add(name);
      }
    }
    return resourceList;
  }
Beispiel #27
0
 // class loader should eventually be deprecated
 public URL[] list(URLFilter filter, ClassLoader loader) {
   try {
     List list = new ArrayList();
     String s = url.toString() + "";
     URLConnection conn = url.openConnection();
     if (conn instanceof JarURLConnection) {
       JarURLConnection jurl = (JarURLConnection) conn;
       JarFile jf = jurl.getJarFile();
       String dirName = s.substring(s.indexOf("!") + 1);
       String pattern = dirName + "/[^/]*(/|.)$";
       String contextPart = s.substring(0, s.indexOf("!"));
       Enumeration ee = jf.entries();
       while (ee.hasMoreElements()) {
         JarEntry je = (JarEntry) ee.nextElement();
         if (!("/" + je.getName()).matches(pattern)) continue;
         // process only the immediate children
         String spath = contextPart + "!/" + je.getName();
         // System.out.println(spath);
         URL u = new URL(spath);
         // System.out.println("---->"+u.toString());
         if (filter == null || filter.accept(u, u.getPath())) {
           list.add(u);
         }
       }
     } else if (conn instanceof HttpURLConnection) {
       throw new Exception("Http URL Connection is not supported at this time.");
     } else {
       File f = new File(url.getFile());
       if (f.isDirectory()) {
         File[] files = f.listFiles();
         for (int i = 0; i < files.length; i++) {
           URL u = files[i].toURL();
           if (filter == null || filter.accept(u, u.getPath())) {
             list.add(u);
           }
         }
       }
     }
     return (URL[]) list.toArray(new URL[] {});
   } catch (Exception ex) {
     System.out.println("URL DIRECTORY ERROR " + ex.getMessage());
     throw new RuntimeException(ex);
   }
 }
Beispiel #28
0
 private Set<Type> getAllJarTypes() {
   Set<Type> types = new LinkedHashSet<Type>();
   JarURLConnection conn;
   JarFile jar;
   try {
     conn = (JarURLConnection) packageURL.openConnection();
     jar = conn.getJarFile();
   } catch (IOException e) {
     throw ReflectionException.getInstance(e.getMessage(), e);
   }
   for (JarEntry e : Collections.list(jar.entries())) {
     String entryName = e.getName();
     Class<?> classEntry = getAsClass(entryName);
     if (classEntry != null) {
       types.add(classEntry);
     }
   }
   return types;
 }
Beispiel #29
0
 /** @throws Exception */
 public void testForEachJarFile() throws Exception {
   final String classFilePath = TestCase.class.getName().replace('.', '/') + ".class";
   final URL classURL = ResourceUtil.getResource(classFilePath);
   final JarURLConnection con = (JarURLConnection) classURL.openConnection();
   ClassTraversal.forEach(
       con.getJarFile(),
       new ClassHandler() {
         public void processClass(String packageName, String shortClassName) {
           if (count < 10) {
             System.out.println(ClassUtil.concatName(packageName, shortClassName));
           }
           assertNotNull(packageName);
           assertNotNull(shortClassName);
           assertTrue(packageName.startsWith("junit"));
           count++;
         }
       });
   assertTrue(count > 0);
 }
  /**
   * Checks a class path entry to see whether it can contain widgets and widgetsets.
   *
   * <p>All directories are automatically accepted. JARs are accepted if they have the
   * "Vaadin-Widgetsets" attribute in their manifest or the JAR file name contains "vaadin-" or
   * ".vaadin.".
   *
   * <p>Also other non-JAR entries may be accepted, the caller should be prepared to handle them.
   *
   * @param classpathEntry class path entry string as given in the Java class path
   * @return true if the entry should be considered when looking for widgets or widgetsets
   */
  private static boolean acceptClassPathEntry(String classpathEntry) {
    if (!classpathEntry.endsWith(".jar")) {
      // accept all non jars (practically directories)
      return true;
    } else {
      // accepts jars that comply with vaadin-component packaging
      // convention (.vaadin. or vaadin- as distribution packages),
      if (classpathEntry.contains("vaadin-") || classpathEntry.contains(".vaadin.")) {
        return true;
      } else {
        URL url;
        try {
          url = new URL("file:" + new File(classpathEntry).getCanonicalPath());
          url = new URL("jar:" + url.toExternalForm() + "!/");
          JarURLConnection conn = (JarURLConnection) url.openConnection();
          debug(url.toString());

          JarFile jarFile = conn.getJarFile();
          Manifest manifest = jarFile.getManifest();
          if (manifest != null) {
            Attributes mainAttributes = manifest.getMainAttributes();
            if (mainAttributes.getValue("Vaadin-Widgetsets") != null) {
              return true;
            }
            if (mainAttributes.getValue("Vaadin-Stylesheets") != null) {
              return true;
            }
          }
        } catch (MalformedURLException e) {
          if (debug) {
            error("Failed to inspect JAR file", e);
          }
        } catch (IOException e) {
          if (debug) {
            error("Failed to inspect JAR file", e);
          }
        }

        return false;
      }
    }
  }