Example usage for java.util.jar JarFile JarFile

List of usage examples for java.util.jar JarFile JarFile

Introduction

In this page you can find the example usage for java.util.jar JarFile JarFile.

Prototype

public JarFile(File file) throws IOException 

Source Link

Document

Creates a new JarFile to read from the specified File object.

Usage

From source file:Main.java

public static void main(String[] argv) throws Exception {
    JarFile jarfile = new JarFile("filename.jar");

    Manifest manifest = jarfile.getManifest();

    Map map = manifest.getEntries();

    for (Iterator it = map.keySet().iterator(); it.hasNext();) {
        String entryName = (String) it.next();

        Attributes attrs = (Attributes) map.get(entryName);

        for (Iterator it2 = attrs.keySet().iterator(); it2.hasNext();) {
            Attributes.Name attrName = (Attributes.Name) it2.next();

            String attrValue = attrs.getValue(attrName);
        }/*w w  w . j av a2  s .  c om*/
    }
}

From source file:Main.java

public static void main(String[] args) throws IOException {

    JarFile jf = new JarFile(args[0]);
    Enumeration e = jf.entries();
    while (e.hasMoreElements()) {
        JarEntry je = (JarEntry) e.nextElement();
        String name = je.getName();

        Attributes a = je.getAttributes();
        if (a != null) {
            Object[] nameValuePairs = a.entrySet().toArray();
            for (int j = 0; j < nameValuePairs.length; j++) {
                System.out.println(nameValuePairs[j]);
            }/*w  w  w.  j  a v  a  2 s .com*/
        }
    }
}

From source file:JarRead.java

public static void main(String args[]) throws IOException {
    if (args.length != 2) {
        System.out.println("Please provide a JAR filename and file to read");
        System.exit(-1);/*from  www  .  j av  a2  s .co  m*/
    }
    JarFile jarFile = new JarFile(args[0]);
    JarEntry entry = jarFile.getJarEntry(args[1]);
    InputStream input = jarFile.getInputStream(entry);
    process(input);
    jarFile.close();
}

From source file:MainClass.java

public static void main(String[] args) throws IOException {

    JarFile jf = new JarFile(args[0]);
    Enumeration e = jf.entries();
    while (e.hasMoreElements()) {
        JarEntry je = (JarEntry) e.nextElement();
        String name = je.getName();
        Date lastModified = new Date(je.getTime());
        long uncompressedSize = je.getSize();
        long compressedSize = je.getCompressedSize();

        int method = je.getMethod();

        if (method == ZipEntry.STORED) {
            System.out.println(name + " was stored at " + lastModified);
            System.out.println("with a size of  " + uncompressedSize + " bytes");
        } else if (method == ZipEntry.DEFLATED) {
            System.out.println(name + " was deflated at " + lastModified);
            System.out.println("from  " + uncompressedSize + " bytes to " + compressedSize
                    + " bytes, a savings of " + (100.0 - 100.0 * compressedSize / uncompressedSize) + "%");
        } else {/*from   ww w  . j  a  va2s  .c o  m*/
            System.out.println(name + " was compressed using an unrecognized method at " + lastModified);
            System.out.println("from  " + uncompressedSize + " bytes to " + compressedSize
                    + " bytes, a savings of " + (100.0 - 100.0 * compressedSize / uncompressedSize) + "%");
        }
    }
}

From source file:Main.java

public static void main(String[] args) throws IOException {
    JarFile jf = new JarFile("a.jar");
    Enumeration e = jf.entries();
    while (e.hasMoreElements()) {
        JarEntry je = (JarEntry) e.nextElement();
        System.out.println(je.getName());
        long uncompressedSize = je.getSize();
        long compressedSize = je.getCompressedSize();
        long crc = je.getCrc();
        int method = je.getMethod();
        String comment = je.getComment();
        System.out.println(new Date(je.getTime()));
        System.out.println("from  " + uncompressedSize + " bytes to " + compressedSize);
        if (method == ZipEntry.STORED) {
            System.out.println("ZipEntry.STORED");
        } else if (method == ZipEntry.DEFLATED) {
            System.out.println(ZipEntry.DEFLATED);
        }/*from  ww w  . j a v a 2s  .co  m*/
        System.out.println("Its CRC is " + crc);
        System.out.println(comment);
        System.out.println(je.isDirectory());

        Attributes a = je.getAttributes();
        if (a != null) {
            Object[] nameValuePairs = a.entrySet().toArray();
            for (int j = 0; j < nameValuePairs.length; j++) {
                System.out.println(nameValuePairs[j]);
            }
        }
        System.out.println();
    }
}

From source file:kilim.tools.DumpClass.java

public static void main(String[] args) throws IOException {
    String name = args.length == 2 ? args[1] : args[0];

    if (name.endsWith(".jar")) {
        try {/*from w w w .  j  ava  2s. c o  m*/
            Enumeration<JarEntry> e = new JarFile(name).entries();
            while (e.hasMoreElements()) {
                ZipEntry en = (ZipEntry) e.nextElement();
                String n = en.getName();
                if (!n.endsWith(".class"))
                    continue;
                n = n.substring(0, n.length() - 6).replace('/', '.');
                new DumpClass(n);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    } else {
        new DumpClass(name);
    }
}

From source file:net.minecraftforge.fml.common.patcher.GenDiffSet.java

public static void main(String[] args) throws IOException {
    String sourceJar = args[0]; //Clean Vanilla jar minecraft.jar or minecraft_server.jar
    String targetDir = args[1]; //Directory containing obfed output classes, typically mcp/reobf/minecraft
    String deobfData = args[2]; //Path to FML's deobfusication_data.lzma
    String outputDir = args[3]; //Path to place generated .binpatch
    String killTarget = args[4]; //"true" if we should destroy the target file if it generated a successful .binpatch

    LogManager.getLogger("GENDIFF").log(Level.INFO,
            String.format("Creating patches at %s for %s from %s", outputDir, sourceJar, targetDir));
    Delta delta = new Delta();
    FMLDeobfuscatingRemapper remapper = FMLDeobfuscatingRemapper.INSTANCE;
    remapper.setupLoadOnly(deobfData, false);
    JarFile sourceZip = new JarFile(sourceJar);
    boolean kill = killTarget.equalsIgnoreCase("true");

    File f = new File(outputDir);
    f.mkdirs();/*from   www . j  ava  2s  .co m*/

    for (String name : remapper.getObfedClasses()) {
        //            Logger.getLogger("GENDIFF").info(String.format("Evaluating path for data :%s",name));
        String fileName = name;
        String jarName = name;
        if (RESERVED_NAMES.contains(name.toUpperCase(Locale.ENGLISH))) {
            fileName = "_" + name;
        }
        File targetFile = new File(targetDir, fileName.replace('/', File.separatorChar) + ".class");
        jarName = jarName + ".class";
        if (targetFile.exists()) {
            String sourceClassName = name.replace('/', '.');
            String targetClassName = remapper.map(name).replace('/', '.');
            JarEntry entry = sourceZip.getJarEntry(jarName);
            byte[] vanillaBytes = toByteArray(sourceZip, entry);
            byte[] patchedBytes = Files.toByteArray(targetFile);

            byte[] diff = delta.compute(vanillaBytes, patchedBytes);

            ByteArrayDataOutput diffOut = ByteStreams.newDataOutput(diff.length + 50);
            // Original name
            diffOut.writeUTF(name);
            // Source name
            diffOut.writeUTF(sourceClassName);
            // Target name
            diffOut.writeUTF(targetClassName);
            // exists at original
            diffOut.writeBoolean(entry != null);
            if (entry != null) {
                diffOut.writeInt(Hashing.adler32().hashBytes(vanillaBytes).asInt());
            }
            // length of patch
            diffOut.writeInt(diff.length);
            // patch
            diffOut.write(diff);

            File target = new File(outputDir, targetClassName + ".binpatch");
            target.getParentFile().mkdirs();
            Files.write(diffOut.toByteArray(), target);
            Logger.getLogger("GENDIFF").info(String.format("Wrote patch for %s (%s) at %s", name,
                    targetClassName, target.getAbsolutePath()));
            if (kill) {
                targetFile.delete();
                Logger.getLogger("GENDIFF").info(String.format("  Deleted target: %s", targetFile.toString()));
            }
        }
    }
    sourceZip.close();
}

From source file:de.unibi.techfak.bibiserv.util.codegen.Main.java

public static void main(String[] args) {
    // check &   validate cmdline options
    OptionGroup opt_g = getCMDLineOptionsGroups();
    Options opt = getCMDLineOptions();/*from ww w .j  a v  a2  s . c  om*/
    opt.addOptionGroup(opt_g);

    CommandLineParser cli = new DefaultParser();
    try {
        CommandLine cl = cli.parse(opt, args);

        if (cl.hasOption("v")) {
            VerboseOutputFilter.SHOW_VERBOSE = true;
        }

        switch (opt_g.getSelected()) {
        case "V":
            try {
                URL jarUrl = Main.class.getProtectionDomain().getCodeSource().getLocation();
                String jarPath = URLDecoder.decode(jarUrl.getFile(), "UTF-8");
                JarFile jarFile = new JarFile(jarPath);
                Manifest m = jarFile.getManifest();
                StringBuilder versionInfo = new StringBuilder();
                for (Object key : m.getMainAttributes().keySet()) {
                    versionInfo.append(key).append(":").append(m.getMainAttributes().getValue(key.toString()))
                            .append("\n");
                }
                System.out.println(versionInfo.toString());
            } catch (Exception e) {
                log.error("Version info could not be read.");
            }
            break;
        case "h":
            HelpFormatter help = new HelpFormatter();
            String header = ""; //TODO: missing infotext 
            StringBuilder footer = new StringBuilder("Supported configuration properties :");
            help.printHelp("CodeGen -h | -V | -g  [...]", header, opt, footer.toString());
            break;
        case "g":
            // target dir
            if (cl.hasOption("t")) {
                File target = new File(cl.getOptionValue("t"));
                if (target.isDirectory() && target.canExecute() && target.canWrite()) {
                    config.setProperty("target.dir", cl.getOptionValue("t"));
                } else {
                    log.error("Target dir '{}' is inaccessible!", cl.getOptionValue("t"));
                    break;
                }
            } else {
                config.setProperty("target.dir", System.getProperty("java.io.tmpdir"));
            }

            // project dir
            if (cl.hasOption("p")) {
                File project = new File(cl.getOptionValue("p"));
                if (!project.exists()) {
                    if (!project.mkdirs()) {
                        log.error("Project dir '{}' can't be created!", cl.getOptionValue("p"));
                        break;
                    }
                }

                if (project.isDirectory() && project.canExecute() && project.canWrite()) {
                    config.setProperty("project.dir", cl.getOptionValue("p"));
                } else {
                    log.error("Project dir '{}' is inaccessible!", cl.getOptionValue("p"));
                    break;
                }
            }

            generateAppfromXML(cl.getOptionValue("g"));
            break;
        }
    } catch (ParseException e) {
        log.error("ParseException occurred while parsing cmdline arguments!\n{}", e.getLocalizedMessage());
    }

}

From source file:com.mirth.connect.server.launcher.MirthLauncher.java

public static void main(String[] args) {
    try {/*w  w  w . jav  a 2 s.  c  o m*/
        try {
            uninstallPendingExtensions();
            installPendingExtensions();
        } catch (Exception e) {
            logger.error("Error uninstalling or installing pending extensions.", e);
        }

        Properties mirthProperties = new Properties();
        String includeCustomLib = null;

        try {
            mirthProperties.load(new FileInputStream(new File(MIRTH_PROPERTIES_FILE)));
            includeCustomLib = mirthProperties.getProperty(PROPERTY_INCLUDE_CUSTOM_LIB);
            createAppdataDir(mirthProperties);
        } catch (Exception e) {
            logger.error("Error creating the appdata directory.", e);
        }

        ManifestFile mirthServerJar = new ManifestFile("server-lib/mirth-server.jar");
        ManifestFile mirthClientCoreJar = new ManifestFile("server-lib/mirth-client-core.jar");
        ManifestDirectory serverLibDir = new ManifestDirectory("server-lib");
        serverLibDir.setExcludes(new String[] { "mirth-client-core.jar" });

        List<ManifestEntry> manifestList = new ArrayList<ManifestEntry>();
        manifestList.add(mirthServerJar);
        manifestList.add(mirthClientCoreJar);
        manifestList.add(serverLibDir);

        // We want to include custom-lib if the property isn't found, or if it equals "true"
        if (includeCustomLib == null || Boolean.valueOf(includeCustomLib)) {
            manifestList.add(new ManifestDirectory("custom-lib"));
        }

        ManifestEntry[] manifest = manifestList.toArray(new ManifestEntry[manifestList.size()]);

        // Get the current server version
        JarFile mirthClientCoreJarFile = new JarFile(mirthClientCoreJar.getName());
        Properties versionProperties = new Properties();
        versionProperties.load(mirthClientCoreJarFile
                .getInputStream(mirthClientCoreJarFile.getJarEntry("version.properties")));
        String currentVersion = versionProperties.getProperty("mirth.version");

        List<URL> classpathUrls = new ArrayList<URL>();
        addManifestToClasspath(manifest, classpathUrls);
        addExtensionsToClasspath(classpathUrls, currentVersion);
        URLClassLoader classLoader = new URLClassLoader(classpathUrls.toArray(new URL[classpathUrls.size()]));
        Class<?> mirthClass = classLoader.loadClass("com.mirth.connect.server.Mirth");
        Thread mirthThread = (Thread) mirthClass.newInstance();
        mirthThread.setContextClassLoader(classLoader);
        mirthThread.start();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:org.apache.hadoop.hbase.util.RunTrigger.java

/**
 * @param args/*  ww w.j a v a2s  .  c  om*/
 * @throws Throwable 
 */
public static void main(String[] args) throws Throwable {
    String usage = "RunTrigger jarFile [mainClass] args...";

    if (args.length < 1) {
        System.err.println(usage);
        System.exit(-1);
    }
    int firstArg = 0;
    String fileName = args[firstArg++];
    File file = new File(fileName);
    File tmpJarFile = new File("/tmp/hbase/triggerJar/trigger.jar");
    if (tmpJarFile.exists()) {
        tmpJarFile.delete();
    }
    FileUtils.copyFile(file, tmpJarFile);

    String mainClassName = null;
    JarFile jarFile;
    try {
        jarFile = new JarFile(fileName);
    } catch (IOException e) {
        throw new IOException("Error opening trigger jar: " + fileName).initCause(e);
    }

    Manifest manifest = jarFile.getManifest();
    if (manifest != null) {
        mainClassName = manifest.getMainAttributes().getValue("Main-Class");
    }
    jarFile.close();
    System.out.println("Manifest From Jar: " + mainClassName);

    if (mainClassName == null) {
        if (args.length < 2) {
            System.err.println(usage);
            System.exit(-1);
        }
        mainClassName = args[firstArg++];
    }
    System.out.println("Manifest class from argument: " + mainClassName);

    mainClassName = mainClassName.replace("/", ".");

    //'hbase.tmp.dir'
    File tmpDir = new File("/tmp/hbase/trigger/");

    tmpDir.mkdirs();
    if (!tmpDir.isDirectory()) {
        System.err.println("Mkdirs failed to create " + tmpDir);
        System.exit(-1);
    }
    final File workDir = File.createTempFile("trigger-unjar", "", tmpDir);
    workDir.delete();
    workDir.mkdirs();
    if (!workDir.isDirectory()) {
        System.err.println("Mkdirs failed to create " + workDir);
        System.exit(-1);
    }

    Runtime.getRuntime().addShutdownHook(new Thread() {
        public void run() {
            try {
                FileUtil.fullyDelete(workDir);
            } catch (IOException e) {
            }
        }
    });

    unJar(file, workDir);

    ArrayList<URL> classPath = new ArrayList<URL>();
    classPath.add(new File(workDir + "/").toURL());
    classPath.add(file.toURL());
    classPath.add(new File(workDir, "classes/").toURL());
    File[] libs = new File(workDir, "lib").listFiles();
    if (libs != null) {
        for (int i = 0; i < libs.length; i++) {
            classPath.add(libs[i].toURL());
        }
    }

    ClassLoader loader = new URLClassLoader(classPath.toArray(new URL[0]));
    Thread.currentThread().setContextClassLoader(loader);
    Class<?> mainClass = Class.forName(mainClassName, true, loader);
    Method main = mainClass.getMethod("main", new Class[] { Array.newInstance(String.class, 0).getClass() });
    String[] newArgs = Arrays.asList(args).subList(firstArg, args.length).toArray(new String[0]);
    try {
        main.invoke(null, new Object[] { newArgs });
    } catch (InvocationTargetException e) {
        throw e.getTargetException();
    }
}