Example usage for java.util.jar JarFile close

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

Introduction

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

Prototype

public void close() throws IOException 

Source Link

Document

Closes the ZIP file.

Usage

From source file:com.smartitengineering.util.simple.reflection.DefaultClassScannerImpl.java

private void scanJar(File jarFile, String parentPath, ClassVisitor classVisitor) {
    final JarFile jar = getJarFile(jarFile);
    try {/* ww  w  .j a v  a2s.com*/
        final Enumeration<JarEntry> entries = jar.entries();
        while (entries.hasMoreElements()) {
            JarEntry e = entries.nextElement();
            if (!e.isDirectory() && e.getName().startsWith(parentPath) && e.getName().endsWith(".class")) {
                visitClassFile(jar, e, classVisitor);
            }
        }
    } catch (Exception e) {
    } finally {
        try {
            if (jar != null) {
                jar.close();
            }
        } catch (IOException ex) {
        }
    }
}

From source file:net.jselby.pc.bukkit.BukkitLoader.java

@SuppressWarnings("unchecked")
public void loadPlugin(File file)
        throws ZipException, IOException, InvalidPluginException, InvalidDescriptionException {
    if (file.getName().endsWith(".jar")) {
        JarFile jarFile = new JarFile(file);

        URL[] urls = { new URL("jar:file:" + file + "!/") };
        URLClassLoader cl = URLClassLoader.newInstance(urls);

        ZipEntry bukkit = jarFile.getEntry("plugin.yml");
        String bukkitClass = "";
        PluginDescriptionFile reader = null;
        if (bukkit != null) {
            reader = new PluginDescriptionFile(new InputStreamReader(jarFile.getInputStream(bukkit)));
            bukkitClass = reader.getMain();
            System.out.println("Loading plugin " + reader.getName() + "...");
        }/*from  w w  w.j  a va  2 s  .  com*/

        jarFile.close();

        try {
            //addToClasspath(file);
            JavaPluginLoader pluginLoader = new JavaPluginLoader(PoweredCube.getInstance().getBukkitServer());
            Plugin plugin = pluginLoader.loadPlugin(file);
            Class<JavaPlugin> pluginClass = (Class<JavaPlugin>) plugin.getClass().getSuperclass();
            for (Method method : pluginClass.getDeclaredMethods()) {
                if (method.getName().equalsIgnoreCase("init")
                        || method.getName().equalsIgnoreCase("initialize")) {
                    method.setAccessible(true);
                    method.invoke(plugin, null, PoweredCube.getInstance().getBukkitServer(), reader,
                            new File("plugins" + File.separator + reader.getName()), file, cl);
                }
            }

            // Load the plugin, using its default methods
            BukkitPluginManager mgr = (BukkitPluginManager) Bukkit.getPluginManager();
            mgr.registerPlugin((JavaPlugin) plugin);
            plugin.onLoad();
            plugin.onEnable();
        } catch (Exception e1) {
            e1.printStackTrace();
        } catch (Error e1) {
            e1.printStackTrace();
        }

        jarFile.close();
    }
}

From source file:net.aepik.alasca.core.ldap.Schema.java

/**
 * Retourne l'ensemble des syntaxes connues, qui sont
 * contenues dans le package 'ldap.syntax'.
 * @return String[] L'ensemble des noms de classes de syntaxes.
 *///from   w  w  w.  ja  va  2s . c  o  m
public static String[] getSyntaxes() {
    String[] result = null;
    try {
        String packageName = getSyntaxPackageName();
        URL url = Schema.class.getResource("/" + packageName.replace('.', '/'));
        if (url == null) {
            return null;
        }
        if (url.getProtocol().equals("jar")) {
            Vector<String> vectTmp = new Vector<String>();
            int index = url.getPath().indexOf('!');
            String path = URLDecoder.decode(url.getPath().substring(index + 1), "UTF-8");
            JarFile jarFile = new JarFile(URLDecoder.decode(url.getPath().substring(5, index), "UTF-8"));
            if (path.charAt(0) == '/') {
                path = path.substring(1);
            }
            Enumeration<JarEntry> jarFiles = jarFile.entries();
            while (jarFiles.hasMoreElements()) {
                JarEntry tmp = jarFiles.nextElement();
                //
                // Pour chaque fichier dans le jar, on regarde si c'est un
                // fichier de classe Java.
                //
                if (!tmp.isDirectory() && tmp.getName().substring(tmp.getName().length() - 6).equals(".class")
                        && tmp.getName().startsWith(path)) {
                    int i = tmp.getName().lastIndexOf('/');
                    String classname = tmp.getName().substring(i + 1, tmp.getName().length() - 6);
                    vectTmp.add(classname);
                }
            }
            jarFile.close();
            result = new String[vectTmp.size()];
            for (int i = 0; i < vectTmp.size(); i++) {
                result[i] = vectTmp.elementAt(i);
            }
        } else if (url.getProtocol().equals("file")) {
            //
            // On cr le fichier associ pour parcourir son contenu.
            // En l'occurence, c'est un dossier.
            //
            File[] files = (new File(url.toURI())).listFiles();
            //
            // On liste tous les fichiers qui sont dedans.
            // On les stocke dans un vecteur ...
            //
            Vector<File> vectTmp = new Vector<File>();
            for (File f : files) {
                if (!f.isDirectory()) {
                    vectTmp.add(f);
                }
            }
            //
            // ... pour ensuite les mettres dans le tableau de resultat.
            //
            result = new String[vectTmp.size()];
            for (int i = 0; i < vectTmp.size(); i++) {
                String name = vectTmp.elementAt(i).getName();
                int a = name.indexOf('.');
                name = name.substring(0, a);
                result[i] = name;
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    if (result != null) {
        Arrays.sort(result);
    }
    return result;
}

From source file:org.apache.maven.plugins.shade.resource.ServiceResourceTransformerTest.java

@Test
public void relocatedClasses() throws Exception {
    SimpleRelocator relocator = new SimpleRelocator("org.foo", "borg.foo", null,
            Arrays.asList("org.foo.exclude.*"));
    List<Relocator> relocators = Lists.<Relocator>newArrayList(relocator);

    String content = "org.foo.Service\norg.foo.exclude.OtherService\n";
    byte[] contentBytes = content.getBytes("UTF-8");
    InputStream contentStream = new ByteArrayInputStream(contentBytes);
    String contentResource = "META-INF/services/org.foo.something.another";
    String contentResourceShaded = "META-INF/services/borg.foo.something.another";

    ServicesResourceTransformer xformer = new ServicesResourceTransformer();
    xformer.processResource(contentResource, contentStream, relocators);
    contentStream.close();/*from   w  w  w.j a va2  s . c  o m*/

    File tempJar = File.createTempFile("shade.", ".jar");
    tempJar.deleteOnExit();
    FileOutputStream fos = new FileOutputStream(tempJar);
    JarOutputStream jos = new JarOutputStream(fos);
    try {
        xformer.modifyOutputStream(jos, false);
        jos.close();
        jos = null;
        JarFile jarFile = new JarFile(tempJar);
        JarEntry jarEntry = jarFile.getJarEntry(contentResourceShaded);
        assertNotNull(jarEntry);
        InputStream entryStream = jarFile.getInputStream(jarEntry);
        try {
            String xformedContent = IOUtils.toString(entryStream, "utf-8");
            assertEquals("borg.foo.Service" + System.getProperty("line.separator")
                    + "org.foo.exclude.OtherService" + System.getProperty("line.separator"), xformedContent);
        } finally {
            IOUtils.closeQuietly(entryStream);
            jarFile.close();
        }
    } finally {
        if (jos != null) {
            IOUtils.closeQuietly(jos);
        }
        tempJar.delete();
    }
}

From source file:org.springframework.boot.loader.tools.RepackagerTests.java

@Test
public void customLayoutFactoryWithLayout() throws Exception {
    this.testJarFile.addClass("a/b/C.class", ClassWithMainMethod.class);
    File source = this.testJarFile.getFile();
    Repackager repackager = new Repackager(source, new TestLayoutFactory());
    repackager.setLayout(new Layouts.Jar());
    repackager.repackage(NO_LIBRARIES);//from  www .ja  va  2  s.co  m
    JarFile jarFile = new JarFile(source);
    assertThat(jarFile.getEntry("test")).isNull();
    jarFile.close();
}

From source file:org.springframework.boot.loader.tools.RepackagerTests.java

@Test
public void customLayoutFactoryWithoutLayout() throws Exception {
    this.testJarFile.addClass("a/b/C.class", ClassWithMainMethod.class);
    File source = this.testJarFile.getFile();
    Repackager repackager = new Repackager(source, new TestLayoutFactory());
    repackager.repackage(NO_LIBRARIES);/*from   w  w  w .  ja v a2 s .  co m*/
    JarFile jarFile = new JarFile(source);
    assertThat(jarFile.getEntry("test")).isNotNull();
    jarFile.close();
}

From source file:com.xiovr.unibot.plugin.impl.PluginLoaderImpl.java

private Properties getPluginProps(File file) throws IOException {
    Properties result = null;//  w w  w  .j  a  v  a  2 s  . c o m
    JarFile jar = new JarFile(file);
    Enumeration<JarEntry> entries = jar.entries();

    while (entries.hasMoreElements()) {
        JarEntry entry = entries.nextElement();
        if (entry.getName().equals(PROPERTY_FILE_NAME)) {
            // That's it! Load props
            InputStream is = null;
            try {
                is = jar.getInputStream(entry);
                result = new Properties();
                result.load(is);
            } finally {
                if (is != null)
                    is.close();
            }
        }
    }
    jar.close();
    return result;
}

From source file:de.metanome.backend.algorithm_loading.AlgorithmFinder.java

/**
 * Finds out which subclass of Algorithm is implemented by the source code in the
 * algorithmJarFile./*  www .  j  av a  2s  .c  o  m*/
 *
 * @param algorithmJarFile the algorithm's jar file
 * @return the interfaces of the algorithm implementation in algorithmJarFile
 * @throws java.io.IOException if the algorithm jar file could not be opened
 * @throws java.lang.ClassNotFoundException if the algorithm contains a not supported interface
 */
public Set<Class<?>> getAlgorithmInterfaces(File algorithmJarFile) throws IOException, ClassNotFoundException {
    JarFile jar = new JarFile(algorithmJarFile);

    Manifest man = jar.getManifest();
    Attributes attr = man.getMainAttributes();
    String className = attr.getValue(bootstrapClassTagName);

    URL[] url = { algorithmJarFile.toURI().toURL() };
    ClassLoader loader = new URLClassLoader(url, Algorithm.class.getClassLoader());

    Class<?> algorithmClass;
    try {
        algorithmClass = Class.forName(className, false, loader);
    } catch (ClassNotFoundException e) {
        System.out.println("Could not find class " + className);
        return new HashSet<>();
    } finally {
        jar.close();
    }

    return new HashSet<>(ClassUtils.getAllInterfaces(algorithmClass));
}

From source file:com.eucalyptus.upgrade.TestHarness.java

@SuppressWarnings("unchecked")
private static Multimap<Class, Method> getTestMethods() throws Exception {
    final Multimap<Class, Method> testMethods = ArrayListMultimap.create();
    List<Class> classList = Lists.newArrayList();
    for (File f : new File(System.getProperty("euca.home") + "/usr/share/eucalyptus").listFiles()) {
        if (f.getName().startsWith("eucalyptus") && f.getName().endsWith(".jar")
                && !f.getName().matches(".*-ext-.*")) {
            try {
                JarFile jar = new JarFile(f);
                Enumeration<JarEntry> jarList = jar.entries();
                for (JarEntry j : Collections.list(jar.entries())) {
                    if (j.getName().matches(".*\\.class.{0,1}")) {
                        String classGuess = j.getName().replaceAll("/", ".").replaceAll("\\.class.{0,1}", "");
                        try {
                            Class candidate = ClassLoader.getSystemClassLoader().loadClass(classGuess);
                            for (final Method m : candidate.getDeclaredMethods()) {
                                if (Iterables.any(testAnnotations,
                                        new Predicate<Class<? extends Annotation>>() {
                                            public boolean apply(Class<? extends Annotation> arg0) {
                                                return m.getAnnotation(arg0) != null;
                                            }
                                        })) {
                                    System.out.println("Added test class: " + candidate.getCanonicalName());
                                    testMethods.put(candidate, m);
                                }/*w w  w. j  av a2  s . c om*/
                            }
                        } catch (ClassNotFoundException e) {
                        }
                    }
                }
                jar.close();
            } catch (Exception e) {
                System.out.println(e.getMessage());
                continue;
            }
        }
    }
    return testMethods;
}

From source file:com.taobao.android.builder.tools.classinject.CodeInjectByJavassist.java

/**
 * jar?//from  w  ww.  jav a 2s .com
 *
 * @param inJar
 * @param outJar
 * @throws IOException
 * @throws NotFoundException
 * @throws CannotCompileException
 */
public static List<String> inject(ClassPool pool, File inJar, File outJar, InjectParam injectParam)
        throws Exception {
    List<String> errorFiles = new ArrayList<String>();
    JarFile jarFile = newJarFile(inJar);

    outJar.getParentFile().mkdirs();
    FileOutputStream fileOutputStream = new FileOutputStream(outJar);
    JarOutputStream jos = new JarOutputStream(new BufferedOutputStream(fileOutputStream));
    Enumeration<JarEntry> jarFileEntries = jarFile.entries();
    JarEntry jarEntry = null;
    while (jarFileEntries.hasMoreElements()) {
        jarEntry = jarFileEntries.nextElement();
        String name = jarEntry.getName();
        String className = StringUtils.replace(name, File.separator, "/");
        className = StringUtils.replace(className, "/", ".");
        className = StringUtils.substring(className, 0, className.length() - 6);
        if (!StringUtils.endsWithIgnoreCase(name, ".class")) {
            InputStream inputStream = jarFile.getInputStream(jarEntry);
            copyStreamToJar(inputStream, jos, name, jarEntry.getTime(), jarEntry);
            IOUtils.closeQuietly(inputStream);
        } else {
            byte[] codes;

            codes = inject(pool, className, injectParam);
            InputStream classInstream = new ByteArrayInputStream(codes);
            copyStreamToJar(classInstream, jos, name, jarEntry.getTime(), jarEntry);

        }
    }
    jarFile.close();
    IOUtils.closeQuietly(jos);
    return errorFiles;
}