java.util.jar.JarEntry#getName ( )源码实例Demo

下面列出了java.util.jar.JarEntry#getName ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: openjdk-8   文件: ClassReader.java
private static void doJar(String a, File source, File dest,
                          ClassReader options, String encoding,
                          Boolean contError) throws IOException {
    try {
        JarFile jf = new JarFile(source);
        for (JarEntry je : Collections.list(jf.entries())) {
            String name = je.getName();
            if (!name.endsWith(".class")) {
                continue;
            }
            try {
                doStream(name, jf.getInputStream(je), dest, options, encoding);
            } catch (Exception e) {
                if (contError) {
                    System.out.println("Error processing " + source + ": " + e);
                    e.printStackTrace();
                    continue;
                }
            }
        }
    } catch (IOException ioe) {
        throw ioe;
    }
}
 
源代码2 项目: CogniCrypt   文件: ProviderFileWriterTest.java
@Test
public void createJarFileTest() {
	try {

		final File[] files = this.folder.listFiles();
		for (final File file : files) {
			this.providerFile.zipProject(file.getAbsolutePath(), this.jarFile, true);

		}
		final JarFile jar = new JarFile(this.jarFile);
		final Enumeration<JarEntry> entries = jar.entries();
		while (entries.hasMoreElements()) {
			final JarEntry entry = entries.nextElement();
			final String entryName = entry.getName();
			this.elementExists = fileExists(files, entryName);
		}
		assertEquals(this.elementExists, true);
		jar.close();
	}
	catch (final IOException e) {
		e.printStackTrace();
	}

}
 
源代码3 项目: pulsar   文件: NarUnpacker.java
/**
 * Unpacks the NAR to the specified directory. Creates a checksum file that used to determine if future expansion is
 * necessary.
 *
 * @param workingDirectory
 *            the root directory to which the NAR should be unpacked.
 * @throws IOException
 *             if the NAR could not be unpacked.
 */
private static void unpack(final File nar, final File workingDirectory, final byte[] hash) throws IOException {

    try (JarFile jarFile = new JarFile(nar)) {
        Enumeration<JarEntry> jarEntries = jarFile.entries();
        while (jarEntries.hasMoreElements()) {
            JarEntry jarEntry = jarEntries.nextElement();
            String name = jarEntry.getName();
            File f = new File(workingDirectory, name);
            if (jarEntry.isDirectory()) {
                FileUtils.ensureDirectoryExistAndCanReadAndWrite(f);
            } else {
                makeFile(jarFile.getInputStream(jarEntry), f);
            }
        }
    }

    final File hashFile = new File(workingDirectory, HASH_FILENAME);
    try (final FileOutputStream fos = new FileOutputStream(hashFile)) {
        fos.write(hash);
    }
}
 
源代码4 项目: commons-bcel   文件: JDKClassDumpTestCase.java
private void testJar(final File file) throws Exception {
    System.out.println("parsing " + file);
    try (JarFile jar = new JarFile(file)) {
        final Enumeration<JarEntry> en = jar.entries();
        while (en.hasMoreElements()) {
            final JarEntry e = en.nextElement();
            final String name = e.getName();
            if (name.endsWith(".class")) {
                // System.out.println("parsing " + name);
                try (InputStream in = jar.getInputStream(e)) {
                    final ClassParser parser = new ClassParser(in, name);
                    final JavaClass jc = parser.parse();
                    compare(jc, jar.getInputStream(e), name);
                }
            }
        }
    }
}
 
源代码5 项目: pinpoint   文件: JarFileAnalyzer.java
@Override
public Providers filter(JarEntry jarEntry) {
    final String jarEntryName = jarEntry.getName();
    if (!jarEntryName.startsWith(SERVICE_LOADER)) {
        return null;
    }
    if (jarEntry.isDirectory()) {
        return null;
    }
    if (jarEntryName.indexOf('/', SERVICE_LOADER.length()) != -1) {
        return null;
    }
    try {
        InputStream inputStream = jarFile.getInputStream(jarEntry);

        ServiceDescriptorParser parser = new ServiceDescriptorParser();
        List<String> serviceImplClassName = parser.parse(inputStream);
        String serviceClassName = jarEntryName.substring(SERVICE_LOADER.length());
        return new Providers(serviceClassName, serviceImplClassName);
    } catch (IOException e) {
        throw new IllegalStateException(jarFile.getName() + " File read fail ", e);
    }
}
 
源代码6 项目: JerryMouse   文件: FileUtils.java
public static byte[] readFileFromJar(File file, String path) throws IOException {
    JarFile jarFile = new JarFile(file.getAbsolutePath());
    Enumeration<JarEntry> entries = jarFile.entries();
    JarEntry configEntry = null;
    while (entries.hasMoreElements()) {
        JarEntry jarEntry = entries.nextElement();
        String name = jarEntry.getName();
        if (path.equals(name)) {
            configEntry = jarEntry;
            break;
        }
    }
    if (configEntry == null) return null;
    InputStream input = jarFile.getInputStream(configEntry);
    byte[] buffer = new byte[4096];
    int n;
    ByteArrayOutputStream output = new ByteArrayOutputStream();
    while (-1 != (n = input.read(buffer))) {
        output.write(buffer, 0, n);
    }
    return output.toByteArray();
}
 
源代码7 项目: dragonwell8_jdk   文件: ClassReader.java
private static void doJar(String a, File source, File dest,
                          ClassReader options, String encoding,
                          Boolean contError) throws IOException {
    try {
        JarFile jf = new JarFile(source);
        for (JarEntry je : Collections.list(jf.entries())) {
            String name = je.getName();
            if (!name.endsWith(".class")) {
                continue;
            }
            try {
                doStream(name, jf.getInputStream(je), dest, options, encoding);
            } catch (Exception e) {
                if (contError) {
                    System.out.println("Error processing " + source + ": " + e);
                    e.printStackTrace();
                    continue;
                }
            }
        }
    } catch (IOException ioe) {
        throw ioe;
    }
}
 
源代码8 项目: jdk8u-jdk   文件: TestNormal.java
public static void compareJars(JarFile jf1, JarFile jf2) throws Exception {
    try {
        if (jf1.size() != jf2.size()) {
            throw new Exception("Jars " + jf1.getName() + " and " + jf2.getName()
                    + " have different number of entries");
        }
        for (JarEntry elem1 : Collections.list(jf1.entries())) {
            JarEntry elem2 = jf2.getJarEntry(elem1.getName());
            if (elem2 == null) {
                throw new Exception("Element " + elem1.getName() + " is missing from " + jf2.getName());
            }
            if (!elem1.isDirectory() && elem1.getCrc() != elem2.getCrc()) {
                throw new Exception("The crc of " + elem1.getName() + " is different.");
            }
        }
    } finally {
        jf1.close();
        jf2.close();
    }
}
 
源代码9 项目: hottub   文件: FindNativeFiles.java
boolean isNativeClass(JarFile jar, JarEntry entry) throws IOException, ConstantPoolException {
    String name = entry.getName();
    if (name.startsWith("META-INF") || !name.endsWith(".class"))
        return false;
    //String className = name.substring(0, name.length() - 6).replace("/", ".");
    //System.err.println("check " + className);
    InputStream in = jar.getInputStream(entry);
    ClassFile cf = ClassFile.read(in);
    in.close();
    for (int i = 0; i < cf.methods.length; i++) {
        Method m = cf.methods[i];
        if (m.access_flags.is(AccessFlags.ACC_NATIVE)) {
            // System.err.println(className);
            return true;
        }
    }
    return false;
}
 
private static Map<String, byte[]> readJarEntries(Path jarPath) throws IOException {
  Map<String, byte[]> allJarEntries = new TreeMap<>();
  try (JarInputStream in = new JarInputStream(new FileInputStream(jarPath.toFile()))) {
    // Add manifest
    byte[] manifest = manifestAsBytes(in);
    allJarEntries.put(JarFile.MANIFEST_NAME, manifest);

    // Add other entries
    JarEntry nextEntry;
    while ((nextEntry = in.getNextJarEntry()) != null) {
      String name = nextEntry.getName();
      byte[] bytes = ByteStreams.toByteArray(in);
      allJarEntries.put(name, bytes);
      in.closeEntry();
    }
  }
  return allJarEntries;
}
 
源代码11 项目: Indic-Keyboard   文件: JarUtils.java
public static ArrayList<String> getEntryNameListing(final JarFile jar, final JarFilter filter) {
    final ArrayList<String> result = new ArrayList<>();
    final Enumeration<JarEntry> entries = jar.entries();
    while (entries.hasMoreElements()) {
        final JarEntry entry = entries.nextElement();
        final String path = entry.getName();
        final int pos = path.lastIndexOf('/');
        final String dirName = (pos >= 0) ? path.substring(0, pos) : "";
        final String name = (pos >= 0) ? path.substring(pos + 1) : path;
        if (filter.accept(dirName, name)) {
            result.add(path);
        }
    }
    return result;
}
 
源代码12 项目: nifi-registry   文件: NarBundleExtractor.java
private void parseExtensionDocs(final JarInputStream jarInputStream, final BundleDetails.Builder builder) throws IOException {
    JarEntry jarEntry;
    boolean foundExtensionDocs = false;
    while((jarEntry = jarInputStream.getNextJarEntry()) != null) {
        final String jarEntryName = jarEntry.getName();
        if (EXTENSION_DESCRIPTOR_ENTRY.equals(jarEntryName)) {
            try {
                final byte[] rawDocsContent = toByteArray(jarInputStream);
                final ExtensionManifestParser docsParser = new JacksonExtensionManifestParser();
                final InputStream inputStream = new NonCloseableInputStream(new ByteArrayInputStream(rawDocsContent));

                final ExtensionManifest extensionManifest = docsParser.parse(inputStream);
                builder.addExtensions(extensionManifest.getExtensions());
                builder.systemApiVersion(extensionManifest.getSystemApiVersion());

                foundExtensionDocs = true;
            } catch (Exception e) {
                throw new BundleException("Unable to obtain extension info for bundle due to: " + e.getMessage(), e);
            }
        } else {
            final Matcher matcher = ADDITIONAL_DETAILS_ENTRY_PATTERN.matcher(jarEntryName);
            if (matcher.matches()) {
                final String extensionName = matcher.group(1);
                final String additionalDetailsContent = new String(toByteArray(jarInputStream), StandardCharsets.UTF_8);
                builder.addAdditionalDetails(extensionName, additionalDetailsContent);
            }
        }
    }

    if (!foundExtensionDocs) {
        throw new BundleException("Unable to find descriptor at '" + EXTENSION_DESCRIPTOR_ENTRY + "'. " +
                "This NAR may need to be rebuilt with the latest version of the NiFi NAR Maven Plugin.");
    }
}
 
源代码13 项目: openjdk-jdk8u   文件: TestNormal.java
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();
            }
        }
    }
}
 
源代码14 项目: hprof-tools   文件: JarStringReader.java
public static Set<String> readStrings(@Nonnull File in) throws IOException {
    Set<String> strings = new HashSet<String>();
    JarFile file = new JarFile(in);
    for (JarEntry entry : Collections.list(file.entries())) {
        String name = entry.getName();
        if (!name.endsWith(".class")) {
            continue;
        }
        name = name.substring(0, name.length() - 6);
        strings.add(name.replace(File.pathSeparator, "."));
    }
    return strings;
}
 
源代码15 项目: gemfirexd-oss   文件: Preload.java
private void preloadJarEntry(Object obj) {
  long start, elapsed;
  JarEntry entry = (JarEntry)obj;
  String name = entry.getName();
  int classIndex = name.indexOf(".class");
  if (classIndex != -1) {
    long size = entry.getSize();
    //long compressedSize = entry.getCompressedSize();
    String classFileName = name.replace('/', '.');
    String className = classFileName.substring(0, classIndex);
    preloadClass(className, size);
  }
}
 
源代码16 项目: openjdk-jdk8u   文件: ClassFileReader.java
protected JarEntry nextEntry() {
    while (entries.hasMoreElements()) {
        JarEntry e = entries.nextElement();
        String name = e.getName();
        if (name.endsWith(".class")) {
            return e;
        }
    }
    return null;
}
 
源代码17 项目: jdk8u60   文件: FindNativeFiles.java
public void run(String[] args) throws IOException, ConstantPoolException {
    JarFile jar = new JarFile(args[0]);
    Set<JarEntry> entries = getNativeClasses(jar);
    for (JarEntry e: entries) {
        String name = e.getName();
        String className = name.substring(0, name.length() - 6).replace("/", ".");
        System.out.println(className);
    }
}
 
源代码18 项目: opoopress   文件: ClassPathUtils.java
/**
   * 
   * @param jarFileURL
   * @param sourcePath
   * @param destination
   * @param overwrite
   * @throws Exception
   */
  protected static void copyJarPath(URL jarFileURL, String sourcePath, File destination, boolean overwrite)throws Exception{
  	//URL jarFileURL = ResourceUtils.extractJarFileURL(url);
  	if(!sourcePath.endsWith("/")){
  		sourcePath += "/";
  	}
  	String root = jarFileURL.toString() + "!/";
  	if(!root.startsWith("jar:")){
  		root = "jar:" + root;
  	}
  	
  	JarFile jarFile = new JarFile(new File(jarFileURL.toURI()));
Enumeration<JarEntry> entries = jarFile.entries();
while (entries.hasMoreElements()) {
	JarEntry jarEntry = entries.nextElement();
	String name = jarEntry.getName();
	//log.debug(name + "." + sourcePath + "." + name.startsWith(sourcePath));
	if(name.startsWith(sourcePath)){
		String relativePath = name.substring(sourcePath.length());
		//log.debug("relativePath: " + relativePath);
		if(relativePath != null && relativePath.length() > 0){
			File tmp = new File(destination, relativePath);
			//not exists or overwrite permitted
			if(overwrite || !tmp.exists()){
				if(jarEntry.isDirectory()){
					tmp.mkdirs();
					if(IS_DEBUG_ENABLED){
						log.debug("Create directory: " + tmp);
					}
				}else{
					File parent = tmp.getParentFile();
					if(!parent.exists()){
						parent.mkdirs();
					}
					//1.FileCopyUtils.copy
					//InputStream is = jarFile.getInputStream(jarEntry);
					//FileCopyUtils.copy(is, new FileOutputStream(tmp));
					
					//2. url copy
					URL u = new URL(root + name);
					//log.debug(u.toString());
					FileUtils.copyURLToFile(u, tmp);
					if(IS_DEBUG_ENABLED){
						log.debug("Copyed file '" + u + "' to '" + tmp + "'.");
					}
				}
			}
		}
	}
}

try{
	jarFile.close();
}catch(Exception ie){
}
  }
 
源代码19 项目: components   文件: JDBCConnectionModule.java
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;
}
 
/**
 * As of TDCH 1.4.1, integration with Teradata wallet only works with hadoop jar command line command.
 * This is mainly because TDCH depends on the behavior of hadoop jar command line which extracts jar file
 * into hadoop tmp folder.
 *
 * This method will extract tdchJarfile and place it into temporary folder, and also add jvm shutdown hook
 * to delete the directory when JVM shuts down.
 * @param tdchJarFile TDCH jar file.
 */
public static void initialize(File tmpDir, File tdchJarFile) {
  synchronized (TeraDataWalletInitializer.class) {
    if (tdchJarExtractedDir != null) {
      return;
    }

    if (tdchJarFile == null) {
      throw new IllegalArgumentException("TDCH jar file cannot be null.");
    }
    if (!tdchJarFile.exists()) {
      throw new IllegalArgumentException("TDCH jar file does not exist. " + tdchJarFile.getAbsolutePath());
    }
    try {
      //Extract TDCH jar.
        File unJarDir = createUnjarDir(new File(tmpDir.getAbsolutePath() + File.separator + UNJAR_DIR_NAME));
        JarFile jar = new JarFile(tdchJarFile);
        Enumeration<JarEntry> enumEntries = jar.entries();

        while (enumEntries.hasMoreElements()) {
          JarEntry srcFile = enumEntries.nextElement();
          File destFile = new File(unJarDir + File.separator + srcFile.getName());
          if (srcFile.isDirectory()) { // if its a directory, create it
            destFile.mkdir();
            continue;
          }

          InputStream is = jar.getInputStream(srcFile);
          BufferedOutputStream os = new BufferedOutputStream(new FileOutputStream(destFile));
          IOUtils.copy(is, os);
          close(os);
          close(is);
        }
        jar.close();
        tdchJarExtractedDir = unJarDir;
    } catch (IOException e) {
      throw new RuntimeException("Failed while extracting TDCH jar file.", e);
    }
  }
  logger.info("TDCH jar has been extracted into directory: " + tdchJarExtractedDir.getAbsolutePath());
}