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:de.nmichael.efa.Daten.java

public static Vector getEfaInfos(boolean efaInfos, boolean pluginInfos, boolean javaInfos, boolean hostInfos,
        boolean jarInfos) {
    Vector infos = new Vector();

    // efa-Infos/*from   ww w  . j  a  va 2s  .  com*/
    if (efaInfos) {
        infos.add("efa.version=" + Daten.VERSIONID);
        if (EFALIVE_VERSION != null && EFALIVE_VERSION.length() > 0) {
            infos.add("efalive.version=" + Daten.EFALIVE_VERSION);
        }
        if (applID != APPL_EFABH || applMode == APPL_MODE_ADMIN) {
            if (Daten.efaMainDirectory != null) {
                infos.add("efa.dir.main=" + Daten.efaMainDirectory);
            }
            if (Daten.efaBaseConfig != null && Daten.efaBaseConfig.efaUserDirectory != null) {
                infos.add("efa.dir.user=" + Daten.efaBaseConfig.efaUserDirectory);
            }
            if (Daten.efaProgramDirectory != null) {
                infos.add("efa.dir.program=" + Daten.efaProgramDirectory);
            }
            if (Daten.efaPluginDirectory != null) {
                infos.add("efa.dir.plugin=" + Daten.efaPluginDirectory);
            }
            if (Daten.efaDocDirectory != null) {
                infos.add("efa.dir.doc=" + Daten.efaDocDirectory);
            }
            if (Daten.efaDataDirectory != null) {
                infos.add("efa.dir.data=" + Daten.efaDataDirectory);
            }
            if (Daten.efaCfgDirectory != null) {
                infos.add("efa.dir.cfg=" + Daten.efaCfgDirectory);
            }
            if (Daten.efaBakDirectory != null) {
                infos.add("efa.dir.bak=" + Daten.efaBakDirectory);
            }
            if (Daten.efaTmpDirectory != null) {
                infos.add("efa.dir.tmp=" + Daten.efaTmpDirectory);
            }
        }
    }

    // efa Plugin-Infos
    if (pluginInfos) {
        try {
            File dir = new File(Daten.efaPluginDirectory);
            if ((applID != APPL_EFABH || applMode == APPL_MODE_ADMIN) && Logger.isDebugLogging()) {
                File[] files = dir.listFiles();
                for (File file : files) {
                    if (file.isFile()) {
                        infos.add("efa.plugin.file=" + file.getName() + ":" + file.length());
                    }
                }
            }

            Plugins plugins = Plugins.getPluginInfoFromLocalFile();
            String[] names = plugins.getAllPluginNames();
            for (String name : names) {
                infos.add("efa.plugin." + name + "="
                        + (Plugins.isPluginInstalled(name) ? "installed" : "not installed"));
            }
        } catch (Exception e) {
            Logger.log(Logger.ERROR, Logger.MSG_CORE_INFOFAILED,
                    International.getString("Programminformationen konnten nicht ermittelt werden") + ": "
                            + e.toString());
            return null;
        }
    }

    // Java Infos
    if (javaInfos) {
        infos.add("java.version=" + System.getProperty("java.version"));
        infos.add("java.vendor=" + System.getProperty("java.vendor"));
        infos.add("java.home=" + System.getProperty("java.home"));
        infos.add("java.vm.version=" + System.getProperty("java.vm.version"));
        infos.add("java.vm.vendor=" + System.getProperty("java.vm.vendor"));
        infos.add("java.vm.name=" + System.getProperty("java.vm.name"));
        infos.add("os.name=" + System.getProperty("os.name"));
        infos.add("os.arch=" + System.getProperty("os.arch"));
        infos.add("os.version=" + System.getProperty("os.version"));
        if (applID != APPL_EFABH || applMode == APPL_MODE_ADMIN) {
            infos.add("user.home=" + System.getProperty("user.home"));
            infos.add("user.name=" + System.getProperty("user.name"));
            infos.add("user.dir=" + System.getProperty("user.dir"));
            infos.add("java.class.path=" + System.getProperty("java.class.path"));
        }
    }

    // Host Infos
    if (hostInfos) {
        if (applID != APPL_EFABH || applMode == APPL_MODE_ADMIN) {
            try {
                infos.add("host.name=" + InetAddress.getLocalHost().getCanonicalHostName());
                infos.add("host.ip=" + InetAddress.getLocalHost().getHostAddress());
                infos.add("host.interface=" + EfaUtil
                        .getInterfaceInfo(NetworkInterface.getByInetAddress(InetAddress.getLocalHost())));
            } catch (Exception eingore) {
            }
        }
    }

    // JAR methods
    if (jarInfos && Logger.isDebugLogging()) {
        try {
            String cp = System.getProperty("java.class.path");
            while (cp != null && cp.length() > 0) {
                int pos = cp.indexOf(";");
                if (pos < 0) {
                    pos = cp.indexOf(":");
                }
                String jarfile;
                if (pos >= 0) {
                    jarfile = cp.substring(0, pos);
                    cp = cp.substring(pos + 1);
                } else {
                    jarfile = cp;
                    cp = null;
                }
                if (jarfile != null && jarfile.length() > 0 && new File(jarfile).isFile()) {
                    try {
                        infos.add("java.jar.filename=" + jarfile);
                        JarFile jar = new JarFile(jarfile);
                        Enumeration _enum = jar.entries();
                        Object o;
                        while (_enum.hasMoreElements() && (o = _enum.nextElement()) != null) {
                            infos.add(
                                    "java.jar.content=" + o + ":" + (jar.getEntry(o.toString()) == null ? "null"
                                            : Long.toString(jar.getEntry(o.toString()).getSize())));
                        }
                        jar.close();
                    } catch (Exception e) {
                        Logger.log(Logger.ERROR, Logger.MSG_CORE_INFOFAILED, e.toString());
                        return null;
                    }
                }
            }
        } catch (Exception e) {
            Logger.log(Logger.ERROR, Logger.MSG_CORE_INFOFAILED,
                    International.getString("Programminformationen konnten nicht ermittelt werden") + ": "
                            + e.toString());
            return null;
        }
    }
    return infos;
}

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

@Test
public void testMdlDefaultHasNoOsgiManifest() throws IOException {
    compile("modules/def/CeylonClass.ceylon");

    File carFile = getModuleArchive("default", null);
    assertTrue(carFile.exists());/*from   w ww  .ja  v  a2  s.co  m*/

    try (JarFile car = new JarFile(carFile)) {
        ZipEntry manifest = car.getEntry(OsgiUtil.OsgiManifest.MANIFEST_FILE_NAME);
        try (InputStream input = car.getInputStream(manifest)) {
            Manifest m = new Manifest(input);
            Assert.assertTrue(OsgiUtil.DefaultModuleManifest.isDefaultModule(m));
        }
    }
}

From source file:org.apache.catalina.loader.WebappClassLoader.java

/**
 * 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
 *///from  w  w w . ja  v  a  2  s  .  c  o  m
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 (log.isDebugEnabled())
            log.debug(" Checking for " + name);
        JarEntry jarEntry = jarFile.getJarEntry(name);
        if (jarEntry != null) {
            log.info("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);

}

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

@Test
public void testMdlOsgiManifestDisabled() throws IOException {
    ErrorCollector c = new ErrorCollector();
    List<String> options = new ArrayList<String>(defaultOptions.size() + 1);
    options.addAll(defaultOptions);/*  w  ww  .ja va 2 s . c o  m*/
    options.add("-noosgi");
    assertCompilesOk(c, getCompilerTask(options, c, "modules/osgi/a/module.ceylon",
            "modules/osgi/a/package.ceylon", "modules/osgi/a/A.ceylon").call2());

    final String moduleName = "com.redhat.ceylon.compiler.java.test.cmr.modules.osgi.a";
    final String moduleVersion = "1.1.0";

    File carFile = getModuleArchive(moduleName, moduleVersion);
    JarFile car = new JarFile(carFile);

    ZipEntry manifest = car.getEntry(OsgiUtil.OsgiManifest.MANIFEST_FILE_NAME);
    assertNull(manifest);

    car.close();
}

From source file:JNLPAppletLauncher.java

/**
 * Download, cache, verify, and unpack the specified native jar file.
 * Before downloading, check the cached time stamp for the jar file
 * against the server. If the time stamp is valid and matches that of the
 * server, then we will use the locally cached files. This method assumes
 * that cacheDir and nativeTmpDir both exist.
 *
 * An IOException is thrown if the files cannot loaded for some reason.
 *///  w  w w  . j a  v  a  2  s  . c  om
private void processNativeJar(URL url) throws IOException {
    assert cacheDir.isDirectory();
    assert nativeTmpDir.isDirectory();

    // 6618105: Map '\' to '/' prior to stripping off the path
    String urlString = url.toExternalForm().replace('\\', '/');
    String nativeFileName = urlString.substring(urlString.lastIndexOf("/") + 1);
    File nativeFile = new File(cacheDir, nativeFileName);
    // Make sure the file is not "." or ".."
    if (nativeFile.isDirectory()) {
        throw new IOException(nativeFile + " is a directory");
    }

    String tmpStr = nativeFileName;
    int idx = nativeFileName.lastIndexOf(".");
    if (idx > 0) {
        tmpStr = nativeFileName.substring(0, idx);
    }
    String indexFileName = tmpStr + ".idx";
    File indexFile = new File(cacheDir, indexFileName);

    if (VERBOSE) {
        System.err.println("nativeFile = " + nativeFile);
        System.err.println("indexFile = " + indexFile);
    }

    displayMessage("Loading: " + nativeFileName);
    setProgress(0);

    URLConnection conn = url.openConnection();
    conn.connect();

    Map/*<String,List<String>>*/ headerFields = conn.getHeaderFields();
    if (VERBOSE) {
        for (Iterator iter = headerFields.entrySet().iterator(); iter.hasNext();) {
            Entry/*<String,List<String>>*/ e = (Entry) iter.next();
            for (Iterator iter2 = ((List/*<String>*/) e.getValue()).iterator(); iter2.hasNext();) {
                String s = (String) iter2.next();
                if (e.getKey() != null) {
                    System.err.print(e.getKey() + ": ");
                }
                System.err.print(s + " ");
            }
            System.err.println();
        }
        System.err.println();
    }

    // Validate the cache, download the jar if needed
    // TODO: rather than synchronizing on System.out during cache validation,
    // we should use a System property as a lock token (protected by
    // System.out) so we don't hold a synchronized lock on System.out during
    // a potentially long download operation.
    synchronized (System.out) {
        validateCache(conn, nativeFile, indexFile);
    }

    // Unpack the jar file
    displayMessage("Unpacking: " + nativeFileName);
    setProgress(0);

    // Enumerate the jar file looking for native libraries
    JarFile jarFile = new JarFile(nativeFile);
    Set/*<String>*/ rootEntries = getRootEntries(jarFile);
    Set/*<String>*/ nativeLibNames = getNativeLibNames(rootEntries);

    // Validate certificates; throws exception upon validation error
    validateCertificates(jarFile, rootEntries);

    // Extract native libraries from the jar file
    extractNativeLibs(jarFile, rootEntries, nativeLibNames);

    if (VERBOSE) {
        System.err.println();
    }
}

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

private Manifest getManifest(String moduleName, String moduleVersion) throws IOException {
    File carFile = getModuleArchive(moduleName, moduleVersion);
    Manifest manifest = null;//from   w  w w .  j a  va2 s . c  o  m
    try (JarFile car = new JarFile(carFile)) {
        manifest = car.getManifest();
    }
    assertNotNull(manifest);
    return manifest;
}

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

@Test
public void testMdlPomManifest() throws IOException {
    compile("modules/pom/a/module.ceylon", "modules/pom/b/module.ceylon");

    final String moduleName = "com.redhat.ceylon.compiler.java.test.cmr.modules.pom.b";
    final String moduleVersion = "1";

    File carFile = getModuleArchive(moduleName, moduleVersion);
    assertTrue(carFile.exists());//from   w  w w. j  a v  a  2 s  .  c o  m
    JarFile car = new JarFile(carFile);

    ZipEntry pomFile = car
            .getEntry("META-INF/maven/com.redhat.ceylon.compiler.java.test.cmr.modules.pom/b/pom.xml");
    assertNotNull(pomFile);
    String pomContents = read(car, pomFile);
    assertEquals("<?xml version=\"1.0\" ?>\n"
            + "<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd\">\n"
            + " <modelVersion>4.0.0</modelVersion>\n"
            + " <groupId>com.redhat.ceylon.compiler.java.test.cmr.modules.pom</groupId>\n"
            + " <artifactId>b</artifactId>\n" + " <version>1</version>\n"
            + " <name>com.redhat.ceylon.compiler.java.test.cmr.modules.pom.b</name>\n" + " <dependencies>\n"
            + "  <dependency>\n"
            + "    <groupId>com.redhat.ceylon.compiler.java.test.cmr.modules.pom</groupId>\n"
            + "    <artifactId>a</artifactId>\n" + "    <version>1</version>\n" + "  </dependency>\n"
            + " </dependencies>\n" + "</project>\n", pomContents);

    ZipEntry propertiesFile = car
            .getEntry("META-INF/maven/com.redhat.ceylon.compiler.java.test.cmr.modules.pom/b/pom.properties");
    assertNotNull(propertiesFile);
    String propertiesContents = read(car, propertiesFile);
    // remove the date comment
    propertiesContents = propertiesContents.replaceFirst("^(#Generated by Ceylon\n)#[^\n]+\n", "$1");
    assertEquals(
            "#Generated by Ceylon\n" + "version=1\n"
                    + "groupId=com.redhat.ceylon.compiler.java.test.cmr.modules.pom\n" + "artifactId=b\n",
            propertiesContents);
    car.close();
}

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

@Test
public void testMdlNoPomManifest() throws IOException {
    ErrorCollector c = new ErrorCollector();
    assertCompilesOk(c, getCompilerTask(Arrays.asList("-nopom", "-out", destDir), c,
            "modules/pom/a/module.ceylon", "modules/pom/b/module.ceylon").call2());

    final String moduleName = "com.redhat.ceylon.compiler.java.test.cmr.modules.pom.b";
    final String moduleVersion = "1";

    File carFile = getModuleArchive(moduleName, moduleVersion);
    assertTrue(carFile.exists());//www .  j a  v a  2 s  . c om
    JarFile car = new JarFile(carFile);

    ZipEntry pomFile = car
            .getEntry("META-INF/maven/com.redhat.ceylon.compiler.java.test.cmr.modules.pom/b/pom.xml");
    assertNull(pomFile);

    ZipEntry propertiesFile = car
            .getEntry("META-INF/maven/com.redhat.ceylon.compiler.java.test.cmr.modules.pom/b/pom.properties");
    assertNull(propertiesFile);
    car.close();
}

From source file:org.apache.openejb.config.DeploymentLoader.java

public static Map<String, URL> getWebDescriptors(final File warFile) throws IOException {
    final Map<String, URL> descriptors = new TreeMap<String, URL>();

    // xbean resource finder has a bug when you use any uri but "META-INF"
    // and the jar file does not contain a directory entry for the uri

    if (warFile.isFile()) { // only to discover module type so xml file filtering is enough
        final URL jarURL = new URL("jar", "", -1, warFile.toURI().toURL() + "!/");
        try {/*from w  ww .j a  va  2  s  . c  om*/
            final JarFile jarFile = new JarFile(warFile);
            for (final JarEntry entry : Collections.list(jarFile.entries())) {
                final String entryName = entry.getName();
                if (!entry.isDirectory() && entryName.startsWith("WEB-INF/")
                        && (KNOWN_DESCRIPTORS.contains(entryName.substring("WEB-INF/".length()))
                                || entryName.endsWith(".xml"))) { // + web.xml, web-fragment.xml...
                    descriptors.put(entryName, new URL(jarURL, entry.getName()));
                }
            }
        } catch (final IOException e) {
            // most likely an invalid jar file
        }
    } else if (warFile.isDirectory()) {
        final File webInfDir = new File(warFile, "WEB-INF");
        if (webInfDir.isDirectory()) {
            final File[] files = webInfDir.listFiles();
            if (files != null) {
                for (final File file : files) {
                    if (!file.isDirectory()) {
                        descriptors.put(file.getName(), file.toURI().toURL());
                    }
                }
            }
        }

        // handle some few file(s) which can be in META-INF too
        final File webAppDdDir = new File(webInfDir, "classes/" + ddDir);
        if (webAppDdDir.isDirectory()) {
            final File[] files = webAppDdDir.listFiles();
            if (files != null) {
                for (final File file : files) {
                    final String name = file.getName();
                    if (!descriptors.containsKey(name)) {
                        descriptors.put(name, file.toURI().toURL());
                    } else {
                        logger.warning("Can't have a " + name
                                + " in WEB-INF and WEB-INF/classes/META-INF, second will be ignored");
                    }
                }
            }
        }
    }

    return descriptors;
}

From source file:org.apache.openejb.config.DeploymentLoader.java

private Class<? extends DeploymentModule> checkAnnotations(final URL urls, final ClassLoader classLoader,
        final boolean scanPotentialEjbModules, final boolean scanPotentialClientModules) {
    Class<? extends DeploymentModule> cls = null;
    if (scanPotentialEjbModules || scanPotentialClientModules) {
        final AnnotationFinder classFinder = new AnnotationFinder(classLoader, urls);

        final Set<Class<? extends DeploymentModule>> otherTypes = new LinkedHashSet<Class<? extends DeploymentModule>>();

        final AnnotationFinder.Filter filter = new AnnotationFinder.Filter() {
            final String packageName = LocalClient.class.getName().replace("LocalClient", "");

            @Override// w w w .  j  ava2  s .  c  o  m
            public boolean accept(final String annotationName) {
                if (scanPotentialClientModules && annotationName.startsWith(packageName)) {
                    if (LocalClient.class.getName().equals(annotationName)) {
                        otherTypes.add(ClientModule.class);
                    }
                    if (RemoteClient.class.getName().equals(annotationName)) {
                        otherTypes.add(ClientModule.class);
                    }
                } else if (scanPotentialEjbModules) {
                    if (annotationName.startsWith("javax.ejb.")) {
                        if ("javax.ejb.Stateful".equals(annotationName)) {
                            return true;
                        }
                        if ("javax.ejb.Stateless".equals(annotationName)) {
                            return true;
                        }
                        if ("javax.ejb.Singleton".equals(annotationName)) {
                            return true;
                        }
                        if ("javax.ejb.MessageDriven".equals(annotationName)) {
                            return true;
                        }
                    } else if (scanManagedBeans && "javax.annotation.ManagedBean".equals(annotationName)) {
                        return true;
                    }
                }
                return false;
            }
        };

        if (classFinder.find(filter)) {
            cls = EjbModule.class;
            // if it is a war just throw an error
            try {
                final File ar = URLs.toFile(urls);
                if (!ar.isDirectory() && !ar.getName().endsWith("ar")) { // guess no archive extension, check it is not a hidden war
                    final JarFile war = new JarFile(ar);
                    final ZipEntry entry = war.getEntry("WEB-INF/");
                    if (entry != null) {
                        logger.warning("you deployed " + urls.toExternalForm()
                                + ", it seems it is a war with no extension, please rename it");
                    }
                }
            } catch (final Exception ignored) {
                // no-op
            }
        }

        if (otherTypes.size() > 0) {
            // We may want some ordering/sorting if we add more type scanning
            cls = otherTypes.iterator().next();
        }
    }
    return cls;
}