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:org.apache.archiva.rest.services.DefaultBrowseService.java

protected List<ArtifactContentEntry> readFileEntries(File file, String filterPath, String repoId)
        throws IOException {
    Map<String, ArtifactContentEntry> artifactContentEntryMap = new HashMap<>();
    int filterDepth = StringUtils.countMatches(filterPath, "/");
    /*if ( filterDepth == 0 )
    {//  ww  w.java2s .  c  om
    filterDepth = 1;
    }*/
    JarFile jarFile = new JarFile(file);
    try {
        Enumeration<JarEntry> jarEntryEnumeration = jarFile.entries();
        while (jarEntryEnumeration.hasMoreElements()) {
            JarEntry currentEntry = jarEntryEnumeration.nextElement();
            String cleanedEntryName = StringUtils.endsWith(currentEntry.getName(), "/") ? //
                    StringUtils.substringBeforeLast(currentEntry.getName(), "/") : currentEntry.getName();
            String entryRootPath = getRootPath(cleanedEntryName);
            int depth = StringUtils.countMatches(cleanedEntryName, "/");
            if (StringUtils.isEmpty(filterPath) //
                    && !artifactContentEntryMap.containsKey(entryRootPath) //
                    && depth == filterDepth) {

                artifactContentEntryMap.put(entryRootPath,
                        new ArtifactContentEntry(entryRootPath, !currentEntry.isDirectory(), depth, repoId));
            } else {
                if (StringUtils.startsWith(cleanedEntryName, filterPath) //
                        && (depth == filterDepth || (!currentEntry.isDirectory() && depth == filterDepth))) {
                    artifactContentEntryMap.put(cleanedEntryName, new ArtifactContentEntry(cleanedEntryName,
                            !currentEntry.isDirectory(), depth, repoId));
                }
            }
        }

        if (StringUtils.isNotEmpty(filterPath)) {
            Map<String, ArtifactContentEntry> filteredArtifactContentEntryMap = new HashMap<>();

            for (Map.Entry<String, ArtifactContentEntry> entry : artifactContentEntryMap.entrySet()) {
                filteredArtifactContentEntryMap.put(entry.getKey(), entry.getValue());
            }

            List<ArtifactContentEntry> sorted = getSmallerDepthEntries(filteredArtifactContentEntryMap);
            if (sorted == null) {
                return Collections.emptyList();
            }
            Collections.sort(sorted, ArtifactContentEntryComparator.INSTANCE);
            return sorted;
        }
    } finally {
        if (jarFile != null) {
            jarFile.close();
        }
    }
    List<ArtifactContentEntry> sorted = new ArrayList<>(artifactContentEntryMap.values());
    Collections.sort(sorted, ArtifactContentEntryComparator.INSTANCE);
    return sorted;
}

From source file:org.grails.io.support.PathMatchingResourcePatternResolver.java

/**
 * Find all resources in jar files that match the given location pattern
 * via the Ant-style PathMatcher.//  w w w  .  j  a v a 2  s  .  c o m
 * @param rootDirResource the root directory as Resource
 * @param subPattern the sub pattern to match (below the root directory)
 * @return the Set of matching Resource instances
 * @throws IOException in case of I/O errors
 * @see java.net.JarURLConnection
 */
protected Set<Resource> doFindPathMatchingJarResources(Resource rootDirResource, String subPattern)
        throws IOException {

    URLConnection con = rootDirResource.getURL().openConnection();
    JarFile jarFile;
    String jarFileUrl;
    String rootEntryPath;
    boolean newJarFile = false;

    if (con instanceof JarURLConnection) {
        // Should usually be the case for traditional JAR files.
        JarURLConnection jarCon = (JarURLConnection) con;
        GrailsResourceUtils.useCachesIfNecessary(jarCon);
        jarFile = jarCon.getJarFile();
        jarFileUrl = jarCon.getJarFileURL().toExternalForm();
        JarEntry jarEntry = jarCon.getJarEntry();
        rootEntryPath = (jarEntry != null ? jarEntry.getName() : "");
    } else {
        // No JarURLConnection -> need to resort to URL file parsing.
        // We'll assume URLs of the format "jar:path!/entry", with the protocol
        // being arbitrary as long as following the entry format.
        // We'll also handle paths with and without leading "file:" prefix.
        String urlFile = rootDirResource.getURL().getFile();
        int separatorIndex = urlFile.indexOf(GrailsResourceUtils.JAR_URL_SEPARATOR);
        if (separatorIndex != -1) {
            jarFileUrl = urlFile.substring(0, separatorIndex);
            rootEntryPath = urlFile.substring(separatorIndex + GrailsResourceUtils.JAR_URL_SEPARATOR.length());
            jarFile = getJarFile(jarFileUrl);
        } else {
            jarFile = new JarFile(urlFile);
            jarFileUrl = urlFile;
            rootEntryPath = "";
        }
        newJarFile = true;
    }

    try {
        if (!"".equals(rootEntryPath) && !rootEntryPath.endsWith("/")) {
            // Root entry path must end with slash to allow for proper matching.
            // The Sun JRE does not return a slash here, but BEA JRockit does.
            rootEntryPath = rootEntryPath + "/";
        }
        Set<Resource> result = new LinkedHashSet<Resource>(8);
        for (Enumeration<JarEntry> entries = jarFile.entries(); entries.hasMoreElements();) {
            JarEntry entry = entries.nextElement();
            String entryPath = entry.getName();
            if (entryPath.startsWith(rootEntryPath)) {
                String relativePath = entryPath.substring(rootEntryPath.length());
                if (getPathMatcher().match(subPattern, relativePath)) {
                    result.add(rootDirResource.createRelative(relativePath));
                }
            }
        }
        return result;
    } finally {
        // Close jar file, but only if freshly obtained -
        // not from JarURLConnection, which might cache the file reference.
        if (newJarFile) {
            jarFile.close();
        }
    }
}

From source file:net.dries007.coremod.Module.java

/**
 * This method gets all the dependencies, ASM classes and ATs from the files associated with this module.
 *///from w  w  w.  j av a  2s .c  o  m
public void parceJarFiles() {
    for (ModuleFile mFile : this.files) {
        try {
            JarFile jar = new JarFile(mFile.file);
            Manifest mf = jar.getManifest();
            if (mf != null) {
                for (Entry<Object, Object> attribute : mf.getMainAttributes().entrySet()) {
                    attributes.put(attribute.getKey().toString(), attribute.getValue().toString());
                }
                /**
                 * Reading NORMAL libs from the modules' manifest files.
                 * We want: Space sperated pairs of filename:sha1
                 */
                if (Data.hasKey(Data.LIBKEY_NORMAL, Data.LIBURL_NORMAL)) {
                    String libs = mf.getMainAttributes().getValue(Data.get(Data.LIBKEY_NORMAL));
                    if (libs != null)
                        for (String lib : libs.split(" ")) {
                            DefaultDependency dependency = new DefaultDependency(lib);
                            dependecies.add(dependency);
                        }
                }

                /**
                 * Reading MAVEN libs from the modules' manifest files.
                 * We want: the maven name
                 */
                if (Data.hasKey(Data.LIBKEY_MAVEN, Data.LIBURL_MAVEN)) {
                    String libs = mf.getMainAttributes().getValue(Data.get(Data.LIBKEY_MAVEN));
                    if (libs != null)
                        for (String lib : libs.split(" ")) {
                            MavenDependency dependency = new MavenDependency(this, lib);
                            dependecies.add(dependency);
                            dependecies.addAll(Coremod.getDependencies(dependency));
                        }
                }

                /*
                 * Reading ASM classes from the modules' manifest files
                 */
                if (Data.hasKey(Data.CLASSKEY_ASM)) {
                    String asmclasses = mf.getMainAttributes().getValue(Data.get(Data.CLASSKEY_ASM));
                    if (asmclasses != null)
                        for (String asmclass : asmclasses.split(" ")) {
                            this.ASMClasses.add(asmclass);
                            System.out.println("[" + Data.NAME + "] Added ASM class (" + asmclass
                                    + ") for module file " + jar.getName());
                        }
                }

                /*
                 * Reading AT Files from the modules' manifest files
                 */
                if (Data.hasKey(Data.FILEKEY_TA)) {
                    String ats = mf.getMainAttributes().getValue(Data.FILEKEY_TA);
                    if (ats != null)
                        for (String at : ats.split(" ")) {
                            this.ATFiles.add(at);
                            System.out.println("[" + Data.NAME + "] Added AccessTransformer (" + at
                                    + ") for module file " + jar.getName());
                        }
                }
            }
            jar.close();
        } catch (final MalformedURLException e) {
            e.printStackTrace();
        } catch (final IOException e) {
            e.printStackTrace();
        }
    }
}

From source file:org.codehaus.groovy.grails.io.support.PathMatchingResourcePatternResolver.java

/**
 * Find all resources in jar files that match the given location pattern
 * via the Ant-style PathMatcher.//from  ww  w . j a va  2 s  .c  o  m
 * @param rootDirResource the root directory as Resource
 * @param subPattern the sub pattern to match (below the root directory)
 * @return the Set of matching Resource instances
 * @throws IOException in case of I/O errors
 * @see java.net.JarURLConnection
 */
protected Set<Resource> doFindPathMatchingJarResources(Resource rootDirResource, String subPattern)
        throws IOException {

    URLConnection con = rootDirResource.getURL().openConnection();
    JarFile jarFile;
    String jarFileUrl;
    String rootEntryPath;
    boolean newJarFile = false;

    if (con instanceof JarURLConnection) {
        // Should usually be the case for traditional JAR files.
        JarURLConnection jarCon = (JarURLConnection) con;
        GrailsResourceUtils.useCachesIfNecessary(jarCon);
        jarFile = jarCon.getJarFile();
        jarFileUrl = jarCon.getJarFileURL().toExternalForm();
        JarEntry jarEntry = jarCon.getJarEntry();
        rootEntryPath = (jarEntry != null ? jarEntry.getName() : "");
    } else {
        // No JarURLConnection -> need to resort to URL file parsing.
        // We'll assume URLs of the format "jar:path!/entry", with the protocol
        // being arbitrary as long as following the entry format.
        // We'll also handle paths with and without leading "file:" prefix.
        String urlFile = rootDirResource.getURL().getFile();
        int separatorIndex = urlFile.indexOf(GrailsResourceUtils.JAR_URL_SEPARATOR);
        if (separatorIndex != -1) {
            jarFileUrl = urlFile.substring(0, separatorIndex);
            rootEntryPath = urlFile.substring(separatorIndex + GrailsResourceUtils.JAR_URL_SEPARATOR.length());
            jarFile = getJarFile(jarFileUrl);
        } else {
            jarFile = new JarFile(urlFile);
            jarFileUrl = urlFile;
            rootEntryPath = "";
        }
        newJarFile = true;
    }

    try {
        if (logger.isDebugEnabled()) {
            logger.debug("Looking for matching resources in jar file [" + jarFileUrl + "]");
        }
        if (!"".equals(rootEntryPath) && !rootEntryPath.endsWith("/")) {
            // Root entry path must end with slash to allow for proper matching.
            // The Sun JRE does not return a slash here, but BEA JRockit does.
            rootEntryPath = rootEntryPath + "/";
        }
        Set<Resource> result = new LinkedHashSet<Resource>(8);
        for (Enumeration<JarEntry> entries = jarFile.entries(); entries.hasMoreElements();) {
            JarEntry entry = entries.nextElement();
            String entryPath = entry.getName();
            if (entryPath.startsWith(rootEntryPath)) {
                String relativePath = entryPath.substring(rootEntryPath.length());
                if (getPathMatcher().match(subPattern, relativePath)) {
                    result.add(rootDirResource.createRelative(relativePath));
                }
            }
        }
        return result;
    } finally {
        // Close jar file, but only if freshly obtained -
        // not from JarURLConnection, which might cache the file reference.
        if (newJarFile) {
            jarFile.close();
        }
    }
}

From source file:org.lnicholls.galleon.app.AppDescriptor.java

public AppDescriptor(File jar) throws IOException, AppException {
    mJar = jar;//www .  j av  a  2  s . c  om

    JarFile zipFile = new JarFile(jar);
    Enumeration entries = zipFile.entries();
    while (entries.hasMoreElements()) {
        ZipEntry entry = (ZipEntry) entries.nextElement();
        String name = entry.getName();
        if (name.toUpperCase().equals(JarFile.MANIFEST_NAME)) {
            InputStream in = null;
            try {
                in = zipFile.getInputStream(entry);
                Manifest manifest = new Manifest(in);
                Attributes attributes = manifest.getMainAttributes();
                if (attributes.getValue("Main-Class") != null) {
                    mClassName = (String) attributes.getValue("Main-Class");
                    if (attributes.getValue("HME-Arguments") != null)
                        mArguments = (String) attributes.getValue("HME-Arguments");
                    if (attributes.getValue(TITLE) != null)
                        mTitle = (String) attributes.getValue(TITLE);
                    if (attributes.getValue(RELEASE_DATE) != null)
                        mReleaseDate = (String) attributes.getValue(RELEASE_DATE);
                    if (attributes.getValue(DESCRIPTION) != null)
                        mDescription = (String) attributes.getValue(DESCRIPTION);
                    if (attributes.getValue(DOCUMENTATION) != null)
                        mDocumentation = (String) attributes.getValue(DOCUMENTATION);
                    if (attributes.getValue(AUTHOR_NAME) != null)
                        mAuthorName = (String) attributes.getValue(AUTHOR_NAME);
                    if (attributes.getValue(AUTHOR_EMAIL) != null)
                        mAuthorEmail = (String) attributes.getValue(AUTHOR_EMAIL);
                    if (attributes.getValue(AUTHOR_HOMEPAGE) != null)
                        mAuthorHomepage = (String) attributes.getValue(AUTHOR_HOMEPAGE);
                    if (attributes.getValue(VERSION) != null)
                        mVersion = (String) attributes.getValue(VERSION);
                    if (attributes.getValue(CONFIGURATION) != null)
                        mConfiguration = (String) attributes.getValue(CONFIGURATION);
                    if (attributes.getValue(CONFIGURATION_PANEL) != null)
                        mConfigurationPanel = (String) attributes.getValue(CONFIGURATION_PANEL);
                    if (attributes.getValue(TAGS) != null)
                        mTags = (String) attributes.getValue(TAGS);
                }

                if (mTitle == null) {
                    mTitle = jar.getName().substring(0, jar.getName().indexOf('.'));
                }
            } catch (Exception ex) {
                Tools.logException(AppDescriptor.class, ex, "Cannot get descriptor: " + jar.getAbsolutePath());
            } finally {
                if (in != null) {
                    try {
                        in.close();
                        in = null;
                    } catch (Exception ex) {
                    }
                }
            }
            break;
        }
    }
    zipFile.close();
}

From source file:org.zkoss.spring.core.io.support.PathMatchingResourcePatternResolver.java

/**
 * Find all resources in jar files that match the given location pattern
 * via the Ant-style PathMatcher.//from w ww .ja  v a 2  s .  com
 * @param rootDirResource the root directory as Resource
 * @param subPattern the sub pattern to match (below the root directory)
 * @return the Set of matching Resource instances
 * @throws IOException in case of I/O errors
 * @see java.net.JarURLConnection
 * @see org.springframework.util.PathMatcher
 */
protected Set<Resource> doFindPathMatchingJarResources(Resource rootDirResource, String subPattern)
        throws IOException {

    URLConnection con = rootDirResource.getURL().openConnection();
    JarFile jarFile;
    String jarFileUrl;
    String rootEntryPath;
    boolean newJarFile = false;

    if (con instanceof JarURLConnection) {
        // Should usually be the case for traditional JAR files.
        JarURLConnection jarCon = (JarURLConnection) con;
        jarCon.setUseCaches(false);
        jarFile = jarCon.getJarFile();
        jarFileUrl = jarCon.getJarFileURL().toExternalForm();
        JarEntry jarEntry = jarCon.getJarEntry();
        rootEntryPath = (jarEntry != null ? jarEntry.getName() : "");
    } else {
        // No JarURLConnection -> need to resort to URL file parsing.
        // We'll assume URLs of the format "jar:path!/entry", with the protocol
        // being arbitrary as long as following the entry format.
        // We'll also handle paths with and without leading "file:" prefix.
        String urlFile = rootDirResource.getURL().getFile();
        int separatorIndex = urlFile.indexOf(ResourceUtils.JAR_URL_SEPARATOR);
        if (separatorIndex != -1) {
            jarFileUrl = urlFile.substring(0, separatorIndex);
            rootEntryPath = urlFile.substring(separatorIndex + ResourceUtils.JAR_URL_SEPARATOR.length());
            jarFile = getJarFile(jarFileUrl);
        } else {
            jarFile = new JarFile(urlFile);
            jarFileUrl = urlFile;
            rootEntryPath = "";
        }
        newJarFile = true;
    }

    try {
        if (logger.isDebugEnabled()) {
            logger.debug("Looking for matching resources in jar file [" + jarFileUrl + "]");
        }
        if (!"".equals(rootEntryPath) && !rootEntryPath.endsWith("/")) {
            // Root entry path must end with slash to allow for proper matching.
            // The Sun JRE does not return a slash here, but BEA JRockit does.
            rootEntryPath = rootEntryPath + "/";
        }
        Set<Resource> result = new LinkedHashSet<Resource>(8);
        for (Enumeration entries = jarFile.entries(); entries.hasMoreElements();) {
            JarEntry entry = (JarEntry) entries.nextElement();
            String entryPath = entry.getName();
            if (entryPath.startsWith(rootEntryPath)) {
                String relativePath = entryPath.substring(rootEntryPath.length());
                if (getPathMatcher().match(subPattern, relativePath)) {
                    result.add(rootDirResource.createRelative(relativePath));
                }
            }
        }
        return result;
    } finally {
        // Close jar file, but only if freshly obtained -
        // not from JarURLConnection, which might cache the file reference.
        if (newJarFile) {
            jarFile.close();
        }
    }
}

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  ww w  .jav a  2s .  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");
    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:org.kepler.objectmanager.ActorMetadata.java

/**
 * try to locate and parse a moml file as a class
 *///from w  ww  . j  av a 2  s  .c  o m
protected ComponentEntity parseMoMLFile(String className) throws Exception {
    if (isDebugging)
        log.debug("parseMoMLFile(" + className + ")");

    JarFile jarFile = null;
    InputStream xmlStream = null;
    try {
        // first we need to find the file and read it
        File classFile = searchClasspath(className);
        StringWriter sw = new StringWriter();
        if (classFile.getName().endsWith(".jar")) {
            jarFile = new JarFile(classFile);
            ZipEntry entry = jarFile.getEntry(className.replace('.', '/') + ".xml");
            xmlStream = jarFile.getInputStream(entry);
        } else {
            xmlStream = new FileInputStream(classFile);
        }

        byte[] b = new byte[1024];
        int numread = xmlStream.read(b, 0, 1024);
        while (numread != -1) {
            String s = new String(b, 0, numread);
            sw.write(s);
            numread = xmlStream.read(b, 0, 1024);
        }
        sw.flush();
        // get the moml document
        String xmlDoc = sw.toString();
        sw.close();

        if (isDebugging)
            log.debug("**** MoMLParser ****");

        // use the moml parser to parse the doc
        MoMLParser parser = new MoMLParser();
        parser.reset();

        // System.out.println("processing " + className);
        NamedObj obj = parser.parse(xmlDoc);
        return (ComponentEntity) obj;
    } finally {
        if (jarFile != null) {
            jarFile.close();
        }
        if (xmlStream != null) {
            xmlStream.close();
        }
    }
}

From source file:org.voltdb.compiler.VoltCompiler.java

public List<Class<?>> getInnerClasses(Class<?> c) throws VoltCompilerException {
    ImmutableList.Builder<Class<?>> builder = ImmutableList.builder();
    ClassLoader cl = c.getClassLoader();
    if (cl == null) {
        cl = Thread.currentThread().getContextClassLoader();
    }/*from  w  ww.  j ava  2s .c  o m*/

    // if loading from an InMemoryJarFile, the process is a bit different...
    if (cl instanceof JarLoader) {
        String[] classes = ((JarLoader) cl).getInnerClassesForClass(c.getName());
        for (String innerName : classes) {
            Class<?> clz = null;
            try {
                clz = cl.loadClass(innerName);
            } catch (ClassNotFoundException e) {
                String msg = "Unable to load " + c + " inner class " + innerName
                        + " from in-memory jar representation.";
                throw new VoltCompilerException(msg);
            }
            assert (clz != null);
            builder.add(clz);
        }
    } else {
        String stem = c.getName().replace('.', '/');
        String cpath = stem + ".class";
        URL curl = cl.getResource(cpath);
        if (curl == null) {
            throw new VoltCompilerException(String.format("Failed to find class file %s in jar.", cpath));
        }

        // load from an on-disk jar
        if ("jar".equals(curl.getProtocol())) {
            Pattern nameRE = Pattern.compile("\\A(" + stem + "\\$[^/]+).class\\z");
            String jarFN;
            try {
                jarFN = URLDecoder.decode(curl.getFile(), "UTF-8");
            } catch (UnsupportedEncodingException e) {
                String msg = "Unable to UTF-8 decode " + curl.getFile() + " for class " + c;
                throw new VoltCompilerException(msg);
            }
            jarFN = jarFN.substring(5, jarFN.indexOf('!'));
            JarFile jar = null;
            try {
                jar = new JarFile(jarFN);
                Enumeration<JarEntry> entries = jar.entries();
                while (entries.hasMoreElements()) {
                    String name = entries.nextElement().getName();
                    Matcher mtc = nameRE.matcher(name);
                    if (mtc.find()) {
                        String innerName = mtc.group(1).replace('/', '.');
                        Class<?> inner;
                        try {
                            inner = cl.loadClass(innerName);
                        } catch (ClassNotFoundException e) {
                            String msg = "Unable to load " + c + " inner class " + innerName;
                            throw new VoltCompilerException(msg);
                        }
                        builder.add(inner);
                    }
                }
            } catch (IOException e) {
                String msg = "Cannot access class " + c + " source code location of " + jarFN;
                throw new VoltCompilerException(msg);
            } finally {
                if (jar != null)
                    try {
                        jar.close();
                    } catch (Exception ignoreIt) {
                    }
                ;
            }
        }
        // load directly from a classfile
        else if ("file".equals(curl.getProtocol())) {
            Pattern nameRE = Pattern.compile("/(" + stem + "\\$[^/]+).class\\z");
            File sourceDH = new File(curl.getFile()).getParentFile();
            for (File f : sourceDH.listFiles()) {
                Matcher mtc = nameRE.matcher(f.getAbsolutePath());
                if (mtc.find()) {
                    String innerName = mtc.group(1).replace('/', '.');
                    Class<?> inner;
                    try {
                        inner = cl.loadClass(innerName);
                    } catch (ClassNotFoundException e) {
                        String msg = "Unable to load " + c + " inner class " + innerName;
                        throw new VoltCompilerException(msg);
                    }
                    builder.add(inner);
                }
            }

        }
    }
    return builder.build();
}

From source file:com.orange.mmp.dao.flf.ModuleDaoFlfImpl.java

@SuppressWarnings("unchecked")
public Module createOrUdpdate(Module module) throws MMPDaoException {
    if (module == null || module.getLocation() == null) {
        throw new MMPDaoException("missing or bad data access object");
    }//from w  w w  . jav a  2s.  com

    JarFile jarFile = null;
    try {
        this.lock.lock();
        jarFile = new JarFile(new File(module.getLocation()));
        Manifest manifest = jarFile.getManifest();
        if (manifest == null) {
            throw new MMPDaoException("invalid module archive, MANIFEST file not found");
        }
        String symbolicName = manifest.getMainAttributes().getValue(MODULE_ID_HEADER);
        if (manifest.getMainAttributes().getValue(MODULE_ID_HEADER) != null) {
            if (module instanceof Widget) {
                String[] widgetId = symbolicName.split(com.orange.mmp.widget.Constants.BRANCH_SUFFIX_PATTERN);
                module.setId(widgetId[0]);
            } else {
                module.setId(symbolicName);
            }
        } else
            throw new MMPDaoException("invalid module archive, missing " + MODULE_ID_HEADER + " header");
        if (manifest.getMainAttributes().getValue(MODULE_NAME_HEADER) != null) {
            module.setName(manifest.getMainAttributes().getValue(MODULE_NAME_HEADER));
        } else
            throw new MMPDaoException("invalid module archive, missing " + MODULE_NAME_HEADER + " header");
        if (manifest.getMainAttributes().getValue(MODULE_VERSION_HEADER) != null) {
            module.setVersion(new Version(manifest.getMainAttributes().getValue(MODULE_VERSION_HEADER)));
        } else
            throw new MMPDaoException("invalid module archive, missing " + MODULE_VERSION_HEADER + " header");
        if (manifest.getMainAttributes().getValue(MODULE_CATEGORY_HEADER) != null) {
            module.setCategory(manifest.getMainAttributes().getValue(MODULE_CATEGORY_HEADER));
        } else
            module.setCategory(Constants.MODULE_CATEGORY_LIBRARY);

        File moduleFile = new File(module.getLocation());
        File dstFile;
        if (module instanceof Widget) {
            String[] nameAndBranch = symbolicName.split(com.orange.mmp.widget.Constants.BRANCH_SUFFIX_PATTERN);
            if (nameAndBranch.length > 1)
                dstFile = new File(this.path,
                        nameAndBranch[0].concat(com.orange.mmp.widget.Constants.BRANCH_SUFFIX_PATTERN)
                                .concat(nameAndBranch[1]).concat(".jar"));
            else {
                String defaultBranchId = null;
                Branch defaultBranch = new Branch();
                defaultBranch.setDefault(true);
                Branch defaultBranchesResult[] = (Branch[]) DaoManagerFactory.getInstance().getDaoManager()
                        .getDao("branch").find(defaultBranch);
                if (defaultBranchesResult.length > 0) {
                    defaultBranchId = defaultBranchesResult[0].getId();
                }
                defaultBranch = defaultBranchesResult[0];
                dstFile = new File(this.path,
                        nameAndBranch[0].concat(com.orange.mmp.widget.Constants.BRANCH_SUFFIX_PATTERN)
                                .concat(defaultBranchId).concat(".jar"));
            }
        } else {
            dstFile = new File(this.path, symbolicName.concat(".jar"));
        }
        FileUtils.copyFile(moduleFile, dstFile);
        module.setLocation(dstFile.toURI());
        module.setLastModified(dstFile.lastModified());
        jarFile.close();

        FileUtils.touch(new File(this.path));

        return module;
    } catch (IOException ioe) {
        throw new MMPDaoException("failed to add module : " + ioe.getMessage());
    } finally {
        try {
            if (jarFile != null)
                jarFile.close();
        } catch (IOException ioe) {
            //Nop just log
        }
        this.lock.unlock();
    }
}