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:com.dtolabs.rundeck.ExpandRunServer.java

private void copyToolLibs(final File toolslibdir, final File coreJar) throws IOException {
    if (!toolslibdir.isDirectory()) {
        if (!toolslibdir.mkdirs()) {
            ERR("Couldn't create bin dir: " + toolslibdir.getAbsolutePath());
            return;
        }// w  w  w  .j ava2 s.  co m
    }
    //get dependencies info
    final JarFile zf = new JarFile(coreJar);
    final String depslist = zf.getManifest().getMainAttributes().getValue("Rundeck-Tools-Dependencies");
    if (null == depslist) {
        throw new RuntimeException(
                "Rundeck Core jar file manifest attribute \"Rundeck-Tools-Dependencies\" was not found: "
                        + coreJar.getAbsolutePath());
    }
    final String[] jars = depslist.split(" ");

    //copy jars from list to toolslibdir

    final String jarpath = jettyLibPath;
    for (final String jarName : jars) {
        ZipUtil.extractZip(thisJar.getAbsolutePath(), toolslibdir, jarpath + "/" + jarName, jarpath + "/");
        if (!new File(toolslibdir, jarName).exists()) {
            ERR("Failed to extract dependent jar for tools into " + toolslibdir.getAbsolutePath() + ": "
                    + jarName);
        }
    }

    //finally, copy corejar to toolslibdir
    final File destfile = new File(toolslibdir, coreJarName);
    if (!destfile.exists()) {
        if (!destfile.createNewFile()) {
            ERR("Unable to create file: " + destfile.createNewFile());
        }
    }
    ZipUtil.copyStream(new FileInputStream(coreJar), new FileOutputStream(destfile));
}

From source file:com.web.server.JarDeployer.java

/**
 * This method obtains the class name inside the jar
 * @param jarPath/*w  w w.  j  a v  a  2 s.  c  o  m*/
 * @param content
 * @throws IOException
 */
public static void getJarContent(String jarPath, CopyOnWriteArrayList content) throws IOException {
    try {
        System.out.println("enumer=" + jarPath);

        JarFile jarFile = new JarFile(jarPath);
        Enumeration enumer = (Enumeration) jarFile.entries();
        while (enumer.hasMoreElements()) {
            JarEntry entry = (JarEntry) enumer.nextElement();
            String name = entry.getName();
            if (name.endsWith(".class"))
                content.add(name.replace("/", "."));
        }
        System.out.println(content);
        jarFile.close();
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}

From source file:com.redhat.ceylon.compiler.java.test.cmr.CMRTests.java

@Test
public void testMdlModuleFromCompiledModule() throws IOException {
    compile("modules/single/module.ceylon");

    File carFile = getModuleArchive("com.redhat.ceylon.compiler.java.test.cmr.modules.single", "6.6.6");
    assertTrue(carFile.exists());//from w  w w  .ja  v a 2  s . c o  m

    JarFile car = new JarFile(carFile);
    // just to be sure
    ZipEntry bogusEntry = car.getEntry("com/redhat/ceylon/compiler/java/test/cmr/modules/single/BOGUS");
    assertNull(bogusEntry);

    ZipEntry moduleClass = car
            .getEntry("com/redhat/ceylon/compiler/java/test/cmr/modules/single/$module_.class");
    assertNotNull(moduleClass);
    car.close();

    compile("modules/single/subpackage/Subpackage.ceylon");

    // MUST reopen it
    car = new JarFile(carFile);

    ZipEntry subpackageClass = car
            .getEntry("com/redhat/ceylon/compiler/java/test/cmr/modules/single/subpackage/Subpackage.class");
    assertNotNull(subpackageClass);

    car.close();
}

From source file:org.apache.struts2.osgi.BaseOsgiHost.java

/**
 * Gets the version used to export the packages. it tries to get it from MANIFEST.MF, or the file name
 *///from w  w w .j ava2 s . c om
protected String getVersion(URL url) {
    if ("jar".equals(url.getProtocol())) {
        try {
            JarFile jarFile = new JarFile(new File(URLUtil.normalizeToFileProtocol(url).toURI()));
            Manifest manifest = jarFile.getManifest();
            if (manifest != null) {
                String version = manifest.getMainAttributes().getValue("Bundle-Version");
                if (StringUtils.isNotBlank(version)) {
                    return getVersionFromString(version);
                }
            } else {
                //try to get the version from the file name
                return getVersionFromString(jarFile.getName());
            }
        } catch (Exception e) {
            if (LOG.isErrorEnabled())
                LOG.error("Unable to extract version from [#0], defaulting to '1.0.0'", url.toExternalForm());

        }
    }

    return "1.0.0";
}

From source file:net.minecraftforge.fml.relauncher.CoreModManager.java

private static void discoverCoreMods(File mcDir, LaunchClassLoader classLoader) {
    ModListHelper.parseModList(mcDir);/* w w  w. ja  v  a2s  .  co m*/
    FMLRelaunchLog.fine("Discovering coremods");
    File coreMods = setupCoreModDir(mcDir);
    FilenameFilter ff = new FilenameFilter() {
        @Override
        public boolean accept(File dir, String name) {
            return name.endsWith(".jar");
        }
    };
    FilenameFilter derpfilter = new FilenameFilter() {
        @Override
        public boolean accept(File dir, String name) {
            return name.endsWith(".jar.zip");
        }
    };
    File[] derplist = coreMods.listFiles(derpfilter);
    if (derplist != null && derplist.length > 0) {
        FMLRelaunchLog.severe(
                "FML has detected several badly downloaded jar files,  which have been named as zip files. You probably need to download them again, or they may not work properly");
        for (File f : derplist) {
            FMLRelaunchLog.severe("Problem file : %s", f.getName());
        }
    }
    FileFilter derpdirfilter = new FileFilter() {
        @Override
        public boolean accept(File pathname) {
            return pathname.isDirectory() && new File(pathname, "META-INF").isDirectory();
        }

    };
    File[] derpdirlist = coreMods.listFiles(derpdirfilter);
    if (derpdirlist != null && derpdirlist.length > 0) {
        FMLRelaunchLog.log.getLogger().log(Level.FATAL,
                "There appear to be jars extracted into the mods directory. This is VERY BAD and will almost NEVER WORK WELL");
        FMLRelaunchLog.log.getLogger().log(Level.FATAL,
                "You should place original jars only in the mods directory. NEVER extract them to the mods directory.");
        FMLRelaunchLog.log.getLogger().log(Level.FATAL,
                "The directories below appear to be extracted jar files. Fix this before you continue.");

        for (File f : derpdirlist) {
            FMLRelaunchLog.log.getLogger().log(Level.FATAL, "Directory {} contains {}", f.getName(),
                    Arrays.asList(new File(f, "META-INF").list()));
        }

        RuntimeException re = new RuntimeException("Extracted mod jars found, loading will NOT continue");
        // We're generating a crash report for the launcher to show to the user here
        try {
            Class<?> crashreportclass = classLoader.loadClass("b");
            Object crashreport = crashreportclass.getMethod("a", Throwable.class, String.class).invoke(null, re,
                    "FML has discovered extracted jar files in the mods directory.\nThis breaks mod loading functionality completely.\nRemove the directories and replace with the jar files originally provided.");
            File crashreportfile = new File(new File(coreMods.getParentFile(), "crash-reports"),
                    String.format("fml-crash-%1$tY-%1$tm-%1$td_%1$tT.txt", Calendar.getInstance()));
            crashreportclass.getMethod("a", File.class).invoke(crashreport, crashreportfile);
            System.out.println("#@!@# FML has crashed the game deliberately. Crash report saved to: #@!@# "
                    + crashreportfile.getAbsolutePath());
        } catch (Exception e) {
            e.printStackTrace();
            // NOOP - hopefully
        }
        throw re;
    }
    File[] coreModList = coreMods.listFiles(ff);
    File versionedModDir = new File(coreMods, FMLInjectionData.mccversion);
    if (versionedModDir.isDirectory()) {
        File[] versionedCoreMods = versionedModDir.listFiles(ff);
        coreModList = ObjectArrays.concat(coreModList, versionedCoreMods, File.class);
    }

    coreModList = ObjectArrays.concat(coreModList, ModListHelper.additionalMods.values().toArray(new File[0]),
            File.class);

    coreModList = FileListHelper.sortFileList(coreModList);

    for (File coreMod : coreModList) {
        FMLRelaunchLog.fine("Examining for coremod candidacy %s", coreMod.getName());
        JarFile jar = null;
        Attributes mfAttributes;
        String fmlCorePlugin;
        try {
            jar = new JarFile(coreMod);
            if (jar.getManifest() == null) {
                // Not a coremod and no access transformer list
                continue;
            }
            ModAccessTransformer.addJar(jar);
            mfAttributes = jar.getManifest().getMainAttributes();
            String cascadedTweaker = mfAttributes.getValue("TweakClass");
            if (cascadedTweaker != null) {
                FMLRelaunchLog.info("Loading tweaker %s from %s", cascadedTweaker, coreMod.getName());
                Integer sortOrder = Ints.tryParse(Strings.nullToEmpty(mfAttributes.getValue("TweakOrder")));
                sortOrder = (sortOrder == null ? Integer.valueOf(0) : sortOrder);
                handleCascadingTweak(coreMod, jar, cascadedTweaker, classLoader, sortOrder);
                ignoredModFiles.add(coreMod.getName());
                continue;
            }
            List<String> modTypes = mfAttributes.containsKey(MODTYPE)
                    ? Arrays.asList(mfAttributes.getValue(MODTYPE).split(","))
                    : ImmutableList.of("FML");

            if (!modTypes.contains("FML")) {
                FMLRelaunchLog.fine(
                        "Adding %s to the list of things to skip. It is not an FML mod,  it has types %s",
                        coreMod.getName(), modTypes);
                ignoredModFiles.add(coreMod.getName());
                continue;
            }
            String modSide = mfAttributes.containsKey(MODSIDE) ? mfAttributes.getValue(MODSIDE) : "BOTH";
            if (!("BOTH".equals(modSide) || FMLLaunchHandler.side.name().equals(modSide))) {
                FMLRelaunchLog.fine("Mod %s has ModSide meta-inf value %s, and we're %s. It will be ignored",
                        coreMod.getName(), modSide, FMLLaunchHandler.side.name());
                ignoredModFiles.add(coreMod.getName());
                continue;
            }
            ModListHelper.additionalMods.putAll(extractContainedDepJars(jar, coreMods, versionedModDir));
            fmlCorePlugin = mfAttributes.getValue("FMLCorePlugin");
            if (fmlCorePlugin == null) {
                // Not a coremod
                FMLRelaunchLog.fine("Not found coremod data in %s", coreMod.getName());
                continue;
            }
        } catch (IOException ioe) {
            FMLRelaunchLog.log(Level.ERROR, ioe, "Unable to read the jar file %s - ignoring",
                    coreMod.getName());
            continue;
        } finally {
            if (jar != null) {
                try {
                    jar.close();
                } catch (IOException e) {
                    // Noise
                }
            }
        }
        // Support things that are mod jars, but not FML mod jars
        try {
            classLoader.addURL(coreMod.toURI().toURL());
            if (!mfAttributes.containsKey(COREMODCONTAINSFMLMOD)) {
                FMLRelaunchLog.finer("Adding %s to the list of known coremods, it will not be examined again",
                        coreMod.getName());
                ignoredModFiles.add(coreMod.getName());
            } else {
                FMLRelaunchLog.finer(
                        "Found FMLCorePluginContainsFMLMod marker in %s, it will be examined later for regular @Mod instances",
                        coreMod.getName());
                candidateModFiles.add(coreMod.getName());
            }
        } catch (MalformedURLException e) {
            FMLRelaunchLog.log(Level.ERROR, e, "Unable to convert file into a URL. weird");
            continue;
        }
        loadCoreMod(classLoader, fmlCorePlugin, coreMod);
    }
}

From source file:com.taobao.android.apatch.MergePatch.java

private Dex getDexFromJar(File file) throws IOException {
    JarFile jarFile = null;//  ww w . ja  va  2s  .c o  m
    try {
        jarFile = new JarFile(file);
        JarEntry dexEntry = jarFile.getJarEntry("classes.dex");
        return new Dex(jarFile.getInputStream(dexEntry));
    } finally {
        if (jarFile != null) {
            jarFile.close();
        }
    }
}

From source file:com.arcusys.liferay.vaadinplugin.VaadinUpdater.java

private boolean extractVAADINFolder(String sourceDirPath, String jarName, String tmpFolderName,
        String destination) throws IOException {
    String vaadinJarFilePath = sourceDirPath + fileSeparator + jarName;
    JarFile vaadinJar = new JarFile(vaadinJarFilePath);
    String vaadinExtractedPath = sourceDirPath + tmpFolderName;
    outputLog.log("Extracting " + jarName);
    try {/*w w  w  .  j  ava  2  s.c  o m*/
        Enumeration<JarEntry> entries = vaadinJar.entries();
        while (entries.hasMoreElements()) {
            JarEntry entry = entries.nextElement();
            boolean extractSuccessful = ControlPanelPortletUtil.extractJarEntry(vaadinJar, entry,
                    vaadinExtractedPath);
            if (!extractSuccessful) {
                outputLog.log("Extraction failed: " + entry.getName());
                return true;
            }
        }
    } catch (Exception e) {
        log.warn("Extracting VAADIN folder failed.", e);
        upgradeListener.updateFailed("Extraction failed: " + e.getMessage());
        return true;
    } finally {
        vaadinJar.close();
    }

    String vaadinExtractedVaadinPath = vaadinExtractedPath + fileSeparator + "VAADIN" + fileSeparator;
    File vaadinExtractedVaadin = new File(vaadinExtractedVaadinPath);
    if (!vaadinExtractedVaadin.exists()) {
        upgradeListener.updateFailed("Could not find " + vaadinExtractedVaadinPath);
        return true;
    }

    FileUtils.copyDirectory(vaadinExtractedVaadin, new File(destination));
    return false;
}

From source file:org.apache.storm.utils.ServerUtils.java

/**
 * Unpack matching files from a jar. Entries inside the jar that do
 * not match the given pattern will be skipped.
 *
 * @param jarFile the .jar file to unpack
 * @param toDir the destination directory into which to unpack the jar
 */// w w w.  jav a2 s.  c om
public static void unJar(File jarFile, File toDir) throws IOException {
    JarFile jar = new JarFile(jarFile);
    try {
        Enumeration<JarEntry> entries = jar.entries();
        while (entries.hasMoreElements()) {
            final JarEntry entry = entries.nextElement();
            if (!entry.isDirectory()) {
                InputStream in = jar.getInputStream(entry);
                try {
                    File file = new File(toDir, entry.getName());
                    ensureDirectory(file.getParentFile());
                    OutputStream out = new FileOutputStream(file);
                    try {
                        copyBytes(in, out, 8192);
                    } finally {
                        out.close();
                    }
                } finally {
                    in.close();
                }
            }
        }
    } finally {
        jar.close();
    }
}

From source file:org.apache.hyracks.maven.license.GenerateFileMojo.java

private void resolveArtifactFiles(final String name, Predicate<JarEntry> filter,
        BiConsumer<Project, String> consumer, UnaryOperator<String> contentTransformer)
        throws MojoExecutionException, IOException {
    for (Project p : getProjects()) {
        File artifactFile = new File(p.getArtifactPath());
        if (!artifactFile.exists()) {
            throw new MojoExecutionException("Artifact file " + artifactFile + " does not exist!");
        } else if (!artifactFile.getName().endsWith(".jar")) {
            getLog().info("Skipping unknown artifact file type: " + artifactFile);
            continue;
        }//from ww w .  jav  a  2  s  .c  o m
        try (JarFile jarFile = new JarFile(artifactFile)) {
            SortedMap<String, JarEntry> matches = gatherMatchingEntries(jarFile, filter);
            if (matches.isEmpty()) {
                getLog().warn("No " + name + " file found for " + p.gav());
            } else {
                if (matches.size() > 1) {
                    getLog().warn("Multiple " + name + " files found for " + p.gav() + ": " + matches.keySet()
                            + "; taking first");
                } else {
                    getLog().info(p.gav() + " has " + name + " file: " + matches.keySet());
                }
                resolveContent(p, jarFile, matches.values().iterator().next(), contentTransformer, consumer,
                        name);
            }
        }
    }
}

From source file:cc.creativecomputing.io.CCIOUtil.java

/**
 * Simplified method to open a Java InputStream.
 * <p>//from   ww  w  . j  a va2  s  .c  o m
 * This method is useful if you want to easily open things from the data folder or from a URL, but want an
 * InputStream object so that you can use other Java methods to take more control of how the stream is read.
 * </p>
 * <p>
 * If the requested item doesn't exist, null is returned. This will also check to see if the user is asking for a
 * file whose name isn't properly capitalized. It is strongly recommended that libraries use this method to open
 * data files, so that the loading sequence is handled in the same way.
 * </p>
 * 
 * @param theFilename The filename passed in can be:
 *        <ul>
 *        <li>An URL, for instance openStream("http://creativecomputing.cc/");</li>
 *        <li>A file in the application's data folder</li>
 *        <li>Another file to be opened locally</li>
 *        </ul>
 */
static public InputStream createStream(String theFilename) {
    InputStream stream = null;

    // check if the filename makes sense
    if (theFilename == null || theFilename.length() == 0)
        return null;

    // safe to check for this as a url first. this will prevent online
    try {
        URL urlObject = new URL(theFilename);
        URLConnection con = urlObject.openConnection();
        // try to be a browser some sources do not like bots
        con.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.5; Windows NT 5.0; H010818)");
        return con.getInputStream();
    } catch (MalformedURLException mfue) {
        // not a url, that's fine
    } catch (FileNotFoundException fnfe) {
        // Java 1.5 likes to throw this when URL not available.

    } catch (IOException e) {
        return null;
    }

    // load resource from jar using the path with getResourceAsStream
    if (theFilename.contains(".jar!")) {
        String[] myParts = theFilename.split("!");
        String myJarPath = myParts[0];
        if (myJarPath.startsWith("file:")) {
            myJarPath = myJarPath.substring(5);
        }

        String myFilePath = myParts[1];
        if (myFilePath.startsWith("/")) {
            myFilePath = myFilePath.substring(1);
        }
        try {
            @SuppressWarnings("resource")
            JarFile myJarFile = new JarFile(myJarPath);
            return myJarFile.getInputStream(myJarFile.getEntry(myFilePath));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // handle case sensitivity check
    try {
        // first see if it's in a data folder
        File file = dataFile(theFilename);
        if (!file.exists()) {
            // next see if it's just in this folder
            file = new File(CCSystem.applicationPath, theFilename);
        }
        if (file.exists()) {
            try {
                String filePath = file.getCanonicalPath();
                String filenameActual = new File(filePath).getName();
                // make sure there isn't a subfolder prepended to the name
                String filenameShort = new File(theFilename).getName();
                // if the actual filename is the same, but capitalized
                // differently, warn the user.
                //if (filenameActual.equalsIgnoreCase(filenameShort) &&
                //!filenameActual.equals(filenameShort)) {
                if (!filenameActual.equals(filenameShort)) {
                    throw new RuntimeException("This file is named " + filenameActual + " not " + theFilename
                            + ". Re-name it " + "or change your code.");
                }
            } catch (IOException e) {
            }
        }

        // if this file is ok, may as well just load it
        stream = new FileInputStream(file);
        if (stream != null)
            return stream;

        // have to break these out because a general Exception might
        // catch the RuntimeException being thrown above
    } catch (IOException ioe) {
    } catch (SecurityException se) {
    }

    try {
        // attempt to load from a local file, used when running as
        // an application, or as a signed applet
        try { // first try to catch any security exceptions
            try {
                stream = new FileInputStream(dataPath(theFilename));
                if (stream != null)
                    return stream;
            } catch (IOException e2) {
            }

            try {
                stream = new FileInputStream(appPath(theFilename));
                if (stream != null)
                    return stream;
            } catch (Exception e) {
            } // ignored

            try {
                stream = new FileInputStream(theFilename);
                if (stream != null)
                    return stream;
            } catch (IOException e1) {
            }

        } catch (SecurityException se) {
        } // online, whups

    } catch (Exception e) {
        //die(e.getMessage(), e);
        e.printStackTrace();
    }
    return null;
}