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:net.fabricmc.installer.installer.ClientInstaller.java

public static void install(File mcDir, String version, IInstallerProgress progress) throws IOException {
    String[] split = version.split("-");
    if (isValidInstallLocation(mcDir, split[0]).isPresent()) {
        throw new RuntimeException(isValidInstallLocation(mcDir, split[0]).get());
    }/*from   w  ww  .j av  a 2 s  .  c om*/
    File fabricData = new File(mcDir, "fabricData");
    File fabricJar = new File(fabricData, version + ".jar");
    if (!fabricJar.exists()) {
        progress.updateProgress(Translator.getString("install.client.downloadFabric"), 10);
        FileUtils.copyURLToFile(new URL(MavenHandler.getPath(Reference.MAVEN_SERVER_URL,
                Reference.PACKAGE_FABRIC, Reference.NAME_FABRIC_LOADER, version)), fabricJar);
    }
    JarFile jarFile = new JarFile(fabricJar);
    Attributes attributes = jarFile.getManifest().getMainAttributes();
    String mcVersion = attributes.getValue("MinecraftVersion");
    install(mcDir, mcVersion, progress, fabricJar);
    FileUtils.deleteDirectory(fabricData);
}

From source file:com.apifest.oauth20.LifecycleEventHandlers.java

@SuppressWarnings("unchecked")
public static void loadLifecycleHandlers(URLClassLoader classLoader, String customJar) {
    try {//from w  w  w.j  av a  2 s. co m
        if (classLoader != null) {
            JarFile jarFile = new JarFile(customJar);
            Enumeration<JarEntry> entries = jarFile.entries();
            while (entries.hasMoreElements()) {
                JarEntry entry = entries.nextElement();
                if (entry.isDirectory() || !entry.getName().endsWith(".class")) {
                    continue;
                }
                // remove .class
                String className = entry.getName().substring(0, entry.getName().length() - 6);
                className = className.replace('/', '.');
                try {
                    // REVISIT: check for better solution
                    if (className.startsWith("org.jboss.netty") || className.startsWith("org.apache.log4j")
                            || className.startsWith("org.apache.commons")) {
                        continue;
                    }
                    Class<?> clazz = classLoader.loadClass(className);
                    if (clazz.isAnnotationPresent(OnRequest.class)
                            && LifecycleHandler.class.isAssignableFrom(clazz)) {
                        requestEventHandlers.add((Class<LifecycleHandler>) clazz);
                        log.debug("preIssueTokenHandler added {}", className);
                    }
                    if (clazz.isAnnotationPresent(OnResponse.class)
                            && LifecycleHandler.class.isAssignableFrom(clazz)) {
                        responseEventHandlers.add((Class<LifecycleHandler>) clazz);
                        log.debug("postIssueTokenHandler added {}", className);
                    }
                    if (clazz.isAnnotationPresent(OnException.class)
                            && ExceptionEventHandler.class.isAssignableFrom(clazz)) {
                        exceptionHandlers.add((Class<ExceptionEventHandler>) clazz);
                        log.debug("exceptionHandlers added {}", className);
                    }
                } catch (ClassNotFoundException e1) {
                    // continue
                }
            }
        }
    } catch (MalformedURLException e) {
        log.error("cannot load lifecycle handlers", e);
    } catch (IOException e) {
        log.error("cannot load lifecycle handlers", e);
    } catch (IllegalArgumentException e) {
        log.error(e.getMessage());
    }
}

From source file:org.apache.stratos.cartridge.agent.statistics.publisher.PluginLoader.java

public static List<Class> loadPluginClassesFromJar(File jarPath, Class pluginInterface) {
    List<Class> listeners = new LinkedList<Class>();

    try {/*from  w  w w .j a  v  a  2s.co  m*/
        URLClassLoader loader = new URLClassLoader(new URL[] { jarPath.toURI().toURL() });
        JarFile jar = new JarFile(jarPath);
        Enumeration<? extends JarEntry> jarEnum = jar.entries();

        log.trace("Scanning jar file " + jarPath);

        while (jarEnum.hasMoreElements()) {
            ZipEntry zipEntry = jarEnum.nextElement();
            String fileName = zipEntry.getName();

            if (fileName.endsWith(".class")) {
                log.trace("Considering jar entry " + fileName);
                try {
                    String className = fileName.replace(".class", "").replace("/", ".");
                    Class cls = loader.loadClass(className);
                    log.trace("Loaded class " + className);

                    if (hasInterface(cls, pluginInterface)) {
                        log.trace("Class has " + pluginInterface.getName() + " interface; adding ");
                        listeners.add(cls);
                    }
                } catch (ClassNotFoundException e) {
                    log.error("Unable to load class from " + fileName + " in " + jarPath);
                }
            }
        }

    } catch (IOException e) {
        log.error("Unable to open JAR file " + jarPath, e);
    }

    return listeners;
}

From source file:org.clickframes.util.JarResourceUtil.java

public static File copyTemplatesFromJarToTempDirectory(String jarFileName, String autoscanDirectoryName)
        throws IOException {
    // String jarName = "clickframes-webflow-plugin";
    // String AUTOSCAN_DIR = "/autoscan/";
    final String classpath = System.getProperty("java.class.path");
    String[] classpathArray = classpath.split(File.pathSeparatorChar + "");

    logger.debug("classpath = " + classpath);
    for (String classpathJar : classpathArray) {
        logger.debug("jar = " + classpathJar);
        if (classpathJar.contains(jarFileName)) {
            JarFile jarFile = new JarFile(classpathJar);
            File temporaryFolder = new File(System.getProperty("java.io.tmpdir"), "autoscanTempDir");
            temporaryFolder.mkdirs();/*from w  ww .  j  a va  2s .  c  o m*/
            temporaryFolder.deleteOnExit();
            // list all entries in jar
            Enumeration<JarEntry> resources = jarFile.entries();
            while (resources.hasMoreElements()) {
                JarEntry je = resources.nextElement();
                final String fileInJar = je.getName();
                // if autoscan target, copy to temp folder
                if (fileInJar.contains(autoscanDirectoryName)) {
                    copyFile(jarFile, temporaryFolder, je, fileInJar);
                }
            }
            return temporaryFolder;
        }
    }
    throw new RuntimeException("We're sorry, we couldn't find your jar");
}

From source file:org.codehaus.mojo.license.osgi.AboutFileLicenseResolver.java

public List<License> resolve(String artifactId, File file) throws IOException {
    List<License> licenses = new ArrayList<License>();
    JarFile jarFile = new JarFile(file);
    try {/*  www. j  a  v a2  s  .  c  o  m*/
        ZipEntry entry = jarFile.getEntry(ABOUT_HTML);
        if (entry != null) {
            licenses.add(createJarEmbeddedLicense(artifactId, file, ABOUT_HTML));
            String content = readContent(jarFile, entry);
            licenses.addAll(findThrirdPartyLicenses(artifactId, file, content));
        }
        return licenses;
    } finally {
        jarFile.close();
    }
}

From source file:fr.husta.test.assembly.JarWithDependenciesTest.java

@Test
public void checkMetaInfContent() throws IOException {
    // check META-INF/services/java.sql.Driver exists
    JarFile jar = new JarFile("target/issue-mvn-assembly-plugin-730-jar-with-dependencies.jar");
    JarEntry entry = jar.getJarEntry("META-INF/services/java.sql.Driver");
    if (entry == null) {
        fail("the file 'META-INF/services/java.sql.Driver' should exist in jar-with-dependencies");
    }//from  w ww .ja  v a 2s. com

    // Content should be "org.postgresql.Driver"
    InputStream is = jar.getInputStream(entry);
    String content = IOUtils.toString(is, "UTF-8");
    System.out.println("JDBC Driver found : " + content.substring(0, content.indexOf("\n")));
    assertEquals("org.postgresql.Driver", content.substring(0, content.indexOf("\n")));

    // if test fails and content == "sun.jdbc.odbc.JdbcOdbcDriver",
    // it means it comes from jre/lib/resources.jar!/META-INF/services/java.sql.Driver (which is unwanted)

}

From source file:framework.JarResourceStore.java

public synchronized byte[] read(String pResourceName) {
    JarFile jar = null;//from  w  w w .  ja va 2s. co  m
    try {
        jar = new JarFile(URLDecoder.decode(filename, "utf-8"));
        JarEntry jarEntry = jar.getJarEntry(pResourceName);
        if (jarEntry != null) {

            InputStream inputStream = jar.getInputStream(jarEntry);
            try {
                return IOUtils.toByteArray(inputStream);
            } finally {
                inputStream.close();
            }
        }
    } catch (IOException e) {
        Loggers.RELOADER.error(e.getMessage(), e);
    } finally {
        if (jar != null) {
            try {
                jar.close();
            } catch (IOException e2) {
                Loggers.RELOADER.error(e2.getMessage(), e2);
            }
        }
    }
    return null;
}

From source file:com.elastica.helper.FileUtility.java

public static void extractJar(final String storeLocation, final Class<?> clz) throws IOException {
    File firefoxProfile = new File(storeLocation);
    String location = clz.getProtectionDomain().getCodeSource().getLocation().getFile();

    JarFile jar = new JarFile(location);
    System.out.println("Extracting jar file::: " + location);
    firefoxProfile.mkdir();/*from  w w  w .  j  a  v a 2  s  .c om*/

    Enumeration<?> jarFiles = jar.entries();
    while (jarFiles.hasMoreElements()) {
        ZipEntry entry = (ZipEntry) jarFiles.nextElement();
        String currentEntry = entry.getName();
        File destinationFile = new File(storeLocation, currentEntry);
        File destinationParent = destinationFile.getParentFile();

        // create the parent directory structure if required
        destinationParent.mkdirs();
        if (!entry.isDirectory()) {
            BufferedInputStream is = new BufferedInputStream(jar.getInputStream(entry));
            int currentByte;

            // buffer for writing file
            byte[] data = new byte[BUFFER];

            // write the current file to disk
            FileOutputStream fos = new FileOutputStream(destinationFile);
            BufferedOutputStream destination = new BufferedOutputStream(fos, BUFFER);

            // read and write till last byte
            while ((currentByte = is.read(data, 0, BUFFER)) != -1) {
                destination.write(data, 0, currentByte);
            }

            destination.flush();
            destination.close();
            is.close();
        }
    }

    FileUtils.deleteDirectory(new File(storeLocation + "\\META-INF"));
    if (OSUtility.isWindows()) {
        new File(storeLocation + "\\" + clz.getCanonicalName().replaceAll("\\.", "\\\\") + ".class").delete();
    } else {
        new File(storeLocation + "/" + clz.getCanonicalName().replaceAll("\\.", "/") + ".class").delete();
    }
}

From source file:com.reactive.hzdfs.dll.JarClassLoader.java

private static TreeSet<String> scanForPackages(String path) throws IOException {
    try (JarFile file = new JarFile(path)) {
        TreeSet<String> packages = new TreeSet<>(new Comparator<String>() {

            @Override/*  w  w  w .  j av  a2s  .  c  o m*/
            public int compare(String o1, String o2) {
                if (o2.length() > o1.length() && o2.contains(o1))
                    return -1;
                else if (o2.length() < o1.length() && o1.contains(o2))
                    return 1;
                else
                    return o1.compareTo(o2);
            }
        });
        for (Enumeration<JarEntry> entries = file.entries(); entries.hasMoreElements();) {
            JarEntry entry = entries.nextElement();
            String name = entry.getName();

            if (name.endsWith(".class")) {
                String fqcn = ClassUtils.convertResourcePathToClassName(name);
                fqcn = StringUtils.delete(fqcn, ".class");
                packages.add(ClassUtils.getPackageName(fqcn));
            }
        }

        return packages;
    }
}

From source file:com.canoo.webtest.util.WebtestEmbeddingUtil.java

/**
 * Copies WebTest resources (ie webtest.xml, tools/*, the XSLs, CSSs and pictures, ...) package in WebTest jar file
 * into the provide folder. Indeed different Ant tasks can't work with resources in a jar file.
 * @param targetFolder the folder in which resources should be copied to
 * @throws java.io.IOException if the resources can be accessed or copied
 *///w  ww .ja v a2s.  c om
static void copyWebTestResources(final File targetFolder) throws IOException {
    final String resourcesPrefix = "com/canoo/webtest/resources/";
    final URL webtestXmlUrl = WebtestEmbeddingUtil.class.getClassLoader()
            .getResource(resourcesPrefix + "webtest.xml");

    if (webtestXmlUrl == null) {
        throw new IllegalStateException("Can't find resource " + resourcesPrefix + "webtest.xml");
    } else if (webtestXmlUrl.toString().startsWith("jar:file")) {
        final String urlJarFileName = webtestXmlUrl.toString().replaceFirst("^jar:file:([^\\!]*).*$", "$1");
        final String jarFileName = URLDecoder.decode(urlJarFileName, Charset.defaultCharset().name());
        final JarFile jarFile = new JarFile(jarFileName);
        final String urlPrefix = StringUtils.removeEnd(webtestXmlUrl.toString(), "webtest.xml");

        for (final Enumeration<JarEntry> entries = jarFile.entries(); entries.hasMoreElements();) {
            final JarEntry jarEntry = entries.nextElement();
            if (jarEntry.getName().startsWith(resourcesPrefix)) {
                final String relativeName = StringUtils.removeStart(jarEntry.getName(), resourcesPrefix);
                final URL url = new URL(urlPrefix + relativeName);
                final File targetFile = new File(targetFolder, relativeName);
                FileUtils.forceMkdir(targetFile.getParentFile());
                FileUtils.copyURLToFile(url, targetFile);
            }
        }
    } else if (webtestXmlUrl.toString().startsWith("file:")) {
        // we're probably developing and/or have a custom version of the resources in classpath
        final File webtestXmlFile = FileUtils.toFile(webtestXmlUrl);
        final File resourceFolder = webtestXmlFile.getParentFile();

        FileUtils.copyDirectory(resourceFolder, targetFolder);
    } else {
        throw new IllegalStateException(
                "Resource " + resourcesPrefix + "webtest.xml is not in a jar file: " + webtestXmlUrl);
    }
}