Search in sources :

Example 31 with JarFile

use of java.util.jar.JarFile in project ACS by ACS-Community.

the class JarSourceExtractorRunner method main.

/**
	 * First argument must be the jar file name to which all Java sources 
	 * @param args
	 */
public static void main(String[] args) {
    if (args.length < 2) {
        System.err.println("usage: " + JarSourceExtractorRunner.class.getName() + " outputJarFile jarDirectory1 jarDirectory2 ...");
        return;
    }
    try {
        Logger logger = Logger.getLogger("ACS.JarSourceExtractorRunner");
        // set up output jar file
        File targetJarFile = new File(args[0]);
        if (targetJarFile.exists()) {
            targetJarFile.delete();
        } else {
            File parent = targetJarFile.getParentFile();
            if (parent != null) {
                parent.mkdirs();
            }
        }
        targetJarFile.createNewFile();
        if (!targetJarFile.isFile() || !targetJarFile.canWrite()) {
            throw new IOException(targetJarFile + " is not a writable file.");
        }
        // get all input jar files
        File[] dirs = getDirectories(args);
        AcsJarFileFinder jarFinder = new AcsJarFileFinder(dirs, logger);
        File[] jarFiles = jarFinder.getAllFiles();
        // extract java sources
        if (jarFiles.length > 0) {
            JarSourceExtractor extractor = new JarSourceExtractor();
            FileOutputStream out = new FileOutputStream(targetJarFile);
            JarOutputStream jarOut = new JarOutputStream(out);
            try {
                for (int i = 0; i < jarFiles.length; i++) {
                    JarFile jarFile = new JarFile(jarFiles[i]);
                    if (needsProcessing(jarFile)) {
                        extractor.extractJavaSourcesToJar(jarFile, jarOut);
                    }
                }
            } finally {
                jarOut.finish();
                jarOut.close();
            }
        } else {
            System.out.println("no jar files found.");
        }
    } catch (Exception e) {
        e.printStackTrace();
        System.exit(1);
    }
}
Also used : FileOutputStream(java.io.FileOutputStream) JarOutputStream(java.util.jar.JarOutputStream) IOException(java.io.IOException) Logger(java.util.logging.Logger) JarFile(java.util.jar.JarFile) JarFile(java.util.jar.JarFile) File(java.io.File) IOException(java.io.IOException)

Example 32 with JarFile

use of java.util.jar.JarFile in project ACS by ACS-Community.

the class JarFileHelper method getClasses.

/**
	 * Flush the java classes contained in this jar file
	 * into the passed vector.
	 * 
	 * @return The java classes in the jar file
	 */
public void getClasses(Collection<String> javaClasses) throws IOException {
    if (javaClasses == null) {
        throw new IllegalArgumentException("The vector can't be null");
    }
    JarFile jar = new JarFile(file);
    Enumeration<JarEntry> entries = jar.entries();
    for (Enumeration<JarEntry> em1 = entries; em1.hasMoreElements(); ) {
        String str = em1.nextElement().toString().trim();
        addJavaClass(str, javaClasses);
    }
    jar.close();
}
Also used : JarFile(java.util.jar.JarFile) JarEntry(java.util.jar.JarEntry)

Example 33 with JarFile

use of java.util.jar.JarFile in project intellij-community by JetBrains.

the class StructContext method addArchive.

private void addArchive(String path, File file, int type, boolean isOwn) throws IOException {
    //noinspection IOResourceOpenedButNotSafelyClosed
    try (ZipFile archive = type == ContextUnit.TYPE_JAR ? new JarFile(file) : new ZipFile(file)) {
        Enumeration<? extends ZipEntry> entries = archive.entries();
        while (entries.hasMoreElements()) {
            ZipEntry entry = entries.nextElement();
            ContextUnit unit = units.get(path + "/" + file.getName());
            if (unit == null) {
                unit = new ContextUnit(type, path, file.getName(), isOwn, saver, decompiledData);
                if (type == ContextUnit.TYPE_JAR) {
                    unit.setManifest(((JarFile) archive).getManifest());
                }
                units.put(path + "/" + file.getName(), unit);
            }
            String name = entry.getName();
            if (!entry.isDirectory()) {
                if (name.endsWith(".class")) {
                    byte[] bytes = InterpreterUtil.getBytes(archive, entry);
                    StructClass cl = new StructClass(bytes, isOwn, loader);
                    classes.put(cl.qualifiedName, cl);
                    unit.addClass(cl, name);
                    loader.addClassLink(cl.qualifiedName, new LazyLoader.Link(LazyLoader.Link.ENTRY, file.getAbsolutePath(), name));
                } else {
                    unit.addOtherEntry(file.getAbsolutePath(), name);
                }
            } else {
                unit.addDirEntry(name);
            }
        }
    }
}
Also used : LazyLoader(org.jetbrains.java.decompiler.struct.lazy.LazyLoader) ZipFile(java.util.zip.ZipFile) ZipEntry(java.util.zip.ZipEntry) JarFile(java.util.jar.JarFile)

Example 34 with JarFile

use of java.util.jar.JarFile in project kotlin by JetBrains.

the class CompileKotlinAgainstCustomBinariesTest method transformJar.

@NotNull
private static File transformJar(@NotNull File jarPath, @NotNull Function2<String, byte[], byte[]> transformEntry, @NotNull String... entriesToDelete) {
    try {
        File outputFile = new File(jarPath.getParentFile(), FileUtil.getNameWithoutExtension(jarPath) + "-after.jar");
        Set<String> toDelete = SetsKt.setOf(entriesToDelete);
        @SuppressWarnings("IOResourceOpenedButNotSafelyClosed") JarFile jar = new JarFile(jarPath);
        ZipOutputStream output = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(outputFile)));
        try {
            for (Enumeration<JarEntry> enumeration = jar.entries(); enumeration.hasMoreElements(); ) {
                JarEntry jarEntry = enumeration.nextElement();
                String name = jarEntry.getName();
                if (toDelete.contains(name)) {
                    continue;
                }
                byte[] bytes = FileUtil.loadBytes(jar.getInputStream(jarEntry));
                byte[] newBytes = name.endsWith(".class") ? transformEntry.invoke(name, bytes) : bytes;
                JarEntry newEntry = new JarEntry(name);
                newEntry.setSize(newBytes.length);
                output.putNextEntry(newEntry);
                output.write(newBytes);
                output.closeEntry();
            }
        } finally {
            output.close();
            jar.close();
        }
        return outputFile;
    } catch (IOException e) {
        throw ExceptionUtilsKt.rethrow(e);
    }
}
Also used : ZipOutputStream(java.util.zip.ZipOutputStream) FileOutputStream(java.io.FileOutputStream) IOException(java.io.IOException) JarFile(java.util.jar.JarFile) JarEntry(java.util.jar.JarEntry) JarFile(java.util.jar.JarFile) RecursiveDescriptorComparator.validateAndCompareDescriptorWithFile(org.jetbrains.kotlin.test.util.RecursiveDescriptorComparator.validateAndCompareDescriptorWithFile) File(java.io.File) BufferedOutputStream(java.io.BufferedOutputStream) NotNull(org.jetbrains.annotations.NotNull)

Example 35 with JarFile

use of java.util.jar.JarFile in project kotlin by JetBrains.

the class ClassPreloadingUtils method loadAllClassesFromJars.

/**
     * @return a map of name to resources. Each value is either a ResourceData if there's only one instance (in the vast majority of cases)
     * or a non-empty ArrayList of ResourceData if there's many
     */
private static Map<String, Object> loadAllClassesFromJars(Collection<File> jarFiles, int classNumberEstimate, ClassHandler handler) throws IOException {
    // 0.75 is HashMap.DEFAULT_LOAD_FACTOR
    Map<String, Object> resources = new HashMap<String, Object>((int) (classNumberEstimate / 0.75));
    for (File jarFile : jarFiles) {
        if (handler != null) {
            handler.beforeLoadJar(jarFile);
        }
        FileInputStream fileInputStream = new FileInputStream(jarFile);
        try {
            byte[] buffer = new byte[10 * 1024];
            ZipInputStream stream = new ZipInputStream(new BufferedInputStream(fileInputStream, 1 << 19));
            while (true) {
                ZipEntry entry = stream.getNextEntry();
                if (entry == null)
                    break;
                if (entry.isDirectory())
                    continue;
                int size = (int) entry.getSize();
                int effectiveSize = size < 0 ? 32 : size;
                ByteArrayOutputStream bytes = new ByteArrayOutputStream(effectiveSize);
                int count;
                while ((count = stream.read(buffer)) > 0) {
                    bytes.write(buffer, 0, count);
                }
                String name = entry.getName();
                byte[] data = bytes.toByteArray();
                if (handler != null) {
                    data = handler.instrument(name, data);
                }
                ResourceData resourceData = new ResourceData(jarFile, name, data);
                Object previous = resources.get(name);
                if (previous == null) {
                    resources.put(name, resourceData);
                } else if (previous instanceof ResourceData) {
                    List<ResourceData> list = new ArrayList<ResourceData>();
                    list.add((ResourceData) previous);
                    list.add(resourceData);
                    resources.put(name, list);
                } else {
                    assert previous instanceof ArrayList : "Resource map should contain ResourceData or ArrayList<ResourceData>: " + name;
                    ((ArrayList<ResourceData>) previous).add(resourceData);
                }
            }
        } finally {
            try {
                fileInputStream.close();
            } catch (IOException e) {
            // Ignore
            }
        }
        if (handler != null) {
            handler.afterLoadJar(jarFile);
        }
    }
    for (Object value : resources.values()) {
        if (value instanceof ArrayList) {
            ((ArrayList) value).trimToSize();
        }
    }
    return resources;
}
Also used : ZipEntry(java.util.zip.ZipEntry) ZipInputStream(java.util.zip.ZipInputStream) JarFile(java.util.jar.JarFile)

Aggregations

JarFile (java.util.jar.JarFile)1366 File (java.io.File)720 JarEntry (java.util.jar.JarEntry)616 IOException (java.io.IOException)587 URL (java.net.URL)272 InputStream (java.io.InputStream)271 ZipEntry (java.util.zip.ZipEntry)203 Manifest (java.util.jar.Manifest)186 ArrayList (java.util.ArrayList)158 Test (org.junit.Test)131 JarURLConnection (java.net.JarURLConnection)123 FileOutputStream (java.io.FileOutputStream)122 ZipFile (java.util.zip.ZipFile)121 FileInputStream (java.io.FileInputStream)111 Attributes (java.util.jar.Attributes)110 MalformedURLException (java.net.MalformedURLException)94 Enumeration (java.util.Enumeration)67 JarOutputStream (java.util.jar.JarOutputStream)65 HashSet (java.util.HashSet)58 URLClassLoader (java.net.URLClassLoader)55