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

The following examples show how to use java.util.jar.JarEntry#getName() . 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: JarFileAnalyzer.java    From pinpoint with Apache License 2.0 6 votes vote down vote up
@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);
    }
}
 
Example 2
Source File: ServiceArtifactBuilderTest.java    From exonum-java-binding with Apache License 2.0 6 votes vote down vote up
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;
}
 
Example 3
Source File: FindNativeFiles.java    From hottub with GNU General Public License v2.0 6 votes vote down vote up
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;
}
 
Example 4
Source File: TestNormal.java    From jdk8u-jdk with GNU General Public License v2.0 6 votes vote down vote up
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();
    }
}
 
Example 5
Source File: ClassReader.java    From dragonwell8_jdk with GNU General Public License v2.0 6 votes vote down vote up
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;
    }
}
 
Example 6
Source File: FileUtils.java    From JerryMouse with MIT License 6 votes vote down vote up
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();
}
 
Example 7
Source File: ClassReader.java    From openjdk-8 with GNU General Public License v2.0 6 votes vote down vote up
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;
    }
}
 
Example 8
Source File: JDKClassDumpTestCase.java    From commons-bcel with Apache License 2.0 6 votes vote down vote up
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);
                }
            }
        }
    }
}
 
Example 9
Source File: NarUnpacker.java    From pulsar with Apache License 2.0 6 votes vote down vote up
/**
 * 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);
    }
}
 
Example 10
Source File: ProviderFileWriterTest.java    From CogniCrypt with Eclipse Public License 2.0 6 votes vote down vote up
@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();
	}

}
 
Example 11
Source File: TestNormal.java    From openjdk-jdk8u 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 12
Source File: JarStringReader.java    From hprof-tools with MIT License 5 votes vote down vote up
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;
}
 
Example 13
Source File: Preload.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
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);
  }
}
 
Example 14
Source File: NarBundleExtractor.java    From nifi-registry with Apache License 2.0 5 votes vote down vote up
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.");
    }
}
 
Example 15
Source File: ClassFileReader.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
protected JarEntry nextEntry() {
    while (entries.hasMoreElements()) {
        JarEntry e = entries.nextElement();
        String name = e.getName();
        if (name.endsWith(".class")) {
            return e;
        }
    }
    return null;
}
 
Example 16
Source File: JarUtils.java    From Indic-Keyboard with Apache License 2.0 5 votes vote down vote up
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;
}
 
Example 17
Source File: FindNativeFiles.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
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);
    }
}
 
Example 18
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;
}
 
Example 19
Source File: TeraDataWalletInitializer.java    From azkaban-plugins with Apache License 2.0 4 votes vote down vote up
/**
 * 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());
}
 
Example 20
Source File: ClassPathUtils.java    From opoopress with Apache License 2.0 4 votes vote down vote up
/**
   * 
   * @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){
}
  }