Java Code Examples for java.util.jar.JarEntry#isDirectory()

The following examples show how to use java.util.jar.JarEntry#isDirectory() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: PackTestZip64.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
static void generateLargeJar(File result, File source) throws IOException {
    if (result.exists()) {
        result.delete();
    }

    try (JarOutputStream copyTo = new JarOutputStream(new FileOutputStream(result));
         JarFile srcJar = new JarFile(source)) {

        for (JarEntry je : Collections.list(srcJar.entries())) {
            copyTo.putNextEntry(je);
            if (!je.isDirectory()) {
                copyStream(srcJar.getInputStream(je), copyTo);
            }
            copyTo.closeEntry();
        }

        int many = Short.MAX_VALUE * 2 + 2;

        for (int i = 0 ; i < many ; i++) {
            JarEntry e = new JarEntry("F-" + i + ".txt");
            copyTo.putNextEntry(e);
        }
        copyTo.flush();
        copyTo.close();
    }
}
 
Example 2
Source File: XmlFileScaner.java    From weed3 with Apache License 2.0 6 votes vote down vote up
/** 在 jar 包里查找目标 */
private static void doScanByJar(String path, JarFile jar, String suffix, Set<String> urls) {
    Enumeration<JarEntry> entry = jar.entries();

    while (entry.hasMoreElements()) {
        JarEntry e = entry.nextElement();
        String n = e.getName();

        if (n.charAt(0) == '/') {
            n = n.substring(1);
        }

        if (e.isDirectory() || !n.startsWith(path) || !n.endsWith(suffix)) {
            // 非指定包路径, 非目标后缀
            continue;
        }

        urls.add(n);
    }
}
 
Example 3
Source File: ChildURLClassLoaderTest.java    From cassandra-reaper with Apache License 2.0 6 votes vote down vote up
private static void list(String pathToJar) throws IOException, ClassNotFoundException {
  JarFile jarFile = new JarFile(pathToJar);
  URL[] urls = { new URL("jar:file:" + pathToJar + "!/") };
  URLClassLoader cl = URLClassLoader.newInstance(urls);

  for (JarEntry entry : Collections.list(jarFile.entries())) {
    if (entry.isDirectory()
        || !entry.getName().endsWith(".class")
        || !entry.getName().startsWith("io/cassandrareaper/")) {
      continue;
    }
    // -6 because of ".class"
    String className = entry.getName().substring(0, entry.getName().length() - 6).replace('/', '.');
    LOG.info(pathToJar + "!/" + className);
    cl.loadClass(className);
  }
}
 
Example 4
Source File: ResourceFinder.java    From tomee with Apache License 2.0 6 votes vote down vote up
private static void readJarEntries(final URL location, final String basePath, final Map<String, URL> resources) throws IOException {
    final JarURLConnection conn = (JarURLConnection) location.openConnection();
    final JarFile jarfile = conn.getJarFile();

    final Enumeration<JarEntry> entries = jarfile.entries();
    while (entries != null && entries.hasMoreElements()) {
        final 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;
        }

        final URL resource = new URL(location, name);
        resources.put(name, resource);
    }
}
 
Example 5
Source File: ClasspathCache.java    From glowroot with Apache License 2.0 6 votes vote down vote up
private static void loadClassNamesFromJarInputStream(JarInputStream jarIn, String directory,
        Location location, Multimap<String, Location> newClassNameLocations)
        throws IOException {
    JarEntry jarEntry;
    while ((jarEntry = jarIn.getNextJarEntry()) != null) {
        if (jarEntry.isDirectory()) {
            continue;
        }
        String name = jarEntry.getName();
        if (name.startsWith(directory) && name.endsWith(".class")) {
            name = name.substring(directory.length());
            String className = name.substring(0, name.lastIndexOf('.')).replace('/', '.');
            newClassNameLocations.put(className, location);
        }
    }
}
 
Example 6
Source File: BundledJarRunner.java    From twill with Apache License 2.0 6 votes vote down vote up
private void unJar(JarFile jarFile, File targetDirectory) throws IOException {
  Enumeration<JarEntry> entries = jarFile.entries();
  while (entries.hasMoreElements()) {
    JarEntry entry = entries.nextElement();
    File output = new File(targetDirectory, entry.getName());

    if (entry.isDirectory()) {
      output.mkdirs();
    } else {
      output.getParentFile().mkdirs();

      try (
        OutputStream os = new FileOutputStream(output);
        InputStream is = jarFile.getInputStream(entry)
      ) {
        ByteStreams.copy(is, os);
      }
    }
  }
}
 
Example 7
Source File: JarClassLoader.java    From hccd with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Finds native library entry.
 *
 * @param sLib Library name. For example for the library name "Native"
 *  - Windows returns entry "Native.dll"
 *  - Linux returns entry "libNative.so"
 *  - Mac returns entry "libNative.jnilib" or "libNative.dylib"
 *    (depending on Apple or Oracle JDK and/or JDK version)
 * @return Native library entry.
 */
private JarEntryInfo findJarNativeEntry(String sLib) {
    String sName = System.mapLibraryName(sLib);
    for (JarFileInfo jarFileInfo : lstJarFile) {
        JarFile jarFile = jarFileInfo.jarFile;
        Enumeration<JarEntry> en = jarFile.entries();
        while (en.hasMoreElements()) {
            JarEntry je = en.nextElement();
            if (je.isDirectory()) {
                continue;
            }
            // Example: sName is "Native.dll"
            String sEntry = je.getName(); // "Native.dll" or "abc/xyz/Native.dll"
            // sName "Native.dll" could be found, for example
            //   - in the path: abc/Native.dll/xyz/my.dll <-- do not load this one!
            //   - in the partial name: abc/aNative.dll   <-- do not load this one!
            String[] token = sEntry.split("/"); // the last token is library name
            if (token.length > 0 && token[token.length - 1].equals(sName)) {
                logInfo(LogArea.NATIVE, "Loading native library '%s' found as '%s' in JAR %s",
                        sLib, sEntry, jarFileInfo.simpleName);
                return new JarEntryInfo(jarFileInfo, je);
            }
        }
    }
    return null;
}
 
Example 8
Source File: JarUtils.java    From confucius-commons with Apache License 2.0 6 votes vote down vote up
/**
 * Extract the source {@link JarFile} to target directory with specified {@link JarEntryFilter}
 *
 * @param jarResourceURL
 *         The resource URL of {@link JarFile} or {@link JarEntry}
 * @param targetDirectory
 *         target directory
 * @param jarEntryFilter
 *         {@link JarEntryFilter}
 * @throws IOException
 *         When the source jar file is an invalid {@link JarFile}
 */
public static void extract(URL jarResourceURL, File targetDirectory, JarEntryFilter jarEntryFilter) throws IOException {
    final JarFile jarFile = JarUtils.toJarFile(jarResourceURL);
    final String relativePath = JarUtils.resolveRelativePath(jarResourceURL);
    final JarEntry jarEntry = jarFile.getJarEntry(relativePath);
    final boolean isDirectory = jarEntry.isDirectory();
    List<JarEntry> jarEntriesList = filter(jarFile, new JarEntryFilter() {
        @Override
        public boolean accept(JarEntry filteredObject) {
            String name = filteredObject.getName();
            if (isDirectory && name.equals(relativePath)) {
                return true;
            } else if (name.startsWith(relativePath)) {
                return true;
            }
            return false;
        }
    });

    jarEntriesList = doFilter(jarEntriesList, jarEntryFilter);

    doExtract(jarFile, jarEntriesList, targetDirectory);
}
 
Example 9
Source File: Maracas.java    From scava with Eclipse Public License 2.0 5 votes vote down vote up
private boolean unzipJarAlt(String pathJar, String pathDir) {
	try {
		FileInputStream fileStream = new FileInputStream(File.separator + pathJar);
		JarInputStream jarStream = new JarInputStream(fileStream);
		JarEntry entry = jarStream.getNextJarEntry();
		
		while (entry != null) {
			File fileEntry = new File(File.separator + pathDir + File.separator + entry.getName());
			
			if (entry.isDirectory()) {
				fileEntry.mkdirs();
			}
			else {
				FileOutputStream os = new FileOutputStream(fileEntry);
				
				while (jarStream.available() > 0) {
					os.write(jarStream.read());
				}
				
				os.close();
			}
			entry = jarStream.getNextJarEntry();
		}
		
		jarStream.close();
		return true;
	} 
	catch (IOException e) {
		e.printStackTrace();
	}
	
	return false;
}
 
Example 10
Source File: MarshallingTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
/**
 * In this case we are dealing with facts which are not on the systems classpath.
 */
@Test
public void testSerializabilityWithJarFacts() throws Exception {
    MapBackedClassLoader loader = new MapBackedClassLoader( this.getClass().getClassLoader() );

    JarInputStream jis = new JarInputStream( this.getClass().getResourceAsStream( "/billasurf.jar" ) );

    JarEntry entry = null;
    byte[] buf = new byte[1024];
    int len = 0;
    while ( (entry = jis.getNextJarEntry()) != null ) {
        if ( !entry.isDirectory() ) {
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            while ( (len = jis.read( buf )) >= 0 ) {
                out.write( buf,
                           0,
                           len );
            }
            loader.addResource( entry.getName(),
                                out.toByteArray() );
        }
    }

    String drl = "package foo.bar \n" +
                 "import com.billasurf.Board\n" +
                 "rule 'MyGoodRule' \n dialect 'mvel' \n when " +
                 "   Board() " +
                 "then \n" +
                 " System.err.println(42); \n" +
                 "end\n";


    KnowledgeBuilderConfiguration kbuilderConf = KnowledgeBuilderFactory.newKnowledgeBuilderConfiguration(null, loader);

    Collection<KiePackage>  kpkgs = loadKnowledgePackagesFromString(kbuilderConf, drl);

    kpkgs = SerializationHelper.serializeObject( kpkgs, loader );

}
 
Example 11
Source File: DeployUtil.java    From jumbune with GNU Lesser General Public License v3.0 5 votes vote down vote up
private boolean copyJarResources(final File destDir, final JarFile jarFile,
		final JarEntry entry) throws IOException {
	String filename = entry.getName();
	final File f = new File(destDir, filename);
	if (!entry.isDirectory()) {
		InputStream entryInputStream = null;
		try {
			entryInputStream = jarFile.getInputStream(entry);
			if (!copyStream(entryInputStream, f)) {
				return false;
			}

			if (filename.indexOf("htfconf") != -1 || filename.indexOf(".properties") != -1
					|| filename.indexOf(".yaml") != -1) {
				DEBUG_FILE_LOGGER.debug("Replacing placeholders for [" + filename + "]");
				replacePlaceHolders(f, FoundPaths);
			}
		} finally {
			if (entryInputStream != null) {
				entryInputStream.close();
			}
		}

	} else {
		if (!ensureDirectoryExists(f)) {
			throw new IOException("Error occurred while extracting : " + f.getAbsolutePath());
		}
	}
	return true;
}
 
Example 12
Source File: URLHandler.java    From j2objc with Apache License 2.0 5 votes vote down vote up
@Override
public void guide(URLVisitor v, boolean recurse, boolean strip) {
    try {
        Enumeration<JarEntry> entries = jarFile.entries();

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

            if (!entry.isDirectory()) { // skip just directory paths
                String name = entry.getName();

                if (name.startsWith(prefix)) {
                    name = name.substring(prefix.length());
                    int ix = name.lastIndexOf('/');
                    if (ix > 0 && !recurse) {
                        continue;
                    }
                    if (strip && ix != -1) {
                        name = name.substring(ix+1);
                    }
                    v.visit(name);
                }
            }
        }
    }
    catch (Exception e) {
        if (DEBUG) System.err.println("icurb jar error: " + e);
    }
}
 
Example 13
Source File: WebjarsResourceHandler.java    From pippo with Apache License 2.0 5 votes vote down vote up
/**
 * Locate all Webjars Maven pom.properties files on the classpath.
 *
 * @return a list of Maven pom.properties files on the classpath
 */
private List<String> locatePomProperties() {
    List<String> propertiesFiles = new ArrayList<>();
    List<URL> packageUrls = ClasspathUtils.getResources(getResourceBasePath());
    for (URL packageUrl : packageUrls) {
        if (packageUrl.getProtocol().equals("jar")) {
            // We only care about Webjars jar files
            log.debug("Scanning {}", packageUrl);
            try {
                String jar = packageUrl.toString().substring("jar:".length()).split("!")[0];
                File file = new File(new URI(jar));
                try (JarInputStream is = new JarInputStream(new FileInputStream(file))) {
                    JarEntry entry = null;
                    while ((entry = is.getNextJarEntry()) != null) {
                        if (!entry.isDirectory() && entry.getName().endsWith("pom.properties")) {
                            propertiesFiles.add(entry.getName());
                        }
                    }
                }
            } catch (URISyntaxException | IOException e) {
                throw new PippoRuntimeException("Failed to get classes for package '{}'", packageUrl);
            }
        }
    }

    return propertiesFiles;
}
 
Example 14
Source File: TestNormal.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
public static void extractJar(JarFile jf, File where) throws Exception {
    for (JarEntry file : Collections.list(jf.entries())) {
        File out = new File(where, file.getName());
        if (file.isDirectory()) {
            out.mkdirs();
            continue;
        }
        File parent = out.getParentFile();
        if (parent != null && !parent.exists()) {
            parent.mkdirs();
        }
        InputStream is = null;
        OutputStream os = null;
        try {
            is = jf.getInputStream(file);
            os = new FileOutputStream(out);
            while (is.available() > 0) {
                os.write(is.read());
            }
        } finally {
            if (is != null) {
                is.close();
            }
            if (os != null) {
                os.close();
            }
        }
    }
}
 
Example 15
Source File: CarMain.java    From component-runtime with Apache License 2.0 5 votes vote down vote up
private static String installJars(final File m2Root, final boolean forceOverwrite) {
    String mainGav = null;
    try (final JarInputStream jar =
            new JarInputStream(new BufferedInputStream(new FileInputStream(jarLocation(CarMain.class))))) {
        JarEntry entry;
        while ((entry = jar.getNextJarEntry()) != null) {
            if (entry.isDirectory()) {
                continue;
            }
            if (entry.getName().startsWith("MAVEN-INF/repository/")) {
                final String path = entry.getName().substring("MAVEN-INF/repository/".length());
                final File output = new File(m2Root, path);
                if (!output.getCanonicalPath().startsWith(m2Root.getCanonicalPath())) {
                    throw new IOException("The output file is not contained in the destination directory");
                }
                if (!output.exists() || forceOverwrite) {
                    output.getParentFile().mkdirs();
                    Files.copy(jar, output.toPath(), StandardCopyOption.REPLACE_EXISTING);
                }
            } else if ("TALEND-INF/metadata.properties".equals(entry.getName())) {
                // mainGav
                final Properties properties = new Properties();
                properties.load(jar);
                mainGav = properties.getProperty("component_coordinates");
            }
        }
    } catch (final IOException e) {
        throw new IllegalArgumentException(e);
    }
    if (mainGav == null || mainGav.trim().isEmpty()) {
        throw new IllegalArgumentException("Didn't find the component coordinates");
    }
    return mainGav;
}
 
Example 16
Source File: TestNormal.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
public static void extractJar(JarFile jf, File where) throws Exception {
    for (JarEntry file : Collections.list(jf.entries())) {
        File out = new File(where, file.getName());
        if (file.isDirectory()) {
            out.mkdirs();
            continue;
        }
        File parent = out.getParentFile();
        if (parent != null && !parent.exists()) {
            parent.mkdirs();
        }
        InputStream is = null;
        OutputStream os = null;
        try {
            is = jf.getInputStream(file);
            os = new FileOutputStream(out);
            while (is.available() > 0) {
                os.write(is.read());
            }
        } finally {
            if (is != null) {
                is.close();
            }
            if (os != null) {
                os.close();
            }
        }
    }
}
 
Example 17
Source File: Scaner.java    From ICERest with Apache License 2.0 5 votes vote down vote up
private Set<String> findInJar(JarFile localJarFile, String packageName) {
    Set<String> classFiles = new HashSet<String>();
    Enumeration<JarEntry> entries = localJarFile.entries();
    while (entries.hasMoreElements()) {
        JarEntry jarEntry = entries.nextElement();
        String entryName = jarEntry.getName();
        if (!jarEntry.isDirectory() && (packageName == null || entryName.startsWith(packageName)) && entryName.endsWith(".class")) {
            String className = entryName.replaceAll("/", ".").substring(0, entryName.length() - 6);
            classFiles.add(className);
        }
    }
    return classFiles;
}
 
Example 18
Source File: JarFinderHandler.java    From LicenseScout with Apache License 2.0 4 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public boolean isFile(final JarEntry entry) {
    return !entry.isDirectory();
}
 
Example 19
Source File: EncoderManager.java    From PacketProxy with Apache License 2.0 4 votes vote down vote up
private void loadModulesFromJar(HashMap<String,Class<Encoder>> module_list) throws Exception
{
	File[] files = new File(DEFAULT_PLUGIN_DIR).listFiles();
	if(null==files){
		return;
	}
	for(File file:files){
		if(!file.isFile() || !"jar".equals(FilenameUtils.getExtension(file.getName()))){
			continue;
		}
		URLClassLoader urlClassLoader = URLClassLoader.newInstance(new URL[]{file.toURI().toURL()});
		JarFile jarFile = new JarFile(file.getPath());
		for (Enumeration<JarEntry> entries = jarFile.entries(); entries.hasMoreElements(); )
		{
			//Jar filter
			JarEntry jarEntry = entries.nextElement();
			if (jarEntry.isDirectory()) continue;

			// class filter
			String fileName = jarEntry.getName();
			if (!fileName.endsWith(".class")) continue;

			Class<?> klass;
			try {
				//jar内のクラスファイルの階層がパッケージに準拠している必要がある
				//例: packetproxy.plugin.EncodeHTTPSample
				//-> packetproxy/plugin/EncodeHTTPSample.class
				String encode_class_path = fileName.replaceAll("\\.class.*$", "").replaceAll("/",".");
				klass = urlClassLoader.loadClass(encode_class_path);
			} catch (Exception e) {
				e.printStackTrace();
				continue;
			}

			// Encode Classを継承しているか
			if (!encode_class.isAssignableFrom(klass)) continue;
			if (Modifier.isAbstract(klass.getModifiers())) continue;

			@SuppressWarnings("unchecked")
			Encoder encoder = createInstance((Class<Encoder>)klass, null);
			String encoderName = encoder.getName();
			if(module_list.containsKey(encoderName)){
				isDuplicated = true;
				encoderName += "-" + file.getName();
			}
			module_list.put(encoderName, (Class<Encoder>)klass);
		}
	}
}
 
Example 20
Source File: JDBCConnectionModule.java    From components with Apache License 2.0 4 votes vote down vote up
public ValidationResult afterSelectClass() {
    List<String> driverClasses = new ArrayList<>();

    AllSetting setting = new AllSetting();
    setting.setDriverPaths(driverTable.drivers.getValue());
    List<String> jar_maven_paths = setting.getDriverPaths();

    try {
        List<URL> urls = new ArrayList<>();
        for (String maven_path : jar_maven_paths) {
            URL url = new URL(removeQuote(maven_path));
            urls.add(url);
        }

        URLClassLoader classLoader = new URLClassLoader(urls.toArray(new URL[0]), this.getClass().getClassLoader());

        for (URL jarUrl : urls) {
            try (JarInputStream jarInputStream = new JarInputStream(jarUrl.openStream())) {
                JarEntry nextJarEntry = jarInputStream.getNextJarEntry();
                while (nextJarEntry != null) {
                    boolean isFile = !nextJarEntry.isDirectory();
                    if (isFile) {
                        String name = nextJarEntry.getName();
                        if (name != null && name.toLowerCase().endsWith(".class")) {
                            String className = changeFileNameToClassName(name);
                            try {
                                Class clazz = classLoader.loadClass(className);
                                if (Driver.class.isAssignableFrom(clazz)) {
                                    driverClasses.add(clazz.getName());
                                }
                            } catch (Throwable th) {
                                // ignore all the exceptions, especially the class not found exception when look up a class
                                // outside the jar
                            }
                        }
                    }

                    nextJarEntry = jarInputStream.getNextJarEntry();
                }
            }
        }
    } catch (Exception ex) {
        return new ValidationResult(ValidationResult.Result.ERROR, ex.getMessage());
    }

    if (driverClasses.isEmpty()) {
        return new ValidationResult(ValidationResult.Result.ERROR,
                "not found any Driver class, please make sure the jar is right");
    }

    driverClass.setPossibleValues(driverClasses);
    driverClass.setValue(driverClasses.get(0));

    return ValidationResult.OK;
}