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.dmulloy2.ultimatearena.api.ArenaLoader.java

public final ArenaDescription getArenaDescription(File file) throws InvalidArenaException {
    Validate.notNull(file, "file cannot be null!");

    try (Closer closer = new Closer()) {
        JarFile jar = closer.register(new JarFile(file));
        JarEntry entry = jar.getJarEntry("arena.yml");

        if (entry == null)
            throw new InvalidArenaException(new FileNotFoundException("Jar does not contain arena.yml"));

        InputStream stream = closer.register(jar.getInputStream(entry));
        Map<?, ?> map = (Map<?, ?>) yaml.load(stream);

        String name = (String) map.get("name");
        Validate.notNull(name, "Missing required key: name");
        Validate.isTrue(name.matches("^[A-Za-z0-9 _.-]+$"), "Name '" + name + "' contains invalid characters");

        String main = (String) map.get("main");
        Validate.notNull(main, "Missing required key: main");

        String version = (String) map.get("version");
        Validate.notNull(version, "Missing required key: version");

        String author = (String) map.get("author");
        if (author == null)
            author = "Unascribed";

        String stylized = (String) map.get("stylized");
        if (stylized == null)
            stylized = name;/*from  ww  w. j a v  a2 s  .c o m*/

        return new ArenaDescription(name, main, stylized, version, author);
    } catch (InvalidArenaException ex) {
        throw ex;
    } catch (Throwable ex) {
        throw new InvalidArenaException("Failed to read arena.yml from " + file.getName(), ex);
    }
}

From source file:com.l2jserver.service.game.scripting.impl.ecj.EclipseCompilerScriptClassLoader.java

/**
 * AddsLibrary jar// w ww.  jav  a  2  s . c o m
 * 
 * @param file
 *            jar file to add
 * @throws IOException
 *             if any I/O error occur
 */
@Override
public void addLibrary(File file) throws IOException {
    URL fileURL = file.toURI().toURL();
    addURL(fileURL);

    JarFile jarFile = new JarFile(file);

    Enumeration<JarEntry> entries = jarFile.entries();
    while (entries.hasMoreElements()) {
        JarEntry entry = entries.nextElement();

        String name = entry.getName();
        if (name.endsWith(".class")) {
            name = name.substring(0, name.length() - 6);
            name = name.replace('/', '.');
            libraryClasses.add(name);
        }
    }

    jarFile.close();
}

From source file:edu.stanford.muse.email.JarDocCache.java

private synchronized Set<String> getHeaders(String prefix) throws IOException {
    Set<String> headers = headersMap.get(prefix);
    if (headers != null)
        return headers;

    // check if the file exists first, if it doesn't return null
    String filename = baseDir + File.separator + prefix + ".headers";
    File f = new File(filename);
    Set<String> result = new LinkedHashSet<String>();
    if (f.exists()) {
        JarFile jarFile;//  w  w w.  j  ava  2  s . c  o  m
        try {
            jarFile = new JarFile(filename);
            result = readJarFileEntries(jarFile);
        } catch (Exception e) {
            // not really a jar file. delete the sucker
            log.warn("Bad jar file! " + filename + " size " + new File(filename).length() + " bytes");
            Util.print_exception(e, log);
            new File(filename).delete();
        }
    }

    headersMap.put(prefix, result);
    return result;
}

From source file:com.arcusys.liferay.vaadinplugin.util.ControlPanelPortletUtil.java

public static String getPortalVaadinJarVersion(String jarPath) throws IOException {
    JarFile jarFile = new JarFile(jarPath);
    try {// www .  ja va 2s.  c o  m
        String version = getManifestVaadinVersion(jarFile);
        if (version == null) {
            version = getPomVaadinVersion(jarFile);
        }

        return version;
    } catch (Exception ex) {
        return null;
    } finally {
        try {
            jarFile.close();
        } catch (IOException e) {
            log.warn(e);
        }
    }
}

From source file:info.dolezel.fatrat.plugins.helpers.NativeHelpers.java

private static Set<Class> findClasses(File directory, String packageName, Class annotation)
        throws ClassNotFoundException, IOException {
    Set<Class> classes = new HashSet<Class>();
    if (!directory.exists()) {

        String fullPath = directory.toString();
        String jarPath = fullPath.replaceFirst("[.]jar[!].*", ".jar").replaceFirst("file:", "");
        JarFile jarFile = new JarFile(jarPath);
        Enumeration<JarEntry> entries = jarFile.entries();
        while (entries.hasMoreElements()) {
            JarEntry entry = entries.nextElement();
            String entryName = entry.getName();
            if (entryName.endsWith(".class") && !entryName.contains("$")) {
                String className = entryName.replace('/', '.').replace('\\', '.').replace(".class", "");
                Class cls = loader.loadClass(className);

                if (annotation == null || cls.isAnnotationPresent(annotation))
                    classes.add(cls);/*from w  w  w .j a  v a  2s. com*/
            }
        }
    } else {
        File[] files = directory.listFiles();
        for (File file : files) {
            if (file.isDirectory()) {
                assert !file.getName().contains(".");
                classes.addAll(findClasses(file, packageName + "." + file.getName(), annotation));
            } else if (file.getName().endsWith(".class")) {
                Class cls = loader.loadClass(
                        packageName + '.' + file.getName().substring(0, file.getName().length() - 6));

                if (annotation == null || cls.isAnnotationPresent(annotation))
                    classes.add(cls);
            }
        }
    }
    return classes;
}

From source file:com.jayway.maven.plugins.android.standalonemojos.UnpackMojo.java

private File unpackClasses() throws MojoExecutionException {
    File outputDirectory = new File(targetDirectory, "android-classes");
    if (lazyLibraryUnpack && outputDirectory.exists()) {
        getLog().info("skip library unpacking due to lazyLibraryUnpack policy");
    } else {//from w  w w  .j a  va 2  s .  c  o m
        outputDirectory.mkdirs();

        for (Artifact artifact : getRelevantCompileArtifacts()) {

            if (artifact.getFile().isDirectory()) {
                try {
                    FileUtils.copyDirectory(artifact.getFile(), outputDirectory);
                } catch (IOException e) {
                    throw new MojoExecutionException(
                            "IOException while copying " + artifact.getFile().getAbsolutePath() + " into "
                                    + outputDirectory.getAbsolutePath(),
                            e);
                }
            } else {
                try {
                    JarHelper.unjar(new JarFile(artifact.getFile()), outputDirectory,
                            new JarHelper.UnjarListener() {
                                @Override
                                public boolean include(JarEntry jarEntry) {
                                    return isIncluded(jarEntry);
                                }
                            });
                } catch (IOException e) {
                    throw new MojoExecutionException(
                            "IOException while unjarring " + artifact.getFile().getAbsolutePath() + " into "
                                    + outputDirectory.getAbsolutePath(),
                            e);
                }
            }

        }
    }

    try {
        FileUtils.copyDirectory(projectOutputDirectory, outputDirectory);
    } catch (IOException e) {
        throw new MojoExecutionException("IOException while copying " + sourceDirectory.getAbsolutePath()
                + " into " + outputDirectory.getAbsolutePath(), e);
    }
    return outputDirectory;
}

From source file:org.apache.bcel.generic.JDKGenericDumpTestCase.java

private void testJar(final File file) throws Exception {
    System.out.println(file);//from   w  ww  .j a  v a  2s. c o m
    try (JarFile jar = new JarFile(file)) {
        final Enumeration<JarEntry> en = jar.entries();
        while (en.hasMoreElements()) {
            final JarEntry e = en.nextElement();
            final String name = e.getName();
            if (name.endsWith(".class")) {
                // System.out.println("- " + name);
                try (InputStream in = jar.getInputStream(e)) {
                    final ClassParser parser = new ClassParser(in, name);
                    final JavaClass jc = parser.parse();
                    for (final Method m : jc.getMethods()) {
                        compare(name, m);
                    }
                }
            }
        }
    }
}

From source file:org.compass.core.config.binding.AbstractInputStreamMappingBinding.java

public boolean addJar(File jar) throws ConfigurationException, MappingException {
    final JarFile jarFile;
    try {//from w w w .  j av  a 2 s  . c  o  m
        jarFile = new JarFile(jar);
    } catch (IOException ioe) {
        throw new ConfigurationException("Could not configure datastore from jar [" + jar.getName() + "]", ioe);
    }

    boolean addedAtLeastOne = false;
    Enumeration jarEntries = jarFile.entries();
    while (jarEntries.hasMoreElements()) {
        ZipEntry ze = (ZipEntry) jarEntries.nextElement();
        for (String suffix : getSuffixes()) {
            if (ze.getName().endsWith(suffix)) {
                try {
                    boolean retVal = internalAddInputStream(jarFile.getInputStream(ze), ze.getName(), true);
                    if (retVal) {
                        addedAtLeastOne = true;
                    }
                } catch (ConfigurationException me) {
                    throw me;
                } catch (Exception e) {
                    throw new ConfigurationException(
                            "Could not configure datastore from jar [" + jar.getAbsolutePath() + "]", e);
                }
            }
        }
    }
    return addedAtLeastOne;
}

From source file:org.apache.hadoop.util.TestClasspath.java

/**
 * Asserts that the specified file is a jar file with a manifest containing a
 * non-empty classpath attribute.//  ww w . java  2s  .  c o m
 *
 * @param file File to check
 * @throws IOException if there is an I/O error
 */
private static void assertJar(File file) throws IOException {
    JarFile jarFile = null;
    try {
        jarFile = new JarFile(file);
        Manifest manifest = jarFile.getManifest();
        assertNotNull(manifest);
        Attributes mainAttributes = manifest.getMainAttributes();
        assertNotNull(mainAttributes);
        assertTrue(mainAttributes.containsKey(Attributes.Name.CLASS_PATH));
        String classPathAttr = mainAttributes.getValue(Attributes.Name.CLASS_PATH);
        assertNotNull(classPathAttr);
        assertFalse(classPathAttr.isEmpty());
    } finally {
        // It's too bad JarFile doesn't implement Closeable.
        if (jarFile != null) {
            try {
                jarFile.close();
            } catch (IOException e) {
                LOG.warn("exception closing jarFile: " + jarFile, e);
            }
        }
    }
}

From source file:org.datavyu.util.NativeLoader.java

/**
 * Unpacks a native application to a temporary location so that it can be
 * utilized from within java code.//  ww  w  . ja va2 s.  co  m
 *
 * @param appJar The jar containing the native app that you want to unpack.
 * @return The path of the native app as unpacked to a temporary location.
 *
 * @throws Exception If unable to unpack the native app to a temporary
 * location.
 */
public static String unpackNativeApp(final String appJar) throws Exception {
    final String nativeLibraryPath;

    if (nativeLibFolder == null) {
        nativeLibraryPath = System.getProperty("java.io.tmpdir") + UUID.randomUUID().toString() + "nativelibs";
        nativeLibFolder = new File(nativeLibraryPath);

        if (!nativeLibFolder.exists()) {
            nativeLibFolder.mkdir();
        }
    }

    // Search the class path for the application jar.
    JarFile jar = null;

    // BugID: 26178921 -- We need to inspect the surefire test class path as
    // well as the regular class path property so that we can scan dependencies
    // during tests.
    String searchPath = System.getProperty("surefire.test.class.path") + File.pathSeparator
            + System.getProperty("java.class.path");

    for (String s : searchPath.split(File.pathSeparator)) {
        // Success! We found a matching jar.
        if (s.endsWith(appJar + ".jar") || s.endsWith(appJar)) {
            jar = new JarFile(s);
        }
    }

    // If we found a jar - it should contain the desired application.
    // decompress as needed.
    if (jar != null) {
        Enumeration<JarEntry> entries = jar.entries();

        while (entries.hasMoreElements()) {
            JarEntry inFile = entries.nextElement();
            File outFile = new File(nativeLibFolder, inFile.getName());

            // If the file from the jar is a directory, create it.
            if (inFile.isDirectory()) {
                outFile.mkdir();

                // The file from the jar is regular - decompress it.
            } else {
                InputStream in = jar.getInputStream(inFile);

                // Create a temporary output location for the library.
                FileOutputStream out = new FileOutputStream(outFile);
                BufferedOutputStream dest = new BufferedOutputStream(out, BUFFER);
                int count;
                byte[] data = new byte[BUFFER];

                while ((count = in.read(data, 0, BUFFER)) != -1) {
                    dest.write(data, 0, count);
                }

                dest.flush();
                dest.close();
                out.close();
                in.close();
            }

            loadedLibs.add(outFile);
        }

        // Unable to find jar file - abort decompression.
    } else {
        System.err.println("Unable to find jar file for unpacking: " + appJar + ". Java classpath is:");

        for (String s : System.getProperty("java.class.path").split(File.pathSeparator)) {
            System.err.println("    " + s);
        }

        throw new Exception("Unable to find '" + appJar + "' for unpacking.");
    }

    return nativeLibFolder.getAbsolutePath();
}