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.orange.mmp.dao.flf.ModuleDaoFlfImpl.java

public Module[] find(Module module) throws MMPDaoException {
    if (module == null) {
        throw new MMPDaoException("missing or bad data access object");
    }//from w  ww  . ja  v  a  2s.  c  om

    FilenameFilter jarFilter = new SuffixFileFilter(".jar");
    File widgetsFiles[] = new File(this.path).listFiles(jarFilter);
    if (widgetsFiles == null)
        return new Module[0];
    ArrayList<Module> list = new ArrayList<Module>();

    JarFile jarFile = null;
    try {
        for (File found : widgetsFiles) {
            jarFile = new JarFile(found);
            Manifest manifest = jarFile.getManifest();
            boolean match = (module.getId() == null && module.getLocation() == null
                    && module.getVersion() == null && module.getName() == null && module.getCategory() == null);
            if (!match) {
                boolean goOnchecking = true;
                if (module.getLocation() != null && goOnchecking) {
                    match = found.toURI().toString().equals(module.getLocation().toString());
                    goOnchecking = false;
                }
                if (module.getId() != null) {
                    match = (manifest.getMainAttributes().getValue(MODULE_ID_HEADER) != null
                            && manifest.getMainAttributes().getValue(MODULE_ID_HEADER).equals(module.getId()));
                    goOnchecking = false;
                }
                if (module.getVersion() != null && goOnchecking) {
                    match = (manifest.getMainAttributes().getValue(MODULE_VERSION_HEADER) != null && manifest
                            .getMainAttributes().getValue(MODULE_VERSION_HEADER).equals(module.getVersion()));
                    goOnchecking = match;
                }
                if (module.getName() != null && goOnchecking) {
                    match = (manifest.getMainAttributes().getValue(MODULE_NAME_HEADER) != null && manifest
                            .getMainAttributes().getValue(MODULE_NAME_HEADER).equals(module.getName()));
                    goOnchecking = match;
                }
                if (module.getCategory() != null && goOnchecking) {
                    match = (manifest.getMainAttributes().getValue(MODULE_CATEGORY_HEADER) != null && manifest
                            .getMainAttributes().getValue(MODULE_CATEGORY_HEADER).equals(module.getCategory()));
                    goOnchecking = match;
                }
            }

            if (match) {
                Module foundModule = new Module();
                foundModule.setId(manifest.getMainAttributes().getValue(MODULE_ID_HEADER));
                foundModule.setName(manifest.getMainAttributes().getValue(MODULE_NAME_HEADER));
                foundModule
                        .setVersion(new Version(manifest.getMainAttributes().getValue(MODULE_VERSION_HEADER)));
                foundModule.setCategory(manifest.getMainAttributes().getValue(MODULE_CATEGORY_HEADER));
                foundModule.setLastModified(found.lastModified());
                foundModule.setLocation(found.toURI());
                list.add(foundModule);
            }
            jarFile.close();
        }
    } catch (IOException ioe) {
        throw new MMPDaoException("failed to load module");
    } finally {
        try {
            if (jarFile != null)
                jarFile.close();
        } catch (IOException ioe) {
            //Nop just log
        }
    }

    Module[] modulesList = new Module[list.size()];
    return list.toArray(modulesList);
}

From source file:org.apache.sling.maven.slingstart.PreparePackageMojoTest.java

@Test
public void testSubsystemBaseGeneration() throws Exception {
    // Provide the system with some artifacts that are known to be in the local .m2 repo
    // These are explicitly included in the test section of the pom.xml
    PreparePackageMojo ppm = getMojoUnderTest("org.apache.sling/org.apache.sling.commons.classloader/1.3.2",
            "org.apache.sling/org.apache.sling.commons.classloader/1.3.2/app",
            "org.apache.sling/org.apache.sling.commons.contentdetection/1.0.2",
            "org.apache.sling/org.apache.sling.commons.json/2.0.12",
            "org.apache.sling/org.apache.sling.commons.mime/2.1.8",
            "org.apache.sling/org.apache.sling.commons.osgi/2.3.0",
            "org.apache.sling/org.apache.sling.commons.threads/3.2.0");

    try {//w ww  . j a v a  2 s . c o  m
        // The launchpad feature is a prerequisite for the model
        String modelTxt = "[feature name=:launchpad]\n" + "[artifacts]\n"
                + "  org.apache.sling/org.apache.sling.commons.classloader/1.3.2\n" + ""
                + "[feature name=test1 type=osgi.subsystem.composite]\n" + ""
                + "[:subsystem-manifest startLevel=123]\n"
                + "  Subsystem-Description: Extra subsystem headers can go here including very long ones that would span multiple lines in a manifest\n"
                + "  Subsystem-Copyright: (c) 2015 yeah!\n" + "" + "[artifacts]\n"
                + "  org.apache.sling/org.apache.sling.commons.osgi/2.3.0\n" + ""
                + "[artifacts startLevel=10]\n" + "  org.apache.sling/org.apache.sling.commons.json/2.0.12\n"
                + "  org.apache.sling/org.apache.sling.commons.mime/2.1.8\n" + ""
                + "[artifacts startLevel=20 runModes=foo,bar,:blah]\n"
                + "  org.apache.sling/org.apache.sling.commons.threads/3.2.0\n" + ""
                + "[artifacts startLevel=100 runModes=bar]\n"
                + "  org.apache.sling/org.apache.sling.commons.contentdetection/1.0.2\n";
        Model model = ModelReader.read(new StringReader(modelTxt), null);
        ppm.execute(model);

        File generatedFile = new File(ppm.getTmpDir() + "/test1.subsystem-base");
        try (JarFile jf = new JarFile(generatedFile)) {
            // Test META-INF/MANIFEST.MF
            Manifest mf = jf.getManifest();
            Attributes attrs = mf.getMainAttributes();
            String expected = "Potential_Bundles/0/org.apache.sling.commons.osgi-2.3.0.jar|"
                    + "Potential_Bundles/10/org.apache.sling.commons.json-2.0.12.jar|"
                    + "Potential_Bundles/10/org.apache.sling.commons.mime-2.1.8.jar";
            assertEquals(expected, attrs.getValue("_all_"));
            assertEquals("Potential_Bundles/20/org.apache.sling.commons.threads-3.2.0.jar",
                    attrs.getValue("foo"));
            assertEquals(
                    "Potential_Bundles/20/org.apache.sling.commons.threads-3.2.0.jar|"
                            + "Potential_Bundles/100/org.apache.sling.commons.contentdetection-1.0.2.jar",
                    attrs.getValue("bar"));

            // Test SUBSYSTEM-MANIFEST-BASE.MF
            ZipEntry smbZE = jf.getEntry("SUBSYSTEM-MANIFEST-BASE.MF");
            try (InputStream smbIS = jf.getInputStream(smbZE)) {
                Manifest smbMF = new Manifest(smbIS);
                Attributes smbAttrs = smbMF.getMainAttributes();
                assertEquals("test1", smbAttrs.getValue("Subsystem-SymbolicName"));
                assertEquals("osgi.subsystem.composite", smbAttrs.getValue("Subsystem-Type"));
                assertEquals("(c) 2015 yeah!", smbAttrs.getValue("Subsystem-Copyright"));
                assertEquals(
                        "Extra subsystem headers can go here including very long ones "
                                + "that would span multiple lines in a manifest",
                        smbAttrs.getValue("Subsystem-Description"));
            }

            // Test embedded bundles
            File mrr = getMavenRepoRoot();
            File soj = getMavenArtifactFile(mrr, "org.apache.sling", "org.apache.sling.commons.osgi", "2.3.0");
            ZipEntry sojZE = jf.getEntry("Potential_Bundles/0/org.apache.sling.commons.osgi-2.3.0.jar");
            try (InputStream is = jf.getInputStream(sojZE)) {
                assertArtifactsEqual(soj, is);
            }

            File sjj = getMavenArtifactFile(mrr, "org.apache.sling", "org.apache.sling.commons.json", "2.0.12");
            ZipEntry sjZE = jf.getEntry("Potential_Bundles/10/org.apache.sling.commons.json-2.0.12.jar");
            try (InputStream is = jf.getInputStream(sjZE)) {
                assertArtifactsEqual(sjj, is);
            }

            File smj = getMavenArtifactFile(mrr, "org.apache.sling", "org.apache.sling.commons.mime", "2.1.8");
            ZipEntry smjZE = jf.getEntry("Potential_Bundles/10/org.apache.sling.commons.mime-2.1.8.jar");
            try (InputStream is = jf.getInputStream(smjZE)) {
                assertArtifactsEqual(smj, is);
            }

            File stj = getMavenArtifactFile(mrr, "org.apache.sling", "org.apache.sling.commons.threads",
                    "3.2.0");
            ZipEntry stjZE = jf.getEntry("Potential_Bundles/20/org.apache.sling.commons.threads-3.2.0.jar");
            try (InputStream is = jf.getInputStream(stjZE)) {
                assertArtifactsEqual(stj, is);
            }

            File ctj = getMavenArtifactFile(mrr, "org.apache.sling",
                    "org.apache.sling.commons.contentdetection", "1.0.2");
            ZipEntry ctjZE = jf
                    .getEntry("Potential_Bundles/100/org.apache.sling.commons.contentdetection-1.0.2.jar");
            try (InputStream is = jf.getInputStream(ctjZE)) {
                assertArtifactsEqual(ctj, is);
            }
        }
    } finally {
        FileUtils.deleteDirectory(new File(ppm.project.getBuild().getDirectory()));
    }
}

From source file:com.jayway.maven.plugins.android.phase04processclasses.DexMojo.java

private File unpackClasses(File inputFile) throws MojoExecutionException {
    File outputDirectory = new File(project.getBuild().getDirectory(), "android-classes");
    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);//from  w  w w.  j  av  a2  s .c o m
            }
        } else {
            try {
                unjar(new JarFile(artifact.getFile()), outputDirectory);
            } catch (IOException e) {
                throw new MojoExecutionException("IOException while unjarring "
                        + artifact.getFile().getAbsolutePath() + " into " + outputDirectory.getAbsolutePath(),
                        e);
            }
        }

    }

    try {
        unjar(new JarFile(inputFile), outputDirectory);
    } catch (IOException e) {
        throw new MojoExecutionException("IOException while unjarring " + inputFile.getAbsolutePath() + " into "
                + outputDirectory.getAbsolutePath(), e);
    }
    return outputDirectory;
}

From source file:org.ow2.proactive_grid_cloud_portal.scheduler.server.UploadServlet.java

private boolean isJarFile(File job) {
    boolean isJar = false;
    try {//from w  w w. j a  v a 2s  . c  om
        new JarFile(job);
        isJar = true;
    } catch (IOException e) {
        // not a jar;
    }
    return isJar;
}

From source file:org.eclipse.jubula.autagent.commands.AbstractStartJavaAut.java

/**
 * @param attributeName the attribute name in the manifest
 * @param jarFile the path and name of the jar file to examine
 * @return the String value of the specified attribute name, or null if
 *         not found./*from www.ja  v a  2s  . c  om*/
 */
protected String getAttributeFromManifest(String attributeName, String jarFile) {

    if (jarFile == null || jarFile.length() < 1) {
        return null;
    }
    String attribute = null;
    try (JarFile jar = new JarFile(jarFile)) {
        Manifest manifest = jar.getManifest();
        if (manifest != null) {
            attribute = manifest.getMainAttributes().getValue(attributeName);
        }
    } catch (FileNotFoundException e) {
        LOG.error("File not found: " + jarFile, e); //$NON-NLS-1$
    } catch (IOException e) {
        LOG.error("Error reading jar file: " + jarFile, e); //$NON-NLS-1$
    }
    return attribute;
}

From source file:appeng.recipes.loader.RecipeResourceCopier.java

/**
 * List directory contents for a resource folder. Not recursive. This is basically a brute-force implementation. Works for regular files and also JARs.
 *
 * @param clazz Any java class that lives in the same place as the resources you want.
 * @param path Should end with "/", but not start with one.
 *
 * @return Just the name of each member item, not the full paths.
 *
 * @throws URISyntaxException            if it is a file path and the URL can not be converted to URI
 * @throws IOException                   if jar path can not be decoded
 * @throws UnsupportedOperationException if it is neither in jar nor in file path
 *///from ww  w  . j  ava 2s . co  m
@Nonnull
private String[] getResourceListing(@Nonnull final Class<?> clazz, @Nonnull final String path)
        throws URISyntaxException, IOException {
    assert clazz != null;
    assert path != null;

    final ClassLoader classLoader = clazz.getClassLoader();
    if (classLoader == null) {
        throw new IllegalStateException(
                "ClassLoader was not found. It was probably loaded at a inappropriate time");
    }

    URL dirURL = classLoader.getResource(path);
    if (dirURL != null) {
        final String protocol = dirURL.getProtocol();
        if (protocol.equals(FILE_PROTOCOL)) {
            // A file path: easy enough

            final URI uriOfURL = dirURL.toURI();
            final File fileOfURI = new File(uriOfURL);
            final String[] filesAndDirectoriesOfURI = fileOfURI.list();

            if (filesAndDirectoriesOfURI == null) {
                throw new IllegalStateException(
                        "Files and Directories were illegal. Either an abstract pathname does not denote a directory, or an I/O error occured.");
            } else {
                return filesAndDirectoriesOfURI;
            }
        }
    }

    if (dirURL == null) {
        /*
         * In case of a jar file, we can't actually find a directory.
         * Have to assume the same jar as clazz.
         */
        final String className = clazz.getName();
        final Matcher matcher = DOT_COMPILE_PATTERN.matcher(className);
        final String me = matcher.replaceAll("/") + CLASS_EXTENSION;
        dirURL = classLoader.getResource(me);
    }

    if (dirURL != null) {
        final String protocol = dirURL.getProtocol();
        if (protocol.equals(JAR_PROTOCOL)) {
            /* A JAR path */
            final String dirPath = dirURL.getPath();
            final String jarPath = dirPath.substring(5, dirPath.indexOf('!')); // strip out only
            // the JAR file
            final JarFile jar = new JarFile(URLDecoder.decode(jarPath, UTF_8_ENCODING));
            try {
                final Enumeration<JarEntry> entries = jar.entries(); // gives ALL entries in jar
                final Collection<String> result = new HashSet<String>(INITIAL_RESOURCE_CAPACITY); // avoid duplicates

                // in case it is a
                // subdirectory
                while (entries.hasMoreElements()) {
                    final JarEntry entry = entries.nextElement();
                    final String entryFullName = entry.getName();
                    if (entryFullName.startsWith(path)) { // filter according to the path
                        String entryName = entryFullName.substring(path.length());
                        final int checkSubDir = entryName.indexOf('/');
                        if (checkSubDir >= 0) {
                            // if it is a subdirectory, we just return the directory name
                            entryName = entryName.substring(0, checkSubDir);
                        }
                        result.add(entryName);
                    }
                }

                return result.toArray(new String[result.size()]);
            } finally {
                jar.close();
            }
        }
    }

    throw new UnsupportedOperationException("Cannot list files for URL " + dirURL);
}

From source file:io.cloudslang.maven.compiler.CloudSlangMavenCompiler.java

private static Map<String, byte[]> getSourceFilesForDependencies(String dependency) throws IOException {
    Path path = Paths.get(dependency);
    if (!Files.exists(path) || !path.toString().toLowerCase().endsWith(".jar")) {
        return Collections.emptyMap();
    }/* w  ww. ja  va  2  s . c o  m*/

    Map<String, byte[]> sources = new HashMap<>();

    try (JarFile jar = new JarFile(dependency)) {
        Enumeration enumEntries = jar.entries();
        while (enumEntries.hasMoreElements()) {
            JarEntry file = (JarEntry) enumEntries.nextElement();
            if ((file == null) || (file.isDirectory()) || (!file.getName().endsWith(".sl.yaml")
                    && !file.getName().endsWith(".sl") && !file.getName().endsWith(".sl.yml"))) {
                continue;
            }

            byte[] bytes;
            try (InputStream is = jar.getInputStream(file)) {
                bytes = IOUtils.toByteArray(is);
                sources.put(file.getName(), bytes);
            }
        }
    }

    return sources;
}

From source file:cc.pp.analyzer.paoding.knife.PaodingMaker.java

@SuppressWarnings("resource")
private static long getFileLastModified(File file) throws IOException {
    String path = file.getPath();
    int jarIndex = path.indexOf(".jar!");
    if (jarIndex == -1) {
        return file.lastModified();
    } else {/*from   w w  w . j a va 2  s  .c  o  m*/
        path = path.replaceAll("%20", " ").replaceAll("\\\\", "/");
        jarIndex = path.indexOf(".jar!");
        int protocalIndex = path.indexOf(":");
        String jarPath = path.substring(protocalIndex + ":".length(), jarIndex + ".jar".length());
        File jarPathFile = new File(jarPath);
        JarFile jarFile;
        try {
            jarFile = new JarFile(jarPathFile);
            String entryPath = path.substring(jarIndex + ".jar!/".length());
            JarEntry entry = jarFile.getJarEntry(entryPath);
            return entry.getTime();
        } catch (IOException e) {
            System.err.println("error in handler path=" + path);
            System.err.println("error in handler jarPath=" + jarPath);
            throw e;
        }
    }
}

From source file:net.paoding.analysis.knife.PaodingMaker.java

private static long getFileLastModified(File file) throws IOException {
    String path = file.getPath();
    int jarIndex = path.indexOf(".jar!");
    if (jarIndex == -1) {
        return file.lastModified();
    } else {//from w  ww  .j av a  2s.  co  m
        path = path.replaceAll("%20", " ").replaceAll("\\\\", "/");
        jarIndex = path.indexOf(".jar!");
        int protocalIndex = path.indexOf(":");
        String jarPath = path.substring(protocalIndex + ":".length(), jarIndex + ".jar".length());
        File jarPathFile = new File(jarPath);
        JarFile jarFile;
        try {
            jarFile = new JarFile(jarPathFile);
            String entryPath = path.substring(jarIndex + ".jar!/".length());
            JarEntry entry = jarFile.getJarEntry(entryPath);
            return entry.getTime();
        } catch (IOException e) {
            System.err.println("error in handler path=" + path);
            System.err.println("error in handler jarPath=" + jarPath);
            throw e;
        }
    }
}

From source file:org.colombbus.tangara.FileUtils.java

public static int extractJar(File jar, File directory) {
    JarEntry entry = null;// ww w  .  j a va  2  s.com
    File currentFile = null;
    BufferedInputStream input = null;
    JarFile jarFile = null;
    int filesCount = 0;
    try {
        jarFile = new JarFile(jar);
        Enumeration<JarEntry> entries = jarFile.entries();

        while (entries.hasMoreElements()) {
            entry = entries.nextElement();
            currentFile = new File(directory, entry.getName());
            if (entry.isDirectory()) {
                currentFile.mkdir();
            } else {
                currentFile.createNewFile();
                input = new BufferedInputStream(jarFile.getInputStream(entry));
                copyFile(input, currentFile);
                input.close();
                filesCount++;
            }
        }
    } catch (IOException e) {
        LOG.error("Error extracting JAR file " + jar.getAbsolutePath(), e);
    } finally {
        try {
            if (input != null) {
                input.close();
            }
            if (jarFile != null) {
                jarFile.close();
            }
        } catch (IOException e) {
        }
    }
    return filesCount;
}