Java Code Examples for java.net.JarURLConnection

The following are top voted examples for showing how to use java.net.JarURLConnection. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: javaide   File: URLClassPath.java   Source Code and License 7 votes vote down vote up
private JarFile getJarFile(URL url) throws IOException {
    // Optimize case where url refers to a local jar file
    if (isOptimizable(url)) {
        //HACK
        //FileURLMapper p = new FileURLMapper (url);
        File p = new File(url.getPath());

        if (!p.exists()) {
            throw new FileNotFoundException(p.getPath());
        }
        return new JarFile (p.getPath());
    }
    URLConnection uc = getBaseURL().openConnection();
    uc.setRequestProperty(USER_AGENT_JAVA_VERSION, JAVA_VERSION);
    return ((JarURLConnection)uc).getJarFile();
}
 
Example 2
Project: incubator-netbeans   File: JarClassLoaderTest.java   Source Code and License 6 votes vote down vote up
public void testAddURLMethod() throws Exception {
    File jar = new File(getWorkDir(), "default-package-resource.jar");
    TestFileUtils.writeZipFile(jar, "META-INF/MANIFEST.MF:Manifest-Version: 1.0\nfoo: bar\n\n", "package/re source++.txt:content");
    JarClassLoader jcl = new JarClassLoader(Collections.<File>emptyList(), new ProxyClassLoader[0]);
    jcl.addURL(Utilities.toURI(jar).toURL());
    URL url = jcl.getResource("package/re source++.txt");
    assertTrue(url.toString(), url.toString().endsWith("default-package-resource.jar!/package/re%20source++.txt"));
    URLConnection conn = url.openConnection();
    assertEquals(7, conn.getContentLength());
    assertTrue(conn instanceof JarURLConnection);
    JarURLConnection jconn = (JarURLConnection) conn;
    assertEquals("package/re source++.txt", jconn.getEntryName());
    assertEquals(Utilities.toURI(jar).toURL(), jconn.getJarFileURL());
    assertEquals("bar", jconn.getMainAttributes().getValue("foo"));
    assertEquals(jar.getAbsolutePath(), jconn.getJarFile().getName());
}
 
Example 3
Project: incubator-netbeans   File: URLMapperTestHidden.java   Source Code and License 6 votes vote down vote up
private void implTestIfReachable(FileObject fo) throws Exception {
    URL urlFromMapper = URLMapper.findURL(fo, getURLType());        
    if (isNullURLExpected(urlFromMapper, fo)) return;
    
    assertNotNull(urlFromMapper);
    URLConnection fc = urlFromMapper.openConnection();
    
    
    if (fc instanceof JarURLConnection && fo.isFolder()) return; 
    InputStream ic = fc.getInputStream();
    try {
        assertNotNull(ic);
    } finally {
        if (ic != null) ic.close();
    }        
}
 
Example 4
Project: hadoop-oss   File: Configuration.java   Source Code and License 6 votes vote down vote up
private Document parse(DocumentBuilder builder, URL url)
    throws IOException, SAXException {
  if (!quietmode) {
    if (LOG.isDebugEnabled()) {
      LOG.debug("parsing URL " + url);
    }
  }
  if (url == null) {
    return null;
  }

  URLConnection connection = url.openConnection();
  if (connection instanceof JarURLConnection) {
    // Disable caching for JarURLConnection to avoid sharing JarFile
    // with other users.
    connection.setUseCaches(false);
  }
  return parse(builder, connection.getInputStream(), url.toString());
}
 
Example 5
Project: vertx-generator   File: TemplateUtil.java   Source Code and License 6 votes vote down vote up
/**
 * 将jar里面的文件复制到模板文件夹
 * 
 * @param jarConn
 * @return
 * @throws IOException
 */
public static void jarCreateTemplate(JarURLConnection jarConn) throws IOException {
	try (JarFile jarFile = jarConn.getJarFile()) {
		Enumeration<JarEntry> entrys = jarFile.entries();
		while (entrys.hasMoreElements()) {
			JarEntry entry = entrys.nextElement();
			if (entry.getName().startsWith(jarConn.getEntryName()) && !entry.getName().endsWith("/")) {
				String fileName = entry.getName().replace(TEMPLATE_DIR + "/", "");
				InputStream inpt = Thread.currentThread().getContextClassLoader()
						.getResourceAsStream(entry.getName());
				Files.copy(inpt, Paths.get(TEMPLATE_DIR, fileName));
			}
		}
	}

}
 
Example 6
Project: ForgeHax   File: ClassLoaderHelper.java   Source Code and License 6 votes vote down vote up
/**
 * Private helper method.
 *
 * @param connection
 *            the connection to the jar
 * @param pckgname
 *            the package name to search for
 * @param classes
 *            the current ArrayList of all classes. This method will simply
 *            add new classes.
 * @throws ClassNotFoundException
 *             if a file isn't loaded but still is in the jar file
 * @throws IOException
 *             if it can't correctly read from the jar file.
 */
private static void checkJarFile(JarURLConnection connection,
                                 String pckgname, ArrayList<Class<?>> classes)
        throws ClassNotFoundException, IOException {
    final JarFile jarFile = connection.getJarFile();
    final Enumeration<JarEntry> entries = jarFile.entries();
    String name;

    for (JarEntry jarEntry = null; entries.hasMoreElements()
            && ((jarEntry = entries.nextElement()) != null);) {
        name = jarEntry.getName();

        if (name.contains(".class")) {
            name = name.substring(0, name.length() - 6).replace('/', '.');

            if (name.contains(pckgname)) {
                classes.add(Class.forName(name));
            }
        }
    }
}
 
Example 7
Project: KernelHive   File: RepositoryLoaderService.java   Source Code and License 6 votes vote down vote up
private List<String> getClassesNamesInPackage(final URL url,
		String packageName) {
	final List<String> classes = new ArrayList<String>();
	packageName = packageName.replaceAll("\\.", "/");
	try {
		JarURLConnection juc = (JarURLConnection) url.openConnection();
		JarFile jf = juc.getJarFile();
		final Enumeration<JarEntry> entries = jf.entries();
		while (entries.hasMoreElements()) {
			final JarEntry je = entries.nextElement();
			if ((je.getName().startsWith(packageName))
					&& (je.getName().endsWith(".class"))) {
				classes.add(je.getName().replaceAll("/", "\\.")
						.replaceAll("\\.class", ""));
			}
		}
		jf.close();
		jf = null;
		juc = null;
		System.gc();
	} catch (final Exception e) {
		e.printStackTrace();
	}
	return classes;
}
 
Example 8
Project: gemini.blueprint   File: BundleClassPathWildcardTest.java   Source Code and License 6 votes vote down vote up
private void testJarConnectionOn(Resource jar) throws Exception {
	String toString = jar.getURL().toExternalForm();
	// force JarURLConnection
	String urlString = "jar:" + toString + "!/";
	URL newURL = new URL(urlString);
	System.out.println(newURL);
	System.out.println(newURL.toExternalForm());
	URLConnection con = newURL.openConnection();
	System.out.println(con);
	System.out.println(con instanceof JarURLConnection);
	JarURLConnection jarCon = (JarURLConnection) con;

	JarFile jarFile = jarCon.getJarFile();
	System.out.println(jarFile.getName());
	Enumeration enm = jarFile.entries();
	while (enm.hasMoreElements())
		System.out.println(enm.nextElement());
}
 
Example 9
Project: Equella   File: WorkspaceJarModelManager.java   Source Code and License 6 votes vote down vote up
private boolean isPluginJar(IFile file)
{
	if( "jar".equals(file.getFileExtension()) )
	{
		URI jarURI = URIUtil.toJarURI(file.getLocationURI(), JPFProject.MANIFEST_PATH);
		try
		{
			JarEntry jarFile = ((JarURLConnection) jarURI.toURL().openConnection()).getJarEntry();
			return jarFile != null;
		}
		catch( IOException e )
		{
			// Bad zip
		}
	}
	return false;
}
 
Example 10
Project: Sikulix2tesseract   File: LoadLibs.java   Source Code and License 6 votes vote down vote up
/**
 * Copies resources to target folder.
 *
 * @param resourceUrl
 * @param targetPath
 * @return
 */
static void copyResources(URL resourceUrl, File targetPath) throws IOException {
    if (resourceUrl == null) {
        return;
    }

    URLConnection urlConnection = resourceUrl.openConnection();

    /**
     * Copy resources either from inside jar or from project folder.
     */
    if (urlConnection instanceof JarURLConnection) {
        copyJarResourceToPath((JarURLConnection) urlConnection, targetPath);
    } else {
        File file = new File(resourceUrl.getPath());
        if (file.isDirectory()) {
            FileUtils.copyDirectory(file, targetPath);
        } else {
            FileUtils.copyFile(file, targetPath);
        }
    }
}
 
Example 11
Project: minijax   File: ClassPathScanner.java   Source Code and License 6 votes vote down vote up
private void checkJarFile(final ClassLoader classLoader, final URL url, final String pckgname) throws IOException {
    final JarURLConnection conn = (JarURLConnection) url.openConnection();
    final JarFile jarFile = conn.getJarFile();
    final Enumeration<JarEntry> entries = jarFile.entries();

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

        String name = jarEntry.getName();

        if (name.endsWith(".class")) {
            name = name.substring(0, name.length() - 6).replace('/', '.');

            if (name.startsWith(pckgname)) {
                addClass(classLoader, name);
            }
        }
    }
}
 
Example 12
Project: FJ-VDMJ   File: VDMJC.java   Source Code and License 6 votes vote down vote up
private static String getVersion()
{
	try
	{
		String path = VDMJC.class.getName().replaceAll("\\.", "/");
		URL url = VDMJC.class.getResource("/" + path + ".class");
		JarURLConnection conn = (JarURLConnection)url.openConnection();
	    JarFile jar = conn.getJarFile();
		Manifest mf = jar.getManifest();
		String version = (String)mf.getMainAttributes().get(Attributes.Name.IMPLEMENTATION_VERSION);
		return version;
	}
	catch (Exception e)
	{
		return null;
	}
}
 
Example 13
Project: FJ-VDMJ   File: VDMJC.java   Source Code and License 6 votes vote down vote up
private static String getVersion()
{
	try
	{
		String path = VDMJC.class.getName().replaceAll("\\.", "/");
		URL url = VDMJC.class.getResource("/" + path + ".class");
		JarURLConnection conn = (JarURLConnection)url.openConnection();
	    JarFile jar = conn.getJarFile();
		Manifest mf = jar.getManifest();
		String version = (String)mf.getMainAttributes().get(Attributes.Name.IMPLEMENTATION_VERSION);
		return version;
	}
	catch (Exception e)
	{
		return null;
	}
}
 
Example 14
Project: FJ-VDMJ   File: VDMJ.java   Source Code and License 6 votes vote down vote up
private static String getVersion()
{
	try
	{
		String path = VDMJ.class.getName().replaceAll("\\.", "/");
		URL url = VDMJ.class.getResource("/" + path + ".class");
		JarURLConnection conn = (JarURLConnection)url.openConnection();
	    JarFile jar = conn.getJarFile();
		Manifest mf = jar.getManifest();
		String version = (String)mf.getMainAttributes().get(Attributes.Name.IMPLEMENTATION_VERSION);
		return version;
	}
	catch (Exception e)
	{
		return null;
	}
}
 
Example 15
Project: FJ-VDMJ   File: VDMJ.java   Source Code and License 6 votes vote down vote up
private static String getVersion()
{
	try
	{
		String path = VDMJ.class.getName().replaceAll("\\.", "/");
		URL url = VDMJ.class.getResource("/" + path + ".class");
		JarURLConnection conn = (JarURLConnection)url.openConnection();
	    JarFile jar = conn.getJarFile();
		Manifest mf = jar.getManifest();
		String version = (String)mf.getMainAttributes().get(Attributes.Name.IMPLEMENTATION_VERSION);
		return version;
	}
	catch (Exception e)
	{
		return null;
	}
}
 
Example 16
Project: Samurai   File: ClassUtil.java   Source Code and License 6 votes vote down vote up
private static List<Class<?>> loadClassFromJarFile(URL url) {
    List<Class<?>> list = new LinkedList<>();
    try {
        JarURLConnection connection = (JarURLConnection) url.openConnection();
        JarFile jarFile = connection.getJarFile();
        Enumeration<JarEntry> jarEntries = jarFile.entries();
        while (jarEntries.hasMoreElements()) {
            String entryName = jarEntries.nextElement().getName();
            if (entryName.endsWith(".class")) {
                list.add(loadClass(entryName.substring(0, entryName.length() - 6).replace("/", ".")));
            }
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    return list;
}
 
Example 17
Project: uroborosql   File: SqlLoaderImpl.java   Source Code and License 6 votes vote down vote up
/**
 * {@inheritDoc}
 *
 * @see jp.co.future.uroborosql.store.SqlLoader#load()
 */
@Override
public ConcurrentHashMap<String, String> load() {
	ConcurrentHashMap<String, String> loadedSqlMap = new ConcurrentHashMap<>();
	try {
		Enumeration<URL> resources = Thread.currentThread().getContextClassLoader().getResources(loadPath);
		while (resources.hasMoreElements()) {
			URL resource = resources.nextElement();
			File rootDir = new File(URLDecoder.decode(resource.getFile(), StandardCharsets.UTF_8.toString()));

			if (!rootDir.exists() || !rootDir.isDirectory()) {
				if ("jar".equalsIgnoreCase(resource.getProtocol())) {
					putAllIfAbsent(loadedSqlMap, load((JarURLConnection) resource.openConnection(), loadPath));
					continue;
				}

				LOG.warn("Ignore because not directory.[{}]", rootDir.getAbsolutePath());
				continue;
			}

			LOG.debug("Start loading SQL template.[{}]", rootDir.getAbsolutePath());
			putAllIfAbsent(loadedSqlMap, load(new StringBuilder(), rootDir));
		}
	} catch (IOException e) {
		throw new UroborosqlRuntimeException("Failed to load SQL template.", e);
	}

	if (loadedSqlMap.isEmpty()) {
		LOG.warn("SQL template could not be found.");
		LOG.warn("Returns an empty SQL cache.");
	}

	return loadedSqlMap;
}
 
Example 18
Project: uroborosql   File: SqlLoaderImpl.java   Source Code and License 6 votes vote down vote up
/**
 * Jar ファイル内の指定のフォルダパス以下にある .sqlファイルを読み込み SQL識別子をキーとしたSQL文のMapを返します
 *
 * @param jarUrlConnection Jarファイル内のURLコレクション
 * @param loadPath ロードパス
 * @return SQL識別子をキーとしたSQL文のMap
 */
private ConcurrentHashMap<String, String> load(final JarURLConnection jarUrlConnection, final String loadPath)
		throws IOException {
	LOG.debug("Loading the following SQL template.[{}]", jarUrlConnection);

	ConcurrentHashMap<String, String> sqlMap = new ConcurrentHashMap<>();
	JarFile jarFile = jarUrlConnection.getJarFile();
	Enumeration<JarEntry> jarEnum = jarFile.entries();
	while (jarEnum.hasMoreElements()) {
		JarEntry jarEntry = jarEnum.nextElement();
		String fileName = jarEntry.getName();
		if (fileName.startsWith(loadPath) && fileName.toLowerCase().endsWith(fileExtension)) {
			String sql = trimSlash(read(new BufferedReader(new InputStreamReader(jarFile.getInputStream(jarEntry)))));
			fileName = fileName.substring(loadPath.length() + 1, fileName.length() - 4);
			sqlMap.put(fileName, sql);

			LOG.trace("SQL template loaded.[{}]", fileName);
			LOG.trace("Add SQL template. [{}],[{}]", fileName, sql);
		}
	}
	return sqlMap;

}
 
Example 19
Project: jdk8u-jdk   File: JarURLConnectionUseCaches.java   Source Code and License 6 votes vote down vote up
public static void main( String[] args ) throws IOException {
    JarOutputStream out = new JarOutputStream(
            new FileOutputStream("usecache.jar"));
    out.putNextEntry(new JarEntry("test.txt"));
    out.write("Test txt file".getBytes());
    out.closeEntry();
    out.close();

    URL url = new URL("jar:"
        + new File(".").toURI().toString()
        + "/usecache.jar!/test.txt");

    JarURLConnection c1 = (JarURLConnection)url.openConnection();
    c1.setDefaultUseCaches( false );
    c1.setUseCaches( true );
    c1.connect();

    JarURLConnection c2 = (JarURLConnection)url.openConnection();
    c2.setDefaultUseCaches( false );
    c2.setUseCaches( true );
    c2.connect();

    c1.getInputStream().close();
    c2.getInputStream().read();
    c2.getInputStream().close();
}
 
Example 20
Project: openjdk-jdk10   File: JarURLConnectionUseCaches.java   Source Code and License 6 votes vote down vote up
public static void main( String[] args ) throws IOException {
    JarOutputStream out = new JarOutputStream(
            new FileOutputStream("usecache.jar"));
    out.putNextEntry(new JarEntry("test.txt"));
    out.write("Test txt file".getBytes());
    out.closeEntry();
    out.close();

    URL url = new URL("jar:"
        + new File(".").toURI().toString()
        + "/usecache.jar!/test.txt");

    JarURLConnection c1 = (JarURLConnection)url.openConnection();
    c1.setDefaultUseCaches( false );
    c1.setUseCaches( true );
    c1.connect();

    JarURLConnection c2 = (JarURLConnection)url.openConnection();
    c2.setDefaultUseCaches( false );
    c2.setUseCaches( true );
    c2.connect();

    c1.getInputStream().close();
    c2.getInputStream().read();
    c2.getInputStream().close();
}
 
Example 21
Project: validator-web   File: ClassPathScanner.java   Source Code and License 6 votes vote down vote up
public Set<Class<?>> findCandidateClasses(String basePackage) {
    Set<Class<?>> candidates = new LinkedHashSet<Class<?>>();
    try {
        String packageSearchPath = basePackage.replace('.', '/');
        ClassLoader classLoader = this.classLoader;
        if (classLoader == null) {
            classLoader = Thread.currentThread().getContextClassLoader();
        }
        Enumeration<URL> resources = classLoader.getResources(packageSearchPath);
        while (resources.hasMoreElements()) {
            URL resource = resources.nextElement();
            if (logger.isTraceEnabled()) {
                logger.trace("Scanning " + resource);
            }
            if ("file".equals(resource.getProtocol())) {
                findClasses(candidates, classLoader, basePackage, resource.getFile());
            } else if ("jar".equals(resource.getProtocol())) {
                findClasses(candidates, classLoader, packageSearchPath, (JarURLConnection) resource.openConnection());
            }
        }
    } catch (IOException e) {
        throw new RuntimeException("I/O failure during classpath scanning", e);
    }
    return candidates;
}
 
Example 22
Project: validator-web   File: ClassPathScanner.java   Source Code and License 6 votes vote down vote up
protected void findClasses(Set<Class<?>> classes, ClassLoader classLoader,
        String packageName, JarURLConnection connection) throws IOException {
    JarFile jarFile = connection.getJarFile();
    if (jarFile == null) {
        return;
    }
    Enumeration<JarEntry> entries = jarFile.entries();
    while (entries.hasMoreElements()) {
        JarEntry entry = entries.nextElement();
        String name = entry.getName();
        if (name.endsWith(CLASS_SUFFIX) && name.startsWith(packageName)) {
            String className = name.replace('/', '.').replace(CLASS_SUFFIX, "");
            try {
                Class<?> c = ClassUtils.forName(className, classLoader);
                classes.add(c);
            } catch (ClassNotFoundException e) {
                // ignore
                e.printStackTrace();
            }
        }
    }
}
 
Example 23
Project: Reer   File: UriTextResource.java   Source Code and License 5 votes vote down vote up
private Reader getInputStream(URI url) throws IOException {
    final URLConnection urlConnection = url.toURL().openConnection();
    urlConnection.setRequestProperty("User-Agent", getUserAgentString());

    // Without this, the URLConnection will keep the backing Jar file open indefinitely
    // This will have a performance impact for Jar-backed `UriTextResource` instances
    if (urlConnection instanceof JarURLConnection) {
        urlConnection.setUseCaches(false);
    }
    urlConnection.connect();
    String charset = extractCharacterEncoding(urlConnection.getContentType(), "utf-8");
    return new InputStreamReader(urlConnection.getInputStream(), charset);
}
 
Example 24
Project: n4js   File: ShippedCodeAccess.java   Source Code and License 5 votes vote down vote up
/**
 * Returns path for the shipped code from the provided location. If location is plain file returns its absolute path
 * as string. If location is inside jar file, unpacks desired resource to the temporal location and returns path to
 * that location.
 *
 * @param rootName
 *            name of shipped root to be located
 * @return the path pointing to the shipped code
 */
protected static String getShippedRuntimeCodePath(String rootName) {
	try {
		URL resourceUrl = getResource(rootName);

		final URLConnection connection = resourceUrl.openConnection();
		if (connection instanceof JarURLConnection) {
			return recursivelyCopyContent((JarURLConnection) connection, rootName);
		}

		return new File(resourceUrl.toURI()).getCanonicalFile().getAbsolutePath().replace("\\", "\\\\");
	} catch (final Exception e) {
		throw new RuntimeException("Error while getting shipped code path.", e);
	}
}
 
Example 25
Project: n4js   File: ShippedCodeAccess.java   Source Code and License 5 votes vote down vote up
/**
 * Unpacks desired folder structure from the JAR file into temporal location and returns that location absolute path
 * as string.
 *
 * @param connection
 *            connection to the JAR file
 * @param rootName
 *            name of the folder to be unpacked
 * @return absolute path to the temporarily unpacked folder
 * @throws IOException
 *             for IO operations
 */
protected static String recursivelyCopyContent(JarURLConnection connection, String rootName) throws IOException {
	final File tempFolder = getTempFolder();
	tempFolder.deleteOnExit();
	final File rootFolder = new File(tempFolder, rootName);
	if (rootFolder.exists()) {
		FileDeleter.delete(rootFolder.toPath());
	}
	checkState(rootFolder.mkdir(), "Error while creating folder for Node.js environment. " + rootFolder);
	checkState(rootFolder.isDirectory(), "Expected directory but got a file: " + rootFolder);
	rootFolder.deleteOnExit();

	try (final JarFile jarFile = connection.getJarFile()) {
		for (final Enumeration<JarEntry> em = jarFile.entries(); em.hasMoreElements(); /**/) {
			final JarEntry entry = em.nextElement();
			// Do not process anything which is not under desired root
			if (!entry.getName().startsWith(rootName)) {
				continue;
			}
			final String fileName = entry.getName();// .substring(connection.getEntryName().length());
			final File newResource = new File(tempFolder, fileName);
			if (entry.isDirectory()) {
				if (!newResource.exists()) {
					checkState(newResource.mkdir(), "Error while creating new folder at: " + newResource);
				}
			} else {
				checkState(newResource.createNewFile(), "Error while creating new file at: " + newResource);
				try (final InputStream is = jarFile.getInputStream(entry)) {
					com.google.common.io.Files.copy(() -> is, newResource);
				}
			}
			newResource.deleteOnExit();
		}
	}
	return rootFolder.getCanonicalFile().getAbsolutePath().replace("\\", "\\\\");
}
 
Example 26
Project: incubator-netbeans   File: JarClassLoaderTest.java   Source Code and License 5 votes vote down vote up
public void testJarURLConnection() throws Exception {
    File jar = new File(getWorkDir(), "default-package-resource.jar");
    TestFileUtils.writeZipFile(jar, "META-INF/MANIFEST.MF:Manifest-Version: 1.0\nfoo: bar\n\n", "package/re source++.txt:content");
    JarClassLoader jcl = new JarClassLoader(Collections.singletonList(jar), new ProxyClassLoader[0]);
    URL url = jcl.getResource("package/re source++.txt");
    assertTrue(url.toString(), url.toString().endsWith("default-package-resource.jar!/package/re%20source++.txt"));
    URLConnection conn = url.openConnection();
    assertEquals(7, conn.getContentLength());
    assertTrue(conn instanceof JarURLConnection);
    JarURLConnection jconn = (JarURLConnection) conn;
    assertEquals("package/re source++.txt", jconn.getEntryName());
    assertEquals(Utilities.toURI(jar).toURL(), jconn.getJarFileURL());
    assertEquals("bar", jconn.getMainAttributes().getValue("foo"));
    assertEquals(jar.getAbsolutePath(), jconn.getJarFile().getName());
}
 
Example 27
Project: ace   File: ScanUtil.java   Source Code and License 5 votes vote down vote up
/**
 * @param packNames 要扫描的包
 * @return Set
 */
public static Set<Class<?>> findFileClass(String... packNames) {

    Set<Class<?>> clazzs = new LinkedHashSet<Class<?>>();
    for (String packName : packNames) {
        String packageDirName = packName.replace('.', '/');
        Enumeration<URL> dirs;
        try {
            dirs = Thread.currentThread().getContextClassLoader().getResources(packageDirName);
            while (dirs.hasMoreElements()) {
                URL url = dirs.nextElement();
                String protocol = url.getProtocol();
                if ("file".equals(protocol)) {
                    //扫描file包中的类
                    String filePath = URLDecoder.decode(url.getFile(), "UTF-8");
                    getFileClass(packName, filePath, clazzs);
                } else if ("jar".equals(protocol)) {
                    //扫描jar包中的类
                    JarFile jarFile = ((JarURLConnection) url.openConnection()).getJarFile();
                    getJarClass(jarFile, packageDirName, clazzs);
                }
            }
        } catch (Exception e) {
            e.getStackTrace();
        }
    }


    return clazzs;
}
 
Example 28
Project: tomcat7   File: ContextConfig.java   Source Code and License 5 votes vote down vote up
@Override
public void scan(JarURLConnection jarConn) throws IOException {

    URL url = jarConn.getURL();
    URL resourceURL = jarConn.getJarFileURL();
    Jar jar = null;
    InputStream is = null;
    WebXml fragment = new WebXml();

    try {
        jar = JarFactory.newInstance(url);
        if (parseRequired || context.getXmlValidation()) {
            is = jar.getInputStream(FRAGMENT_LOCATION);
        }

        if (is == null) {
            // If there is no web-fragment.xml to process there is no
            // impact on distributable
            fragment.setDistributable(true);
        } else {
            InputSource source = new InputSource(
                    "jar:" + resourceURL.toString() + "!/" +
                    FRAGMENT_LOCATION);
            source.setByteStream(is);
            parseWebXml(source, fragment, true);
        }
    } finally {
        if (jar != null) {
            jar.close();
        }
        fragment.setURL(url);
        if (fragment.getName() == null) {
            fragment.setName(fragment.getURL().toString());
        }
        fragment.setJarName(extractJarFileName(url));
        fragments.put(fragment.getName(), fragment);
    }
}
 
Example 29
Project: tomcat7   File: BaseDirContext.java   Source Code and License 5 votes vote down vote up
/**
 * Add a resources JAR. The contents of /META-INF/resources/ will be used if
 * a requested resource can not be found in the main context.
 */
public void addResourcesJar(URL url) {
    try {
        JarURLConnection conn = (JarURLConnection) url.openConnection();
        JarFile jarFile = conn.getJarFile();   
        ZipEntry entry = jarFile.getEntry("/");
        WARDirContext warDirContext = new WARDirContext(jarFile,
                new WARDirContext.Entry("/", entry));
        warDirContext.loadEntries();
        altDirContexts.add(warDirContext);
    } catch (IOException ioe) {
        log.warn(sm.getString("resources.addResourcesJarFail", url), ioe);
    }
}
 
Example 30
Project: tomcat7   File: UrlJar.java   Source Code and License 5 votes vote down vote up
private NonClosingJarInputStream createJarInputStream() throws IOException {
    JarURLConnection jarConn = (JarURLConnection) url.openConnection();
    URL resourceURL = jarConn.getJarFileURL();
    URLConnection resourceConn = resourceURL.openConnection();
    resourceConn.setUseCaches(false);
    return new NonClosingJarInputStream(resourceConn.getInputStream());
}
 
Example 31
Project: tomcat7   File: JarURLResource.java   Source Code and License 5 votes vote down vote up
@Override
public JarFile getJarFile() throws IOException {
    URL jarFileUrl = new URL("jar:" + jarUrl + "!/");
    JarURLConnection conn = (JarURLConnection) jarFileUrl.openConnection();
    conn.setUseCaches(false);
    conn.connect();
    return conn.getJarFile();
}
 
Example 32
Project: airsonic   File: FileUtils.java   Source Code and License 5 votes vote down vote up
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 = StringUtils.removeStart(
                    entry.getName(), //
                    jarConnection.getEntryName());

            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;
}
 
Example 33
Project: airsonic   File: FileUtils.java   Source Code and License 5 votes vote down vote up
public static boolean copyResourcesRecursively(final URL originUrl, final File destination) {
    try {
        final URLConnection urlConnection = originUrl.openConnection();
        if (urlConnection instanceof JarURLConnection) {
            return FileUtils.copyJarResourcesRecursively(destination, (JarURLConnection) urlConnection);
        } else {
            return FileUtils.copyFilesRecusively(new File(originUrl.getPath()), destination);
        }
    } catch (final IOException e) {
        e.printStackTrace();
    }
    return false;
}
 
Example 34
Project: KernelHive   File: JarFileLoaderService.java   Source Code and License 5 votes vote down vote up
private String getJarVersion(final String jarUrl) {
	String version = null;
	try {
		final URL url = new URL("jar:" + jarUrl + "!/");
		final JarURLConnection juc = (JarURLConnection) url
				.openConnection();
		final JarFile jf = juc.getJarFile();
		final Attributes attrs = jf.getManifest().getMainAttributes();
		version = attrs.getValue("Manifest-Version");
	} catch (final IOException e) {
		e.printStackTrace();
	}
	return version;
}
 
Example 35
Project: incubator-ratis   File: RaftProperties.java   Source Code and License 5 votes vote down vote up
private Document parse(DocumentBuilder builder, URL url)
    throws IOException, SAXException {
  LOG.debug("parsing URL " + url);
  if (url == null) {
    return null;
  }

  URLConnection connection = url.openConnection();
  if (connection instanceof JarURLConnection) {
    // Disable caching for JarURLConnection to avoid sharing JarFile
    // with other users.
    connection.setUseCaches(false);
  }
  return parse(builder, connection.getInputStream(), url.toString());
}
 
Example 36
Project: osc-core   File: JarURLConnector.java   Source Code and License 5 votes vote down vote up
@Override
public TaggedData connectTagged(URL url) throws Exception {
	URLConnection connection = url.openConnection();
	if (connection instanceof JarURLConnection) {
           connection.setUseCaches(false);
       }
	return new TaggedData(connection, connection.getInputStream());
}
 
Example 37
Project: lams   File: TldLocationsCache.java   Source Code and License 5 votes vote down vote up
private void scanJars() throws Exception {

        ClassLoader webappLoader
            = Thread.currentThread().getContextClassLoader();
        ClassLoader loader = webappLoader;

        while (loader != null) {
            if (loader instanceof URLClassLoader) {
                URL[] urls = ((URLClassLoader) loader).getURLs();
                for (int i=0; i<urls.length; i++) {
                    URLConnection conn = urls[i].openConnection();
                    if (conn instanceof JarURLConnection) {
                        if (needScanJar(loader, webappLoader,
                                        ((JarURLConnection) conn).getJarFile().getName())) {
                            scanJar((JarURLConnection) conn, true);
                        }
                    } else {
                        String urlStr = urls[i].toString();
                        if (urlStr.startsWith(FILE_PROTOCOL)
                                && urlStr.endsWith(JAR_FILE_SUFFIX)
                                && needScanJar(loader, webappLoader, urlStr)) {
                            URL jarURL = new URL("jar:" + urlStr + "!/");
                            scanJar((JarURLConnection) jarURL.openConnection(),
                                    true);
                        }
                    }
                }
            }

            loader = loader.getParent();
        }
    }
 
Example 38
Project: kowalski   File: ClassResolver.java   Source Code and License 5 votes vote down vote up
/**
 * @see <a
 *      href="http://docs.oracle.com/javase/7/docs/technotes/guides/io/fsp/zipfilesystemprovider.html"http://docs.oracle.com/javase/7/docs/technotes/guides/io/fsp/zipfilesystemprovider.html</a>
 * @see <a href=
 *      "http://stackoverflow.com/questions/8014099/how-do-i-convert-a-jarfile-uri-to-the-path-of-jar-file">http://stackoverflow.com/questions/8014099/how-do-i-convert-a-jarfile-uri-to-the-path-of-jar-file</a>
 * @param clazz
 * @return
 * @throws URISyntaxException
 * @throws IOException
 */
private Optional<Artifact> resolveByResource(Class clazz) throws URISyntaxException, IOException {
	URL url = this.classLoader.getResource(clazz.getName().replaceAll("\\.", "/") + ".class");
	if (url == null) {
		return Optional.empty();
	}
	URI uri = url.toURI();
	this.fileSystemsUp.add(FileSystemSynchronizer.INSTANCE.up(uri));
	if (uri.getScheme().equals("jar")) {
		JarURLConnection connection = (JarURLConnection) uri.toURL().openConnection();
		uri = connection.getJarFileURL().toURI();
	}
	return this.find(Paths.get(uri).toAbsolutePath());
}
 
Example 39
Project: javaide   File: URLClassPath.java   Source Code and License 5 votes vote down vote up
static void check(URL url) throws IOException {
    SecurityManager security = System.getSecurityManager();
    if (security != null) {
        URLConnection urlConnection = url.openConnection();
        Permission perm = urlConnection.getPermission();
        if (perm != null) {
            try {
                security.checkPermission(perm);
            } catch (SecurityException se) {
                // fallback to checkRead/checkConnect for pre 1.2
                // security managers
                if ((perm instanceof java.io.FilePermission) &&
                    perm.getActions().indexOf("read") != -1) {
                    security.checkRead(perm.getName());
                } else if ((perm instanceof
                    java.net.SocketPermission) &&
                    perm.getActions().indexOf("connect") != -1) {
                    URL locUrl = url;
                    if (urlConnection instanceof JarURLConnection) {
                        locUrl = ((JarURLConnection)urlConnection).getJarFileURL();
                    }
                    security.checkConnect(locUrl.getHost(),
                                          locUrl.getPort());
                } else {
                    throw se;
                }
            }
        }
    }
}
 
Example 40
Project: bfmvc   File: ClassUtil.java   Source Code and License 5 votes vote down vote up
/**
 * 获取指定包下所有类
 *
 * @param packageName
 * @return
 */
public static ArrayList<Class<?>> getClasses(String packageName) {
    ArrayList<Class<?>> classes = new ArrayList<>();
    try {
        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(classes, packagePath, packageName);
                } else if (protocol.equals("jar")) {
                    JarURLConnection jarURLConnection = (JarURLConnection) url.openConnection();
                    if (jarURLConnection != null) {
                        JarFile jarFile = jarURLConnection.getJarFile();
                        if (jarFile != null) {
                            Enumeration<JarEntry> jarEntries = jarFile.entries();
                            while (jarEntries.hasMoreElements()) {
                                JarEntry jarEntry = jarEntries.nextElement();
                                String jarEntryName = jarEntry.getName();
                                if (jarEntryName.equals(".class")) {
                                    String className = jarEntryName.substring(0, jarEntryName.lastIndexOf(".")).replaceAll("/", ".");
                                    doAddClass(classes, className);
                                }
                            }
                        }
                    }
                }
            }
        }
    } catch (Exception e) {
       e.printStackTrace();
        throw new RuntimeException(e);
    }
    return classes;
}
 
Example 41
Project: OpenJSharp   File: URLClassPath.java   Source Code and License 5 votes vote down vote up
static void check(URL url) throws IOException {
    SecurityManager security = System.getSecurityManager();
    if (security != null) {
        URLConnection urlConnection = url.openConnection();
        Permission perm = urlConnection.getPermission();
        if (perm != null) {
            try {
                security.checkPermission(perm);
            } catch (SecurityException se) {
                // fallback to checkRead/checkConnect for pre 1.2
                // security managers
                if ((perm instanceof java.io.FilePermission) &&
                    perm.getActions().indexOf("read") != -1) {
                    security.checkRead(perm.getName());
                } else if ((perm instanceof
                    java.net.SocketPermission) &&
                    perm.getActions().indexOf("connect") != -1) {
                    URL locUrl = url;
                    if (urlConnection instanceof JarURLConnection) {
                        locUrl = ((JarURLConnection)urlConnection).getJarFileURL();
                    }
                    security.checkConnect(locUrl.getHost(),
                                          locUrl.getPort());
                } else {
                    throw se;
                }
            }
        }
    }
}
 
Example 42
Project: OpenJSharp   File: URLClassPath.java   Source Code and License 5 votes vote down vote up
private JarFile getJarFile(URL url) throws IOException {
    // Optimize case where url refers to a local jar file
    if (isOptimizable(url)) {
        FileURLMapper p = new FileURLMapper (url);
        if (!p.exists()) {
            throw new FileNotFoundException(p.getPath());
        }
        return checkJar(new JarFile(p.getPath()));
    }
    URLConnection uc = getBaseURL().openConnection();
    uc.setRequestProperty(USER_AGENT_JAVA_VERSION, JAVA_VERSION);
    JarFile jarFile = ((JarURLConnection)uc).getJarFile();
    return checkJar(jarFile);
}
 
Example 43
Project: OpenJSharp   File: ExtCheck.java   Source Code and License 5 votes vote down vote up
private JarFile findJarFile(URL url) throws IOException {
    // Optimize case where url refers to a local jar file
    if ("file".equals(url.getProtocol())) {
        String path = url.getFile().replace('/', File.separatorChar);
        File file = new File(path);
        if (!file.exists()) {
            throw new FileNotFoundException(path);
        }
        return new JarFile(path);
    }
    URLConnection uc = getBaseURL().openConnection();
    //uc.setRequestProperty(USER_AGENT_JAVA_VERSION, JAVA_VERSION);
    return ((JarURLConnection)uc).getJarFile();
}
 
Example 44
Project: SmartFramework   File: ClassUtil.java   Source Code and License 5 votes vote down vote up
/**
 * 获取包名下的所有类
 */
public static Set<Class<?>> getClassSet(String packageName){
    Set<Class<?>> classSet = new HashSet<Class<?>>();
    try{
        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){
                            Enumeration<JarEntry> jarEnties = jarFile.entries();
                            while(jarEnties.hasMoreElements()){
                                JarEntry jarEntry = jarEnties.nextElement();
                                String jarEntryName = jarEntry.getName();
                                if (jarEntryName.endsWith(".class")){
                                    String className= jarEntryName.substring(0,jarEntryName.lastIndexOf(".")).replaceAll("/",".");
                                    doAddClass(classSet,className);
                                }
                            }
                        }
                    }
                }
            }
        }
    }catch (Exception e){
        LOGGER.error("get class set failure", e);
        throw new RuntimeException(e);
    }
    return classSet;
}
 
Example 45
Project: ArchUnit   File: ClassFileSource.java   Source Code and License 5 votes vote down vote up
FromJar(URL jarUrl, String path, ImportOptions importOptions) {
    try {
        JarURLConnection connection = (JarURLConnection) jarUrl.openConnection();
        classFileLocations = FluentIterable.from(Collections.list(connection.getJarFile().entries()))
                .filter(classFilesBeneath(fixRelative(path)))
                .transform(toClassFilesInJarOf(connection))
                .filter(by(importOptions))
                .transform(toInputStreamSupplier());
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}
 
Example 46
Project: ArchUnit   File: ClassFileSource.java   Source Code and License 5 votes vote down vote up
private Function<JarEntry, ClassFileInJar> toClassFilesInJarOf(final JarURLConnection connection) {
    return new Function<JarEntry, ClassFileInJar>() {
        @Override
        public ClassFileInJar apply(JarEntry input) {
            return new ClassFileInJar(connection, input);
        }
    };
}
 
Example 47
Project: apache-tomcat-7.0.73-with-comment   File: BaseDirContext.java   Source Code and License 5 votes vote down vote up
/**
 * Add a resources JAR. The contents of /META-INF/resources/ will be used if
 * a requested resource can not be found in the main context.
 */
public void addResourcesJar(URL url) {
    try {
        JarURLConnection conn = (JarURLConnection) url.openConnection();
        JarFile jarFile = conn.getJarFile();   
        ZipEntry entry = jarFile.getEntry("/");
        WARDirContext warDirContext = new WARDirContext(jarFile,
                new WARDirContext.Entry("/", entry));
        warDirContext.loadEntries();
        altDirContexts.add(warDirContext);
    } catch (IOException ioe) {
        log.warn(sm.getString("resources.addResourcesJarFail", url), ioe);
    }
}
 
Example 48
Project: apache-tomcat-7.0.73-with-comment   File: UrlJar.java   Source Code and License 5 votes vote down vote up
private NonClosingJarInputStream createJarInputStream() throws IOException {
    JarURLConnection jarConn = (JarURLConnection) url.openConnection();
    URL resourceURL = jarConn.getJarFileURL();
    URLConnection resourceConn = resourceURL.openConnection();
    resourceConn.setUseCaches(false);
    return new NonClosingJarInputStream(resourceConn.getInputStream());
}
 
Example 49
Project: apache-tomcat-7.0.73-with-comment   File: JarURLResource.java   Source Code and License 5 votes vote down vote up
@Override
public JarFile getJarFile() throws IOException {
    URL jarFileUrl = new URL("jar:" + jarUrl + "!/");
    JarURLConnection conn = (JarURLConnection) jarFileUrl.openConnection();
    conn.setUseCaches(false);
    conn.connect();
    return conn.getJarFile();
}
 
Example 50
Project: winter   File: BuildInfo.java   Source Code and License 5 votes vote down vote up
public static Long getBuildTime(Class<?> cl) {
    try {
        String rn = cl.getName().replace('.', '/') + ".class";
        JarURLConnection j = (JarURLConnection) ClassLoader.getSystemResource(rn).openConnection();
        return j.getJarFile().getEntry("META-INF/MANIFEST.MF").getTime();
    } catch (Exception e) {
        return 0L;
    }
}
 
Example 51
Project: jdk8u-jdk   File: URLClassPath.java   Source Code and License 5 votes vote down vote up
static void check(URL url) throws IOException {
    SecurityManager security = System.getSecurityManager();
    if (security != null) {
        URLConnection urlConnection = url.openConnection();
        Permission perm = urlConnection.getPermission();
        if (perm != null) {
            try {
                security.checkPermission(perm);
            } catch (SecurityException se) {
                // fallback to checkRead/checkConnect for pre 1.2
                // security managers
                if ((perm instanceof java.io.FilePermission) &&
                    perm.getActions().indexOf("read") != -1) {
                    security.checkRead(perm.getName());
                } else if ((perm instanceof
                    java.net.SocketPermission) &&
                    perm.getActions().indexOf("connect") != -1) {
                    URL locUrl = url;
                    if (urlConnection instanceof JarURLConnection) {
                        locUrl = ((JarURLConnection)urlConnection).getJarFileURL();
                    }
                    security.checkConnect(locUrl.getHost(),
                                          locUrl.getPort());
                } else {
                    throw se;
                }
            }
        }
    }
}
 
Example 52
Project: jdk8u-jdk   File: URLClassPath.java   Source Code and License 5 votes vote down vote up
private JarFile getJarFile(URL url) throws IOException {
    // Optimize case where url refers to a local jar file
    if (isOptimizable(url)) {
        FileURLMapper p = new FileURLMapper (url);
        if (!p.exists()) {
            throw new FileNotFoundException(p.getPath());
        }
        return checkJar(new JarFile(p.getPath()));
    }
    URLConnection uc = getBaseURL().openConnection();
    uc.setRequestProperty(USER_AGENT_JAVA_VERSION, JAVA_VERSION);
    JarFile jarFile = ((JarURLConnection)uc).getJarFile();
    return checkJar(jarFile);
}
 
Example 53
Project: jdk8u-jdk   File: ExtCheck.java   Source Code and License 5 votes vote down vote up
private JarFile findJarFile(URL url) throws IOException {
    // Optimize case where url refers to a local jar file
    if ("file".equals(url.getProtocol())) {
        String path = url.getFile().replace('/', File.separatorChar);
        File file = new File(path);
        if (!file.exists()) {
            throw new FileNotFoundException(path);
        }
        return new JarFile(path);
    }
    URLConnection uc = getBaseURL().openConnection();
    //uc.setRequestProperty(USER_AGENT_JAVA_VERSION, JAVA_VERSION);
    return ((JarURLConnection)uc).getJarFile();
}
 
Example 54
Project: openjdk-jdk10   File: URLClassPath.java   Source Code and License 5 votes vote down vote up
public static void check(URL url) throws IOException {
    SecurityManager security = System.getSecurityManager();
    if (security != null) {
        URLConnection urlConnection = url.openConnection();
        Permission perm = urlConnection.getPermission();
        if (perm != null) {
            try {
                security.checkPermission(perm);
            } catch (SecurityException se) {
                // fallback to checkRead/checkConnect for pre 1.2
                // security managers
                if ((perm instanceof java.io.FilePermission) &&
                    perm.getActions().indexOf("read") != -1) {
                    security.checkRead(perm.getName());
                } else if ((perm instanceof
                    java.net.SocketPermission) &&
                    perm.getActions().indexOf("connect") != -1) {
                    URL locUrl = url;
                    if (urlConnection instanceof JarURLConnection) {
                        locUrl = ((JarURLConnection)urlConnection).getJarFileURL();
                    }
                    security.checkConnect(locUrl.getHost(),
                                          locUrl.getPort());
                } else {
                    throw se;
                }
            }
        }
    }
}
 
Example 55
Project: openjdk-jdk10   File: URLClassPath.java   Source Code and License 5 votes vote down vote up
private JarFile getJarFile(URL url) throws IOException {
    // Optimize case where url refers to a local jar file
    if (isOptimizable(url)) {
        FileURLMapper p = new FileURLMapper (url);
        if (!p.exists()) {
            throw new FileNotFoundException(p.getPath());
        }
        return checkJar(new JarFile(new File(p.getPath()), true, ZipFile.OPEN_READ,
                JarFile.runtimeVersion()));
    }
    URLConnection uc = (new URL(getBaseURL(), "#runtime")).openConnection();
    uc.setRequestProperty(USER_AGENT_JAVA_VERSION, JAVA_VERSION);
    JarFile jarFile = ((JarURLConnection)uc).getJarFile();
    return checkJar(jarFile);
}
 
Example 56
Project: openjdk-jdk10   File: MultiReleaseJarURLConnection.java   Source Code and License 5 votes vote down vote up
private boolean readAndCompare(URL url, String match) throws Exception {
    boolean result;
    // necessary to do it this way, instead of openStream(), so we can
    // close underlying JarFile, otherwise windows can't delete the file
    URLConnection conn = url.openConnection();
    try (InputStream is = conn.getInputStream()) {
        byte[] bytes = is.readAllBytes();
        result = (new String(bytes)).contains(match);
    }
    if (conn instanceof JarURLConnection) {
        ((JarURLConnection)conn).getJarFile().close();
    }
    return result;
}
 
Example 57
Project: openjdk-jdk10   File: TestBug4523159.java   Source Code and License 5 votes vote down vote up
public void run(String[] args) throws Exception {
    File tmp = createTempDir();
    try {
        File dir = new File(tmp, "dir!name");
        dir.mkdir();
        File testFile = copyResource(dir, "jar1.jar");

        // Case 1: direct access
        URL url = new URL("jar:" + testFile.toURI().toURL() + "!/res1.txt");
        JarURLConnection conn = (JarURLConnection) url.openConnection();
        JarFile file = conn.getJarFile();
        JarEntry entry = conn.getJarEntry();
        byte[] buffer = readFully(file.getInputStream(entry));
        String str = new String(buffer);
        if (!str.equals("This is jar 1\n")) {
            throw (new Exception("resource content invalid"));
        }

        // Case 2: indirect access
        URL[] urls = new URL[1];
        urls[0] = new URL("jar:" + testFile.toURI().toURL()  + "!/");
        URLClassLoader loader = new URLClassLoader(urls);
        loader.loadClass("jar1.GetResource").newInstance();
    } finally {
        deleteRecursively(tmp);
    }
}
 
Example 58
Project: pysonar2   File: $.java   Source Code and License 5 votes vote down vote up
public static void copyResourcesRecursively(URL originUrl, File destination) throws Exception {
    URLConnection urlConnection = originUrl.openConnection();
    if (urlConnection instanceof JarURLConnection) {
        copyJarResourcesRecursively(destination, (JarURLConnection) urlConnection);
    } else if (urlConnection instanceof FileURLConnection) {
        FileUtils.copyDirectory(new File(originUrl.getPath()), destination);
    } else {
        die("Unsupported URL type: " + urlConnection);
    }
}
 
Example 59
Project: spring-boot-seed   File: ClassFactory.java   Source Code and License 5 votes vote down vote up
private static void getClassInPackages(URL url, String packageDirName, String packageName, boolean recursive, Set<Class<?>> classes) throws IOException, ClassNotFoundException {
    JarFile jar;
    String varPackageName = packageName;

    jar = ((JarURLConnection) url.openConnection())
            .getJarFile();

    Enumeration<JarEntry> entries = jar.entries();

    while (entries.hasMoreElements()) {
        JarEntry entry = entries.nextElement();
        String name = entry.getName();

        if (name.charAt(0) == '/') {
            name = name.substring(1);
        }
        if (name.startsWith(packageDirName)) {
            int idx = name.lastIndexOf('/');
            if (idx != -1) {
                varPackageName = name.substring(0, idx)
                        .replace('/', '.');
            }
            if ((idx != -1 || recursive) && name.endsWith(".class")
                    && !entry.isDirectory()) {
                String className = name.substring(
                        varPackageName.length() + 1, name
                                .length() - 6);
                classes.add(Class
                        .forName(varPackageName + '.'
                                + className));
            }
        }
    }
}
 
Example 60
Project: lazycat   File: ContextConfig.java   Source Code and License 5 votes vote down vote up
@Override
public void scan(JarURLConnection jarConn) throws IOException {

	URL url = jarConn.getURL();
	URL resourceURL = jarConn.getJarFileURL();
	Jar jar = null;
	InputStream is = null;
	WebXml fragment = new WebXml();

	try {
		jar = JarFactory.newInstance(url);
		if (parseRequired || context.getXmlValidation()) {
			is = jar.getInputStream(FRAGMENT_LOCATION);
		}

		if (is == null) {
			// If there is no web-fragment.xml to process there is no
			// impact on distributable
			fragment.setDistributable(true);
		} else {
			InputSource source = new InputSource("jar:" + resourceURL.toString() + "!/" + FRAGMENT_LOCATION);
			source.setByteStream(is);
			parseWebXml(source, fragment, true);
		}
	} finally {
		if (jar != null) {
			jar.close();
		}
		fragment.setURL(url);
		if (fragment.getName() == null) {
			fragment.setName(fragment.getURL().toString());
		}
		fragment.setJarName(extractJarFileName(url));
		fragments.put(fragment.getName(), fragment);
	}
}