Search in sources :

Example 76 with JarURLConnection

use of java.net.JarURLConnection in project duangframework by tcrct.

the class AbstractClassTemplate method getList.

/**
 * TODO  替换重复的包路径
 */
/*
    private void replaceDuplicatePackageName() {
        if (ToolsKit.isEmpty(packageSet) ) {
           throw new EmptyNullException("包路径为空,请指定包路径");
        }

        Set<String> tmpPackageSet = new HashSet<>(packageSet.size());

        String[] packageArray = packageSet.toArray(new String[packageSet.size()]);

        Arrays.sort(packageArray, new Comparator<String>() {
            @Override
            public int compare(String o1, String o2) {
                return (o1.length() > o2.length()) ? 0 : 1;
            }

            @Override
            public boolean equals(Object obj) {
                return false;
            }
        });

        for (Iterator<String> it = packageSet.iterator(); it.hasNext();) {
            String key = it.next();
            for(String packageName : packageArray) {
                if (key.startsWith(packageName)) {

                }
            }
        }
    }
    */
/**
 * 取出所有指定包名及指定jar文件前缀的Class类
 * @return
 * @throws Exception
 */
@Override
public List<Class<?>> getList() throws Exception {
    List<Class<?>> classList = new ArrayList<>();
    for (String packageName : packageSet) {
        Enumeration<URL> urls = PathKit.duang().resource(packageName).paths();
        while (urls.hasMoreElements()) {
            URL url = urls.nextElement();
            if (ToolsKit.isEmpty(url)) {
                continue;
            }
            String protocol = url.getProtocol();
            // logger.debug(protocol +"                  "+url.getPath());
            if ("file".equalsIgnoreCase(protocol)) {
                String packagePath = url.getPath().replaceAll("%20", " ");
                addClass(classList, packagePath, packageName);
            } else if ("jar".equalsIgnoreCase(protocol)) {
                // 若在 jar 包中,则解析 jar 包中的 entry
                JarURLConnection jarURLConnection = (JarURLConnection) url.openConnection();
                JarFile jarFile = jarURLConnection.getJarFile();
                String jarFileName = jarFile.getName();
                int indexOf = jarFileName.lastIndexOf("/");
                if (indexOf == -1) {
                    indexOf = jarFileName.lastIndexOf("\\");
                }
                if (indexOf == -1) {
                    throw new MvcStartUpException("取jar包取时出错");
                }
                jarFileName = jarFileName.substring(indexOf + 1, jarFileName.length());
                boolean isContains = false;
                for (String key : jarNameSet) {
                    if (jarFileName.contains(key)) {
                        isContains = true;
                        break;
                    }
                }
                if (!isContains) {
                    continue;
                }
                Enumeration<JarEntry> jarEntries = jarFile.entries();
                while (jarEntries.hasMoreElements()) {
                    JarEntry jarEntry = jarEntries.nextElement();
                    String fileName = jarEntry.getName();
                    // 是class文件
                    if (fileName.endsWith(".class")) {
                        String suffix = fileName.substring(fileName.lastIndexOf("."));
                        String subFileName = fileName.substring(fileName.lastIndexOf("/") + 1, fileName.length() - suffix.length());
                        String filePkg = fileName.contains("/") ? fileName.substring(0, fileName.length() - subFileName.length() - suffix.length() - 1).replaceAll("/", ".") : "";
                        // 执行添加类操作
                        doAddClass(classList, filePkg, subFileName, suffix);
                    }
                }
            }
            if (!Const.IS_RELOAD_SCANNING) {
                // 将所有URL添加到集合
                Const.URL_LIST.add(url);
            }
        }
    }
    return classList;
}
Also used : MvcStartUpException(com.duangframework.core.exceptions.MvcStartUpException) JarURLConnection(java.net.JarURLConnection) JarFile(java.util.jar.JarFile) JarEntry(java.util.jar.JarEntry) URL(java.net.URL)

Example 77 with JarURLConnection

use of java.net.JarURLConnection in project maple-ir by LLVM-but-worse.

the class MultiJarDownloader method download.

@Override
public void download() throws IOException {
    URL[] urls = new URL[jarInfos.length];
    for (int i = 0; i < jarInfos.length; i++) {
        urls[i] = new URL(jarInfos[i].formattedURL());
    }
    contents = new LocateableJarContents<C>(urls);
    for (JarInfo jarinfo : jarInfos) {
        JarURLConnection connection = (JarURLConnection) new URL(jarinfo.formattedURL()).openConnection();
        JarFile jarFile = connection.getJarFile();
        Enumeration<JarEntry> entries = jarFile.entries();
        while (entries.hasMoreElements()) {
            JarEntry entry = entries.nextElement();
            byte[] bytes = IOUtil.read(jarFile.getInputStream(entry));
            if (entry.getName().endsWith(".class")) {
                C cn = factory.create(bytes, entry.getName());
                contents.getClassContents().add(cn);
            } else {
                JarResource resource = new JarResource(entry.getName(), bytes);
                contents.getResourceContents().add(resource);
            }
        }
    }
}
Also used : JarInfo(org.topdank.byteengineer.commons.data.JarInfo) JarURLConnection(java.net.JarURLConnection) JarResource(org.topdank.byteengineer.commons.data.JarResource) JarFile(java.util.jar.JarFile) JarEntry(java.util.jar.JarEntry) URL(java.net.URL)

Example 78 with JarURLConnection

use of java.net.JarURLConnection in project maple-ir by LLVM-but-worse.

the class SingleJarDownloader method download.

@Override
public void download() throws IOException {
    URL url = null;
    JarURLConnection connection = (JarURLConnection) (url = new URL(jarInfo.formattedURL())).openConnection();
    JarFile jarFile = connection.getJarFile();
    Enumeration<JarEntry> entries = jarFile.entries();
    contents = new LocateableJarContents<>(url);
    Map<String, ClassNode> map = new HashMap<>();
    while (entries.hasMoreElements()) {
        JarEntry entry = entries.nextElement();
        byte[] bytes = read(jarFile.getInputStream(entry));
        if (entry.getName().endsWith(".class")) {
            C cn = factory.create(bytes, entry.getName());
            if (!map.containsKey(cn.name)) {
                contents.getClassContents().add(cn);
            } else {
                throw new IllegalStateException("duplicate: " + cn.name);
            }
        // if(cn.name.equals("org/xmlpull/v1/XmlPullParser")) {
        // System.out.println("SingleJarDownloader.download() " +entry.getName() + " " + bytes.length);
        // }
        } else {
            JarResource resource = new JarResource(entry.getName(), bytes);
            contents.getResourceContents().add(resource);
        }
    }
}
Also used : ClassNode(org.objectweb.asm.tree.ClassNode) HashMap(java.util.HashMap) JarURLConnection(java.net.JarURLConnection) JarResource(org.topdank.byteengineer.commons.data.JarResource) JarFile(java.util.jar.JarFile) JarEntry(java.util.jar.JarEntry) URL(java.net.URL)

Example 79 with JarURLConnection

use of java.net.JarURLConnection in project Axe by DongyuCai.

the class ClassUtil method getClassSet.

/**
 * 获取指定包名下,所有的类
 */
public static Set<Class<?>> getClassSet(String packageName) {
    Set<Class<?>> classSet = new HashSet<>();
    try {
        if (packageName == null)
            return classSet;
        Enumeration<URL> urls = getClassLoader().getResources(packageName.replace(".", "/"));
        while (urls.hasMoreElements()) {
            URL url = urls.nextElement();
            if (url != null) {
                String protocol = url.getProtocol();
                if (protocol.equals("file")) {
                    String packagePath = url.getPath().replaceAll("%20", " ");
                    addClass(classSet, packagePath, packageName);
                } else if (protocol.equals("jar")) {
                    JarURLConnection jarURLConnection = (JarURLConnection) url.openConnection();
                    if (jarURLConnection != null) {
                        JarFile jarFile = jarURLConnection.getJarFile();
                        if (jarFile != null) {
                            String packagePath = packageName.replace(".", "/");
                            Enumeration<JarEntry> jarEntries = jarFile.entries();
                            while (jarEntries.hasMoreElements()) {
                                JarEntry jarEntry = jarEntries.nextElement();
                                String jarEntryName = jarEntry.getName();
                                // TODO:另外,这个地方没有注意到spi问题,有些spi的资源,可能还是会报ClassDefNotFound异常
                                if (!jarEntryName.startsWith(packagePath)) {
                                    continue;
                                }
                                if (jarEntryName.endsWith(".class")) {
                                    String className = jarEntryName.substring(0, jarEntryName.lastIndexOf(".")).replace("/", ".");
                                    doAddClass(classSet, className);
                                }
                            }
                        }
                    }
                }
            }
        }
    } catch (IOException e) {
        LogUtil.error(e);
        throw new RuntimeException(e);
    }
    return classSet;
}
Also used : Enumeration(java.util.Enumeration) JarURLConnection(java.net.JarURLConnection) IOException(java.io.IOException) JarFile(java.util.jar.JarFile) JarEntry(java.util.jar.JarEntry) URL(java.net.URL) HashSet(java.util.HashSet)

Example 80 with JarURLConnection

use of java.net.JarURLConnection in project apex-core by apache.

the class StramAppLauncher method init.

private void init(String tmpName) throws Exception {
    File baseDir = StramClientUtils.getUserDTDirectory();
    baseDir = new File(new File(baseDir, "appcache"), tmpName);
    baseDir.mkdirs();
    LinkedHashSet<URL> clUrls;
    List<String> classFileNames = new ArrayList<>();
    if (jarFile != null) {
        JarFileContext jfc = new JarFileContext(new java.util.jar.JarFile(jarFile), mvnBuildClasspathOutput);
        jfc.cacheDir = baseDir;
        java.util.Enumeration<JarEntry> entriesEnum = jfc.jarFile.entries();
        while (entriesEnum.hasMoreElements()) {
            java.util.jar.JarEntry jarEntry = entriesEnum.nextElement();
            if (!jarEntry.isDirectory()) {
                if (jarEntry.getName().endsWith("pom.xml")) {
                    jfc.pomEntry = jarEntry;
                } else if (jarEntry.getName().endsWith(".app.properties")) {
                    File targetFile = new File(baseDir, jarEntry.getName());
                    FileUtils.copyInputStreamToFile(jfc.jarFile.getInputStream(jarEntry), targetFile);
                    appResourceList.add(new PropertyFileAppFactory(targetFile));
                } else if (jarEntry.getName().endsWith(".class")) {
                    classFileNames.add(jarEntry.getName());
                }
            }
        }
        URL mainJarUrl = new URL("jar", "", "file:" + jarFile.getAbsolutePath() + "!/");
        jfc.urls.add(mainJarUrl);
        deployJars = Sets.newLinkedHashSet();
        // add all jar files from same directory
        Collection<File> jarFiles = FileUtils.listFiles(jarFile.getParentFile(), new String[] { "jar" }, false);
        for (File lJarFile : jarFiles) {
            jfc.urls.add(lJarFile.toURI().toURL());
            deployJars.add(lJarFile);
        }
        // resolve dependencies
        List<Resolver> resolvers = Lists.newArrayList();
        String resolverConfig = this.propertiesBuilder.conf.get(CLASSPATH_RESOLVERS_KEY_NAME, null);
        if (!StringUtils.isEmpty(resolverConfig)) {
            resolvers = new ClassPathResolvers().createResolvers(resolverConfig);
        } else {
            // default setup if nothing was configured
            String manifestCp = jfc.jarFile.getManifest().getMainAttributes().getValue(ManifestResolver.ATTR_NAME);
            if (manifestCp != null) {
                File repoRoot = new File(System.getProperty("user.home") + "/.m2/repository");
                if (repoRoot.exists()) {
                    LOG.debug("Resolving manifest attribute {} based on {}", ManifestResolver.ATTR_NAME, repoRoot);
                    resolvers.add(new ClassPathResolvers.ManifestResolver(repoRoot));
                } else {
                    LOG.warn("Ignoring manifest attribute {} because {} does not exist.", ManifestResolver.ATTR_NAME, repoRoot);
                }
            }
        }
        for (Resolver r : resolvers) {
            r.resolve(jfc);
        }
        jfc.jarFile.close();
        URLConnection urlConnection = mainJarUrl.openConnection();
        if (urlConnection instanceof JarURLConnection) {
            // JDK6 keeps jar file shared and open as long as the process is running.
            // we want the jar file to be opened on every launch to pick up latest changes
            // http://abondar-howto.blogspot.com/2010/06/howto-unload-jar-files-loaded-by.html
            // http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4167874
            ((JarURLConnection) urlConnection).getJarFile().close();
        }
        clUrls = jfc.urls;
    } else {
        clUrls = new LinkedHashSet<>();
    }
    // add the jar dependencies
    /*
    if (cp == null) {
      // dependencies from parent loader, if classpath can't be found from pom
      ClassLoader baseCl = StramAppLauncher.class.getClassLoader();
      if (baseCl instanceof URLClassLoader) {
        URL[] baseUrls = ((URLClassLoader)baseCl).getURLs();
        // launch class path takes precedence - add first
        clUrls.addAll(Arrays.asList(baseUrls));
      }
    }
*/
    String libjars = propertiesBuilder.conf.get(LIBJARS_CONF_KEY_NAME);
    if (libjars != null) {
        processLibJars(libjars, clUrls);
    }
    for (URL baseURL : clUrls) {
        LOG.debug("Dependency: {}", baseURL);
    }
    this.launchDependencies = clUrls;
    // we have the classpath dependencies, scan for java configurations
    findAppConfigClasses(classFileNames);
}
Also used : Resolver(com.datatorrent.stram.client.ClassPathResolvers.Resolver) ManifestResolver(com.datatorrent.stram.client.ClassPathResolvers.ManifestResolver) JarURLConnection(java.net.JarURLConnection) ArrayList(java.util.ArrayList) JarEntry(java.util.jar.JarEntry) URL(java.net.URL) JarURLConnection(java.net.JarURLConnection) URLConnection(java.net.URLConnection) JarEntry(java.util.jar.JarEntry) JarFileContext(com.datatorrent.stram.client.ClassPathResolvers.JarFileContext) ManifestResolver(com.datatorrent.stram.client.ClassPathResolvers.ManifestResolver) File(java.io.File)

Aggregations

JarURLConnection (java.net.JarURLConnection)220 URL (java.net.URL)159 JarFile (java.util.jar.JarFile)128 IOException (java.io.IOException)119 JarEntry (java.util.jar.JarEntry)104 File (java.io.File)90 URLConnection (java.net.URLConnection)88 ArrayList (java.util.ArrayList)30 InputStream (java.io.InputStream)26 MalformedURLException (java.net.MalformedURLException)25 URISyntaxException (java.net.URISyntaxException)21 Enumeration (java.util.Enumeration)17 Manifest (java.util.jar.Manifest)16 CodeSource (java.security.CodeSource)12 FileInputStream (java.io.FileInputStream)11 LinkedHashSet (java.util.LinkedHashSet)11 URI (java.net.URI)10 Attributes (java.util.jar.Attributes)10 ZipEntry (java.util.zip.ZipEntry)9 FileNotFoundException (java.io.FileNotFoundException)8