Java Code Examples for java.util.jar.JarEntry

The following are top voted examples for showing how to use java.util.jar.JarEntry. 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: Jenisys3   File: JavaPluginLoader.java   View source code 8 votes vote down vote up
@Override
public PluginDescription getPluginDescription(File file) {
    try (JarFile jar = new JarFile(file)) {
        JarEntry entry = jar.getJarEntry("nukkit.yml");
        if (entry == null) {
            entry = jar.getJarEntry("plugin.yml");
            if (entry == null) {
                return null;
            }
        }
        try (InputStream stream = jar.getInputStream(entry)) {
            return new PluginDescription(Utils.readFile(stream));
        }
    } catch (IOException e) {
        return null;
    }
}
 
Example 2
Project: nymph   File: ScannerNymphBeans.java   View source code 6 votes vote down vote up
/**
 * 解析jar包中的类
 * @param jarFile			表示jar文件
 * @param packageLocation	扫描的包路径
 * @throws Exception 反射时的异常
 */
private void resolveJar(JarFile jarFile, String packageLocation) throws Exception {
	Enumeration<JarEntry> entries = jarFile.entries();
	while (entries.hasMoreElements()) {
		String classLocation = entries.nextElement().getName();
		// 当jar文件中的路径是以packageLocation指定的路径开头,并且是以.class结尾时
		if (classLocation.startsWith(packageLocation) && classLocation.endsWith(".class")) {
			String location = classLocation.replace(".class", "").replace("/", ".");
			Class<?> forName = Class.forName(location);
			configurationBeansHandler(forName);
			Annotation[] annos = forName.getAnnotations();
			if (AnnoUtil.exist(annos, Bean.class) && !forName.isInterface()) {
				beansInitializedHandler(forName);
			}
		}
	}
}
 
Example 3
Project: incubator-netbeans   File: ModuleManagerTest.java   View source code 6 votes vote down vote up
private File copyJar(File file, String manifest) throws IOException {
    File ret = File.createTempFile(file.getName(), "2ndcopy", file.getParentFile());
    JarFile jar = new JarFile(file);
    JarOutputStream os = new JarOutputStream(new FileOutputStream(ret), new Manifest(
        new ByteArrayInputStream(manifest.getBytes())
    ));
    Enumeration<JarEntry> en = jar.entries();
    while (en.hasMoreElements()) {
        JarEntry elem = en.nextElement();
        if (elem.getName().equals("META-INF/MANIFEST.MF")) {
            continue;
        }
        os.putNextEntry(elem);
        InputStream is = jar.getInputStream(elem);
        copyStreams(is, os);
        is.close();
    }
    os.close();
    return ret;
}
 
Example 4
Project: incubator-netbeans   File: SetupHid.java   View source code 6 votes vote down vote up
private static void writeJarEntry(JarOutputStream jos, String path, File f) throws IOException, FileNotFoundException {
    JarEntry je = new JarEntry(path);
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    InputStream is = new FileInputStream(f);
    try {
        copyStreams(is, baos);
    } finally {
        is.close();
    }
    byte[] data = baos.toByteArray();
    je.setSize(data.length);
    CRC32 crc = new CRC32();
    crc.update(data);
    je.setCrc(crc.getValue());
    jos.putNextEntry(je);
    jos.write(data);
}
 
Example 5
Project: Agent   File: Agent.java   View source code 6 votes vote down vote up
public static File createAgent(Class<?> agent, Class<?>... resources) throws IOException {
    File jarFile = File.createTempFile("agent", ".jar");
    jarFile.deleteOnExit();
    Manifest manifest = new Manifest();
    Attributes mainAttributes = manifest.getMainAttributes();
    mainAttributes.put(Name.MANIFEST_VERSION, "1.0");
    mainAttributes.put(new Name("Agent-Class"), agent.getName());
    mainAttributes.put(new Name("Can-Retransform-Classes"), "true");
    mainAttributes.put(new Name("Can-Redefine-Classes"), "true");
    JarOutputStream jos = new JarOutputStream(new FileOutputStream(jarFile), manifest);
    jos.putNextEntry(new JarEntry(agent.getName().replace('.', '/') + ".class"));
    jos.write(getBytesFromStream(agent.getClassLoader().getResourceAsStream(unqualify(agent))));
    jos.closeEntry();
    for (Class<?> clazz : resources) {
        String name = unqualify(clazz);
        jos.putNextEntry(new JarEntry(name));
        jos.write(getBytesFromStream(clazz.getClassLoader().getResourceAsStream(name)));
        jos.closeEntry();
    }

    jos.close();
    return jarFile;
}
 
Example 6
Project: jdk8u-jdk   File: ClassReader.java   View source code 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 7
Project: Jar2Java   File: JarAnalyzer.java   View source code 6 votes vote down vote up
public Map<String, String> getRenameMap(String jarFilePath) {
    Map<String, String> map = new HashMap<>();
    try {
        File jarFile = new File(jarFilePath);
        JarFile file = new JarFile(jarFile);
        Enumeration<JarEntry> enumeration = file.entries();
        while (enumeration.hasMoreElements()) {
            JarEntry jarEntry = enumeration.nextElement();
            String entryName = jarEntry.getName();
            String className;
            if (entryName.endsWith(".class")) {
                className = Utils.path2Classname(entryName);
                String simpleName = className.substring(className.lastIndexOf('.') + 1);
                if (Utils.isProguardedName(simpleName)) {
                    map.put(className, getNewClassName(className, simpleName));
                }
            }
        }
        file.close();
    } catch (IOException e) {
        e.printStackTrace();
    }

    return map;
}
 
Example 8
Project: incubator-netbeans   File: VerifyFile.java   View source code 6 votes vote down vote up
/**
 * Converts a jar entry to a class name.
 * 
 * @param entry <code>JarEntry</code> to process.
 * @return The classname of the jar entry or <code>null</code> if it cannot be 
 *      devised.
 */
private static String getClassName(JarEntry entry) {
    final String name = entry.getName();
    
    if (name.endsWith(".class")) { // NOI18N
        final String className = 
                name.substring(0, name.length() - 6).replace('/', '.'); // NOMAGI
        if (className.matches(
                "([a-zA-Z][a-zA-Z0-9_]+\\.)+[a-zA-Z][a-zA-Z0-9_]+")) { // NOI18N
            return className;
        } else {
            return null;
        }
    }
    
    return null;
}
 
Example 9
Project: enigma-vk   File: JarClassIterator.java   View source code 6 votes vote down vote up
public JarClassIterator(JarFile jar) {
	m_jar = jar;
	
	// get the jar entries that correspond to classes
	List<JarEntry> classEntries = Lists.newArrayList();
	Enumeration<JarEntry> entries = m_jar.entries();
	while (entries.hasMoreElements()) {
		JarEntry entry = entries.nextElement();
		
		// is this a class file?
		if (entry.getName().endsWith(".class")) {
			classEntries.add(entry);
		}
	}
	m_iter = classEntries.iterator();
}
 
Example 10
Project: util4j   File: AbstractLibScriptFactory.java   View source code 6 votes vote down vote up
/**
 * 加载jar的所有类
 * 
 * @param jarFiles
 * @param loader
 * @return
 * @throws ClassNotFoundException
 * @throws IOException
 */
protected Set<Class<?>> loadAllClass(File jarFile, ScriptClassLoader loader) throws Exception {
	Set<Class<?>> clzzs = new HashSet<Class<?>>();
	JarFile jf = new JarFile(jarFile);
	try {
		loader.addURL(jarFile.toURI().toURL());// 添加文件到加载器
		Enumeration<JarEntry> it = jf.entries();
		while (it.hasMoreElements()) {
			JarEntry jarEntry = it.nextElement();
			if (jarEntry.getName().endsWith(".class")) {
				String className = jarEntry.getName().replace("/", ".").replaceAll(".class", "");
				clzzs.add(loader.findClass(className));
			}
		}
	} finally {
		jf.close();
	}
	return clzzs;
}
 
Example 11
Project: Vanilla-Injection   File: JarClassLoader.java   View source code 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 12
Project: AlphaLibary   File: AlphaLibary.java   View source code 6 votes vote down vote up
private Class<?>[] getClasses(File jarFile) {
    Set<Class<?>> classes = new HashSet<>();
    try {
        JarFile file = new JarFile(jarFile);
        for (Enumeration<JarEntry> entry = file.entries(); entry.hasMoreElements(); ) {
            JarEntry jarEntry = entry.nextElement();
            String jarName = jarEntry.getName().replace('/', '.');

            if (jarName.endsWith(".class")) {
                if (!jarName.contains("1_8") && !jarName.contains("1_9") && !jarName.contains("1_10") && !jarName.contains("1_11") && !jarName.contains("1_7"))
                    classes.add(Class.forName(jarName.substring(0, jarName.length() - 6)));
            }
        }
        file.close();
    } catch (IOException | ClassNotFoundException ex) {
        Bukkit.getLogger().severe("Error ocurred at getting classes, log: " + ex);
    }

    return classes.toArray(new Class[classes.size()]);
}
 
Example 13
Project: openjdk-jdk10   File: JarTask.java   View source code 6 votes vote down vote up
private void writeFileObjects(JarOutputStream jos) throws IOException {
    for (FileObject fo : fileObjects) {
        String p = guessPath(fo);
        JarEntry e = new JarEntry(p);
        jos.putNextEntry(e);
        try {
            byte[] buf = new byte[1024];
            try (BufferedInputStream in = new BufferedInputStream(fo.openInputStream())) {
                int n;
                while ((n = in.read(buf)) > 0)
                    jos.write(buf, 0, n);
            } catch (IOException ex) {
                error("Exception while adding " + fo.getName() + " to jar file", ex);
            }
    } finally {
            jos.closeEntry();
    }
    }
}
 
Example 14
Project: incubator-netbeans   File: DeclarativeHintsTestBase.java   View source code 6 votes vote down vote up
private static Collection<String> listTestsFromJar(File archive) {
    Collection<String> result = new LinkedList<String>();

    try {
        JarFile jf = new JarFile(archive);
        Enumeration<JarEntry> entries = jf.entries();

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

            if (entry.getName().endsWith(".test")) {
                result.add(entry.getName());
            }
        }
    } catch (IOException ex) {
        throw new IllegalStateException(ex);
    }
    
    return result;
}
 
Example 15
Project: incubator-netbeans   File: JavaProjectGeneratorTest.java   View source code 6 votes vote down vote up
public void createRealJarFile(File f) throws Exception {
        OutputStream os = new FileOutputStream(f);
        try {
            JarOutputStream jos = new JarOutputStream(os);
//            jos.setMethod(ZipEntry.STORED);
            JarEntry entry = new JarEntry("foo.txt");
//            entry.setSize(0L);
//            entry.setTime(System.currentTimeMillis());
//            entry.setCrc(new CRC32().getValue());
            jos.putNextEntry(entry);
            jos.flush();
            jos.close();
        } finally {
            os.close();
        }
    }
 
Example 16
Project: incubator-netbeans   File: RemoveWritablesModifiedTest.java   View source code 6 votes vote down vote up
private File createModuleJar(String manifest) throws IOException {
    // XXX use TestFileUtils.writeZipFile
    File jarFile = new File( getWorkDir(), "mymodule.jar" );
    
    JarOutputStream os = new JarOutputStream(new FileOutputStream(jarFile), new Manifest(
        new ByteArrayInputStream(manifest.getBytes())
    ));
    JarEntry entry = new JarEntry("foo/mf-layer.xml");
    os.putNextEntry( entry );
    
    File l3 = new File(new File(new File(getDataDir(), "layers"), "data"), "layer3.xml");
    InputStream is = new FileInputStream(l3);
    FileUtil.copy( is, os );
    is.close();
    os.close();
    
    return jarFile;
}
 
Example 17
Project: incubator-netbeans   File: DelayFSEventsTest.java   View source code 6 votes vote down vote up
private File createModuleJar(String manifest) throws IOException {
    File jarFile = new File( getWorkDir(), "mymodule.jar" );
    
    JarOutputStream os = new JarOutputStream(new FileOutputStream(jarFile), new Manifest(
        new ByteArrayInputStream(manifest.getBytes())
    ));
    JarEntry entry = new JarEntry("foo/mf-layer.xml");
    os.putNextEntry( entry );
    
    File l3 = new File(new File(new File(getDataDir(), "layers"), "data"), "layer3.xml");
    InputStream is = new FileInputStream(l3);
    FileUtil.copy( is, os );
    is.close();
    os.putNextEntry(new JarEntry("org/netbeans/core/startup/layers/DelayFSInstaller.class"));
    is = DelayFSEventsTest.class.getResourceAsStream("DelayFSInstaller.class");
    FileUtil.copy (is, os);
    
    os.close();
    
    return jarFile;
}
 
Example 18
Project: apache-maven-shade-plugin   File: DefaultShader.java   View source code 6 votes vote down vote up
private void addDirectory( Set<String> resources, JarOutputStream jos, String name, boolean consistentDates )
    throws IOException
{
    if ( name.lastIndexOf( '/' ) > 0 )
    {
        String parent = name.substring( 0, name.lastIndexOf( '/' ) );
        if ( !resources.contains( parent ) )
        {
            addDirectory( resources, jos, parent, consistentDates );
        }
    }

    // directory entries must end in "/"
    JarEntry entry = new ConsistentJarEntry( name + "/", consistentDates );
    jos.putNextEntry( entry );

    resources.add( name );
}
 
Example 19
Project: openjdk-jdk10   File: PackTestZip64.java   View source code 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 20
Project: incubator-netbeans   File: RecognizeInstanceObjectsOnModuleEnablementTest.java   View source code 6 votes vote down vote up
@Override
protected void setUp() throws Exception {
    clearWorkDir();
    f = new File(getWorkDir(), "m.jar");
    
    Manifest man = new Manifest();
    Attributes attr = man.getMainAttributes();
    attr.putValue("OpenIDE-Module", "m.test");
    attr.putValue("OpenIDE-Module-Public-Packages", "-");
    attr.putValue("Manifest-Version", "1.0");
    JarOutputStream os = new JarOutputStream(new FileOutputStream(f), man);
    os.putNextEntry(new JarEntry("META-INF/namedservices/ui/javax.swing.JComponent"));
    os.write("javax.swing.JButton\n".getBytes("UTF-8"));
    os.closeEntry();
    os.close();
    
    FileObject fo = FileUtil.createData(FileUtil.getConfigRoot(), "ui/ch/my/javax-swing-JPanel.instance");
}
 
Example 21
Project: openjdk-jdk10   File: Scan.java   View source code 6 votes vote down vote up
/**
 * Scans a jar file for uses of deprecated APIs.
 *
 * @param jarname the jar file to process
 * @return true on success, false on failure
 */
public boolean scanJar(String jarname) {
    try (JarFile jf = new JarFile(jarname)) {
        out.println(Messages.get("scan.head.jar", jarname));
        finder.addJar(jarname);
        Enumeration<JarEntry> entries = jf.entries();
        while (entries.hasMoreElements()) {
            JarEntry entry = entries.nextElement();
            String name = entry.getName();
            if (name.endsWith(".class")
                    && !name.endsWith("package-info.class")
                    && !name.endsWith("module-info.class")) {
                processClass(ClassFile.read(jf.getInputStream(entry)));
            }
        }
        return true;
    } catch (NoSuchFileException nsfe) {
        errorNoFile(jarname);
    } catch (IOException | ConstantPoolException ex) {
        errorException(ex);
    }
    return false;
}
 
Example 22
Project: openjdk-jdk10   File: VersionedStream.java   View source code 6 votes vote down vote up
private static String getBaseSuffix(JarEntry je, int version) {
    String name = je.getName();
    if (name.startsWith(META_INF_VERSIONS)) {
        int len = META_INF_VERSIONS.length();
        int index = name.indexOf('/', len);
        if (index == -1 || index == (name.length() - 1)) {
            // filter out META-INF/versions/* and META-INF/versions/*/
            return null;
        }
        try {
            if (Integer.parseInt(name, len, index, 10) > version) {
                // not an integer
                return null;
            }
        } catch (NumberFormatException x) {
            // silently remove malformed entries
            return null;
        }
        // We know name looks like META-INF/versions/*/*
        return name.substring(index + 1);
    }
    return name;
}
 
Example 23
Project: atlas   File: LocalSignedJarBuilder.java   View source code 6 votes vote down vote up
/**
 * Writes a new {@link File} into the archive.
 *
 * @param inputFile the {@link File} to write.
 * @param jarPath   the filepath inside the archive.
 * @throws IOException
 */
public void writeFile(File inputFile, String jarPath) throws IOException {
    // Get an input stream on the file.
    FileInputStream fis = new FileInputStream(inputFile);
    try {

        // create the zip entry
        JarEntry entry = new JarEntry(jarPath);
        entry.setTime(inputFile.lastModified());

        writeEntry(fis, entry);
    } finally {
        // close the file stream used to read the file
        fis.close();
    }
}
 
Example 24
Project: jdk8u-jdk   File: PackTestZip64.java   View source code 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 25
Project: anvil   File: Publicizer.java   View source code 6 votes vote down vote up
private static void publicize(Path inPath, Path outPath) throws IOException {
	try (JarInputStream in = new JarInputStream(Files.newInputStream(inPath))) {
		try (JarOutputStream out = new JarOutputStream(Files.newOutputStream(outPath))) {
			JarEntry entry;
			while ((entry = in.getNextJarEntry()) != null) {
				if (entry.isDirectory()) {
					continue;
				}

				String name = entry.getName();
				out.putNextEntry(new JarEntry(name));

				if (name.endsWith(".class")) {
					ClassWriter writer = new ClassWriter(0);

					ClassReader reader = new ClassReader(in);
					reader.accept(new CheckClassAdapter(new ClassDefinalizer(new ClassPublicizer(writer)), true), 0);

					out.write(writer.toByteArray());
				} else {
					ByteStreams.copy(in, out);
				}
			}
		}
	}
}
 
Example 26
Project: incubator-netbeans   File: SetupHid.java   View source code 6 votes vote down vote up
private static void writeJarEntry(JarOutputStream jos, String path, File f) throws IOException, FileNotFoundException {
    JarEntry je = new JarEntry(path);
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    InputStream is = new FileInputStream(f);
    try {
        copyStreams(is, baos);
    } finally {
        is.close();
    }
    byte[] data = baos.toByteArray();
    je.setSize(data.length);
    CRC32 crc = new CRC32();
    crc.update(data);
    je.setCrc(crc.getValue());
    jos.putNextEntry(je);
    jos.write(data);
}
 
Example 27
Project: CoreX   File: JavaPluginLoader.java   View source code 6 votes vote down vote up
@Override
public PluginDescription getPluginDescription(File file) {
    try (JarFile jar = new JarFile(file)) {
        JarEntry entry = jar.getJarEntry("nukkit.yml");
        if (entry == null) {
            entry = jar.getJarEntry("plugin.yml");
            if (entry == null) {
                return null;
            }
        }
        try (InputStream stream = jar.getInputStream(entry)) {
            return new PluginDescription(Utils.readFile(stream));
        }
    } catch (IOException e) {
        return null;
    }
}
 
Example 28
Project: atlas   File: ClazzReplacer.java   View source code 6 votes vote down vote up
@Override
protected void handleClazz(JarFile jarFile, JarOutputStream jos, JarEntry ze, String pathName) {

    //            logger.log(pathName);
    if (reMapping.containsKey(pathName.substring(0, pathName.length() - 6))) {
        logger.info("[ClazzReplacer] remove class  " + pathName + " form " + jarFile);
        return;
    }

    try {
        InputStream in = jarFile.getInputStream(ze);
        ClassReader cr = new ClassReader(in);
        ClassWriter cw = new ClassWriter(0);
        RemappingClassAdapter remappingClassAdapter = new RemappingClassAdapter(cw, new SimpleRemapper(reMapping));
        cr.accept(remappingClassAdapter, ClassReader.EXPAND_FRAMES);

        InputStream inputStream = new ByteArrayInputStream(cw.toByteArray());
        copyStreamToJar(inputStream, jos, pathName, ze.getTime());

    } catch (Throwable e) {

        System.err.println("[ClazzReplacer] rewrite error > " + pathName);
        justCopy(jarFile, jos, ze, pathName);
    }

}
 
Example 29
Project: OperatieBRP   File: TimestampMojo.java   View source code 6 votes vote down vote up
private Set<String> pakArchiefBestandUit(final Path tmpFolder) {
    getLog().debug("Unpacking artifact");
    Set<String> keys = new TreeSet<>();
    try (final JarInputStream archiefStream = new JarInputStream(new FileInputStream(artifact + ".bak"))) {

        final List<String> bestanden = new ArrayList<>();
        JarEntry archiefItem = archiefStream.getNextJarEntry();
        while (archiefItem != null) {
            final File archiefBestand = new File(tmpFolder.toFile(), archiefItem.getName());
            if (archiefItem.isDirectory()) {
                archiefBestand.mkdirs();
            } else {
                pakBestandUit(archiefStream, archiefBestand);
            }
            bestanden.add(archiefItem.getName());
            archiefStream.closeEntry();
            archiefItem = archiefStream.getNextJarEntry();
        }

        pakManifestUit(tmpFolder, archiefStream, bestanden);
        keys.addAll(bestanden);
    } catch (IOException | WrappedException e) {
        getLog().debug("Artifact cannot be fixed", e);
    }
    return keys;
}
 
Example 30
Project: beaker-notebook-archive   File: SimpleClassLoader.java   View source code 6 votes vote down vote up
protected Class<?> findClassInJarFile(String qualifiedClassName) throws ClassNotFoundException {
    URI classUri = URIUtil.buildUri(StandardLocation.CLASS_OUTPUT, qualifiedClassName);
    String internalClassName = classUri.getPath().substring(1);
    JarFile jarFile = null;
    try {
        for (int i = 0; i < jarFiles.size(); i++) {
            jarFile = jarFiles.get(i);
            JarEntry jarEntry = jarFile.getJarEntry(internalClassName);
            if (jarEntry != null) {
                InputStream inputStream = jarFile.getInputStream(jarEntry);
                try {
                    byte[] byteCode = new byte[(int) jarEntry.getSize()];
                    ByteStreams.read(inputStream, byteCode, 0, byteCode.length);
                    return defineClass(qualifiedClassName, byteCode, 0, byteCode.length);
                } finally {
                    Closeables.closeQuietly(inputStream);
                }
            }
        }
    } catch (IOException e) {
        throw new IllegalStateException(String.format("Failed to lookup class %s in jar file %s", qualifiedClassName, jarFile), e);
    }
    return null;
}
 
Example 31
Project: android-perftracking   File: ClassJarMaker.java   View source code 5 votes vote down vote up
public void add(String name, byte[] data) {
  try {
    JarEntry entry = new JarEntry(name.replace('.', '/') + ".class");
    _output.putNextEntry(entry);
    _output.write(data);
    _output.closeEntry();
  } catch (Exception e) {
    throw new RuntimeException("Failed to add jar entry", e);
  }
}
 
Example 32
Project: JavaShell   File: JarUtils.java   View source code 5 votes vote down vote up
public static boolean extractFromJar(final String fileName, final String dest) throws IOException {
	if (getRunningJar() == null) {
		return false;
	}
	final File file = new File(dest);
	if (file.isDirectory()) {
		file.mkdir();
		return false;
	}
	if (!file.exists()) {
		file.getParentFile().mkdirs();
	}

	final JarFile jar = getRunningJar();
	final Enumeration<JarEntry> e = jar.entries();
	while (e.hasMoreElements()) {
		final JarEntry je = e.nextElement();
		if (!je.getName().contains(fileName)) {
			continue;
		}
		final InputStream in = new BufferedInputStream(jar.getInputStream(je));
		final OutputStream out = new BufferedOutputStream(new FileOutputStream(file));
		copyInputStream(in, out);
		jar.close();
		return true;
	}
	jar.close();
	return false;
}
 
Example 33
Project: openjdk-jdk10   File: ClassFileReader.java   View source code 5 votes vote down vote up
protected Set<String> scan() {
    try (JarFile jf = openJarFile(path.toFile(), version)) {
        return VersionedStream.stream(jf).map(JarEntry::getName)
                 .filter(n -> n.endsWith(".class"))
                 .collect(Collectors.toSet());
    } catch (IOException e) {
        throw new UncheckedIOException(e);
    }
}
 
Example 34
Project: jerrydog   File: WebappClassLoader.java   View source code 5 votes vote down vote up
/**
     * Check the specified JAR file, and return <code>true</code> if it does
     * not contain any of the trigger classes.
     *
//     * @param jarFile The JAR file to be checked
     *
     * @exception IOException if an input/output error occurs
     */
    private boolean validateJarFile(File jarfile)
        throws IOException {

        if (triggers == null)
            return (true);
        JarFile jarFile = new JarFile(jarfile);
        for (int i = 0; i < triggers.length; i++) {
            Class clazz = null;
            try {
                if (parent != null) {
                    clazz = parent.loadClass(triggers[i]);
                } else {
                    clazz = Class.forName(triggers[i]);
                }
            } catch (Throwable t) {
                clazz = null;
            }
            if (clazz == null)
                continue;
            String name = triggers[i].replace('.', '/') + ".class";
            if (debug >= 2)
                log(" Checking for " + name);
            JarEntry jarEntry = jarFile.getJarEntry(name);
            if (jarEntry != null) {
                log("validateJarFile(" + jarfile +
                    ") - jar not loaded. See Servlet Spec 2.3, "
                    + "section 9.7.2. Offending class: " + name);
                jarFile.close();
                return (false);
            }
        }
        jarFile.close();
        return (true);

    }
 
Example 35
Project: incubator-netbeans   File: SetupHid.java   View source code 5 votes vote down vote up
/**
 * Create a fresh JAR file.
 * @param jar the file to create
 * @param contents keys are JAR entry paths, values are text contents (will be written in UTF-8)
 * @param manifest a manifest to store (key/value pairs for main section)
 */
public static void createJar(File jar, Map<String,String> contents, Map<String,String> manifest) throws IOException {
    // XXX use TestFileUtils.writeZipFile
    Manifest m = new Manifest();
    m.getMainAttributes().putValue("Manifest-Version", "1.0"); // workaround for JDK bug
    for (Map.Entry<String,String> line : manifest.entrySet()) {
        m.getMainAttributes().putValue(line.getKey(), line.getValue());
    }
    jar.getParentFile().mkdirs();
    OutputStream os = new FileOutputStream(jar);
    try {
        JarOutputStream jos = new JarOutputStream(os, m);
        Iterator it = contents.entrySet().iterator();
        while (it.hasNext()) {
            Map.Entry entry = (Map.Entry) it.next();
            String path = (String) entry.getKey();
            byte[] data = ((String) entry.getValue()).getBytes("UTF-8");
            JarEntry je = new JarEntry(path);
            je.setSize(data.length);
            CRC32 crc = new CRC32();
            crc.update(data);
            je.setCrc(crc.getValue());
            jos.putNextEntry(je);
            jos.write(data);
        }
        jos.close();
    } finally {
        os.close();
    }
}
 
Example 36
Project: mobile-store   File: IndexV1UpdaterTest.java   View source code 5 votes vote down vote up
private void testBadTestyJar(String jar) throws IOException, RepoUpdater.UpdateException {
    Repo repo = MultiRepoUpdaterTest.createRepo("Testy", jar, context, TESTY_CERT);
    IndexV1Updater updater = new IndexV1Updater(context, repo);
    JarFile jarFile = new JarFile(TestUtils.copyResourceToTempFile(jar), true);
    JarEntry indexEntry = (JarEntry) jarFile.getEntry(IndexV1Updater.DATA_FILE_NAME);
    InputStream indexInputStream = jarFile.getInputStream(indexEntry);
    updater.processIndexV1(indexInputStream, indexEntry, "fakeEtag");
    fail(); // it should never reach here, it should throw a SigningException
}
 
Example 37
Project: Vanilla-Injection   File: JarClassLoader.java   View source code 5 votes vote down vote up
private List<JarEntryInfo> findJarEntries(String sName) {
    List<JarEntryInfo> lst = new ArrayList<JarEntryInfo>();
    for (JarFileInfo jarFileInfo : lstJarFile) {
        JarFile jarFile = jarFileInfo.jarFile;
        JarEntry jarEntry = jarFile.getJarEntry(sName);
        if (jarEntry != null) {
            lst.add(new JarEntryInfo(jarFileInfo, jarEntry));
        }
    }
    return lst;
}
 
Example 38
Project: fitnotifications   File: URLHandler.java   View source code 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 39
Project: incubator-netbeans   File: Utils.java   View source code 5 votes vote down vote up
/**
 * Checks whether the given file is a signed jar archive.
 *
 * @param file File to check for being a signed jar archive.
 * @return <code>true</code> if the file is a signed jar archive,
 *      <code>false</code> otherwise.
 * @throws java.io.IOException if an I/O error occurs.
 */
public static boolean isSigned(final File file) throws IOException {
    JarFile jar = new JarFile(file);
    
    try {
        Enumeration<JarEntry> entries = jar.entries();
        boolean signatureInfoPresent = false;
        boolean signatureFilePresent = false;
        while (entries.hasMoreElements()) {
            String entryName = entries.nextElement().getName();
            if (entryName.startsWith("META-INF/")) {
                if (entryName.endsWith(".RSA") || entryName.endsWith(".DSA")) {
                    signatureFilePresent = true;
                    if(signatureInfoPresent) {
                        break;
                    }
                } else if (entryName.endsWith(".SF")) {
                    signatureInfoPresent = true;
                    if(signatureFilePresent) {
                        break;
                    }
                }
            }
        }
        return signatureFilePresent && signatureInfoPresent;
    } finally {
        jar.close();
    }
}
 
Example 40
Project: whackpad   File: JarClassLoader.java   View source code 5 votes vote down vote up
private static JarEntry findJarEntry(JarFile jarFile, String entryName) {

        Enumeration entries = jarFile.entries();

        while (entries.hasMoreElements()) {
            JarEntry entry = (JarEntry) entries.nextElement();
            if (entry.getName().equals(entryName)) {
                return entry;
            }
        }

        return null;
    }