Example usage for java.util.jar JarFile entries

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

Introduction

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

Prototype

public Enumeration<JarEntry> entries() 

Source Link

Document

Returns an enumeration of the jar file entries.

Usage

From source file:org.lockss.plugin.PluginManager.java

void ensureJarPluginsLoaded(String jarname, Pattern pat) {
    try {//from  w  w w .  j av  a2s  .c om
        JarFile jar = new JarFile(jarname);
        for (Enumeration<JarEntry> en = jar.entries(); en.hasMoreElements();) {
            JarEntry ent = en.nextElement();
            Matcher mat = pat.matcher(ent.getName());
            if (mat.matches()) {
                String membname = mat.group(1);
                String plugname = membname.replace('/', '.');
                String plugkey = pluginKeyFromName(plugname);
                ensurePluginLoaded(plugkey);
            }
        }
    } catch (IOException e) {
        log.error("Couldn't open plugin registry jar: " + jarname);
    }
}

From source file:org.springframework.core.io.support.PathMatchingResourcePatternResolver.java

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

    URLConnection con = rootDirURL.openConnection();
    JarFile jarFile;
    String jarFileUrl;
    String rootEntryPath;
    boolean closeJarFile;

    if (con instanceof JarURLConnection) {
        // Should usually be the case for traditional JAR files.
        JarURLConnection jarCon = (JarURLConnection) con;
        ResourceUtils.useCachesIfNecessary(jarCon);
        jarFile = jarCon.getJarFile();
        jarFileUrl = jarCon.getJarFileURL().toExternalForm();
        JarEntry jarEntry = jarCon.getJarEntry();
        rootEntryPath = (jarEntry != null ? jarEntry.getName() : "");
        closeJarFile = !jarCon.getUseCaches();
    } 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 = rootDirURL.getFile();
        try {
            int separatorIndex = urlFile.indexOf(ResourceUtils.WAR_URL_SEPARATOR);
            if (separatorIndex == -1) {
                separatorIndex = urlFile.indexOf(ResourceUtils.JAR_URL_SEPARATOR);
            }
            if (separatorIndex != -1) {
                jarFileUrl = urlFile.substring(0, separatorIndex);
                rootEntryPath = urlFile.substring(separatorIndex + 2); // both separators are 2 chars
                jarFile = getJarFile(jarFileUrl);
            } else {
                jarFile = new JarFile(urlFile);
                jarFileUrl = urlFile;
                rootEntryPath = "";
            }
            closeJarFile = true;
        } catch (ZipException ex) {
            if (logger.isDebugEnabled()) {
                logger.debug("Skipping invalid jar classpath entry [" + urlFile + "]");
            }
            return Collections.emptySet();
        }
    }

    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<>(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 {
        if (closeJarFile) {
            jarFile.close();
        }
    }
}

From source file:org.kchine.r.server.DirectJNI.java

public static void generateMaps(URL jarUrl, boolean rawClasses) {

    try {//from w  ww  .  j a va  2 s  . c o m

        _mappingClassLoader = new URLClassLoader(new URL[] { jarUrl }, DirectJNI.class.getClassLoader());
        Vector<String> list = new Vector<String>();
        JarURLConnection jarConnection = (JarURLConnection) jarUrl.openConnection();
        JarFile jarfile = jarConnection.getJarFile();
        Enumeration<JarEntry> enu = jarfile.entries();
        while (enu.hasMoreElements()) {
            String entry = enu.nextElement().toString();
            if (entry.endsWith(".class"))
                list.add(entry.replace('/', '.').substring(0, entry.length() - ".class".length()));
        }

        log.info(list);

        for (int i = 0; i < list.size(); ++i) {
            String className = list.elementAt(i);
            if (className.startsWith("org.kchine.r.packages.")
                    && !className.startsWith("org.kchine.r.packages.rservices")) {
                Class<?> c_ = _mappingClassLoader.loadClass(className);

                if (c_.getSuperclass() != null && c_.getSuperclass().equals(RObject.class)
                        && !Modifier.isAbstract(c_.getModifiers())) {

                    if (c_.equals(RLogical.class) || c_.equals(RInteger.class) || c_.equals(RNumeric.class)
                            || c_.equals(RComplex.class) || c_.equals(RChar.class) || c_.equals(RMatrix.class)
                            || c_.equals(RArray.class) || c_.equals(RList.class) || c_.equals(RDataFrame.class)
                            || c_.equals(RFactor.class) || c_.equals(REnvironment.class)
                            || c_.equals(RVector.class) || c_.equals(RUnknown.class)) {
                    } else {
                        String rclass = DirectJNI.getRClassForBean(jarfile, className);
                        _s4BeansHash.put(className, c_);
                        _s4BeansMapping.put(rclass, className);
                        _s4BeansMappingRevert.put(className, rclass);
                    }

                } else if ((rawClasses && c_.getSuperclass() != null && c_.getSuperclass().equals(Object.class))
                        || (!rawClasses && RPackage.class.isAssignableFrom(c_) && (c_.isInterface()))) {

                    String shortClassName = className.substring(className.lastIndexOf('.') + 1);
                    _packageNames.add(shortClassName);

                    Vector<Class<?>> v = _rPackageInterfacesHash.get(className);
                    if (v == null) {
                        v = new Vector<Class<?>>();
                        _rPackageInterfacesHash.put(className, v);
                    }
                    v.add(c_);

                } else {
                    String nameWithoutPackage = className.substring(className.lastIndexOf('.') + 1);
                    if (nameWithoutPackage.indexOf("Factory") != -1
                            && c_.getMethod("setData", new Class[] { RObject.class }) != null) {
                        // if
                        // (DirectJNI._factoriesMapping.get(nameWithoutPackage
                        // )
                        // != null) throw new Exception("Factories Names
                        // Conflict : two " + nameWithoutPackage);
                        _factoriesMapping.put(nameWithoutPackage, className);
                        if (Modifier.isAbstract(c_.getModifiers()))
                            _abstractFactories.add(className);
                    }
                }
            }
        }

        // log.info("s4Beans:" +s4Beans);
        log.info("rPackageInterfaces:" + _packageNames);
        log.info("s4Beans MAP :" + _s4BeansMapping);
        log.info("s4Beans Revert MAP :" + _s4BeansMappingRevert);
        log.info("factories :" + _factoriesMapping);
        log.info("r package interface hash :" + _rPackageInterfacesHash);

    } catch (Exception ex) {
        ex.printStackTrace();
    }

}

From source file:org.regenstrief.util.Util.java

/**
 * Writes information about a .jar/* www . ja  va 2  s .  c  o  m*/
 * 
 * @param path the path of the .jar
 * @param w the Writer
 * @throws Exception if an I/O problem occurs
 **/
public final static void jarInfo(final String path, final Writer w) throws Exception {
    final JarFile jar = new JarFile(new File(path));
    final Enumeration<JarEntry> en = jar.entries();
    final PrintWriter pw = getPrintWriter(w);

    while (en.hasMoreElements()) {
        final String name = en.nextElement().getName();
        if (!name.endsWith(".class")) {
            continue;
        }
        try {
            Class<?> c = Class.forName(name.substring(0, name.length() - 6).replace('/', '.'));
            final Member[][] allMembers = new Member[][] { c.getFields(), c.getConstructors(), c.getMethods() };
            pw.print(c);
            for (c = c.getSuperclass(); c != null; c = c.getSuperclass()) {
                pw.print(" extends ");
                pw.print(c.getName());
            }
            pw.println();
            pw.println('{');
            for (int j = 0; j < allMembers.length; j++) {
                final Member[] members = allMembers[j];
                for (final Member member : members) {
                    if (!Modifier.isPublic(member.getModifiers())) {
                        continue;
                    }
                    pw.print('\t');
                    pw.print(member);
                    pw.println(';');
                }
                if ((members.length > 0) && (j < allMembers.length - 1)) {
                    pw.println();
                }
            }
            pw.println('}');
        } catch (final Throwable e) {
            pw.println(e);
        }
        pw.println();
    }

    pw.flush();
    jar.close();
}

From source file:org.regenstrief.util.Util.java

private final static Class<?>[] getClasses(final Criterion nameCriterion, final Criterion classCriterion,
        final String ext) {
    final String[] _paths = getClassPath();
    List<String> paths = Arrays.asList(_paths);
    if (ext != null) {
        paths = new ArrayList<String>(paths);
        paths.add(ext);/*w w  w . j  av  a 2s . com*/
    }
    final List<Resource> nameList = new ArrayList<Resource>();

    for (final String path : paths) {
        //log.info(path);
        final File f = new File(path);
        if (f.isDirectory()) {
            final int pathLength = f.getAbsolutePath().length() + 1;
            for (final File child : getAllFiles(f)) {
                //log.info('\t' + child.getAbsolutePath().substring(pathLength));
                nameList.add(new Resource(path, child.getAbsolutePath().substring(pathLength)));
            }
        } else if (path.endsWith(".jar")) {
            final JarFile jf;
            try {
                jf = new JarFile(f);
            } catch (final IOException e) {
                throw toRuntimeException(e);
            }
            final Enumeration<JarEntry> entries = jf.entries();
            while (entries.hasMoreElements()) {
                nameList.add(new Resource(path, entries.nextElement().getName()));
            }
            try {
                jf.close();
            } catch (final IOException e) {
                // Can't close
            }
        }
    }

    final List<Class<?>> classList = new ArrayList<Class<?>>();
    final Set<String> nameSet = new HashSet<String>();
    for (final Resource resource : nameList) {
        final String childName = resource.resourcePath;
        if (childName.endsWith(".class")) {
            final String className = childName.substring(0, childName.length() - 6).replace('/', '.')
                    .replace('\\', '.');
            if (((nameCriterion == null) || nameCriterion.isMet(className)) && !nameSet.contains(className)) {
                nameSet.add(className);
                final Class<?> c;
                try {
                    c = ReflectUtil.forName(className);
                    //} catch (final NoClassDefFoundError e)
                    //{   // Just keep looking
                    //} catch (final IncompatibleClassChangeError e)
                    //{   // Just keep looking
                } catch (final Throwable e) {
                    throw new RuntimeException("Error loading class " + className + " from " + childName
                            + " in " + resource.containerPath, e);
                }
                if ((classCriterion == null) || classCriterion.isMet(c)) {
                    addIfNotContainedOrNull(classList, c);
                }
            }
        }
    }

    return classList.toArray(EMPTY_ARRAY_CLASS);
}

From source file:org.infoglue.deliver.portal.deploy.Deploy.java

/**
 * Prepare a portlet according to Pluto (switch web.xml)
 * /*from www  . j  a  v  a 2s.  c o m*/
 * @param file .war to prepare
 * @param tmp the resulting updated .war
 * @param appName name of application (context name)
 * @return the portlet application definition (portlet.xml)
 * @throws IOException
 */
public static PortletApplicationDefinition prepareArchive(File file, File tmp, String appName)
        throws IOException {
    PortletApplicationDefinitionImpl portletApp = null;
    try {
        Mapping pdmXml = new Mapping();
        try {
            URL url = Deploy.class.getResource("/" + PORTLET_MAPPING);
            pdmXml.loadMapping(url);
        } catch (Exception e) {
            throw new IOException("Failed to load mapping file " + PORTLET_MAPPING);
        }

        // Open the jar file.
        JarFile jar = new JarFile(file);

        // Extract and parse portlet.xml
        ZipEntry portletEntry = jar.getEntry(PORTLET_XML);
        if (portletEntry == null) {
            throw new IOException("Unable to find portlet.xml");
        }

        InputStream pisDebug = jar.getInputStream(portletEntry);
        StringBuffer sb = new StringBuffer();
        int i;
        while ((i = pisDebug.read()) > -1) {
            sb.append((char) i);
        }
        pisDebug.close();

        InputSource xmlSource = new InputSource(new ByteArrayInputStream(sb.toString().getBytes("UTF-8")));
        DOMParser parser = new DOMParser();
        parser.parse(xmlSource);
        Document portletDocument = parser.getDocument();

        //InputStream pis = jar.getInputStream(portletEntry);
        //Document portletDocument = XmlParser.parsePortletXml(pis);
        //pis.close();
        InputStream pis = jar.getInputStream(portletEntry);

        ZipEntry webEntry = jar.getEntry(WEB_XML);
        InputStream wis = null;
        if (webEntry != null) {
            wis = jar.getInputStream(webEntry);
            /*  webDocument = XmlParser.parseWebXml(wis);
            wis.close();
            */
        }

        Unmarshaller unmarshaller = new Unmarshaller(pdmXml);
        unmarshaller.setWhitespacePreserve(true);
        unmarshaller.setIgnoreExtraElements(true);
        unmarshaller.setIgnoreExtraAttributes(true);

        portletApp = (PortletApplicationDefinitionImpl) unmarshaller.unmarshal(portletDocument);

        // refill structure with necessary information
        Vector structure = new Vector();
        structure.add(appName);
        structure.add(null);
        structure.add(null);
        portletApp.preBuild(structure);

        /*
        // now generate web part
        WebApplicationDefinitionImpl webApp = null;
        if (webDocument != null) {
        Unmarshaller unmarshallerWeb = new Unmarshaller(sdmXml);
                
        // modified by YCLI: START :: to ignore extra elements and
        // attributes
        unmarshallerWeb.setWhitespacePreserve(true);
        unmarshallerWeb.setIgnoreExtraElements(true);
        unmarshallerWeb.setIgnoreExtraAttributes(true);
        // modified by YCLI: END
                
        webApp = (WebApplicationDefinitionImpl) unmarshallerWeb.unmarshal(webDocument);
        } else {
        webApp = new WebApplicationDefinitionImpl();
        DisplayNameImpl dispName = new DisplayNameImpl();
        dispName.setDisplayName(appName);
        dispName.setLocale(Locale.ENGLISH);
        DisplayNameSetImpl dispSet = new DisplayNameSetImpl();
        dispSet.add(dispName);
        webApp.setDisplayNames(dispSet);
        DescriptionImpl desc = new DescriptionImpl();
        desc.setDescription("Automated generated Application Wrapper");
        desc.setLocale(Locale.ENGLISH);
        DescriptionSetImpl descSet = new DescriptionSetImpl();
        descSet.add(desc);
        webApp.setDescriptions(descSet);
        }
                
        org.apache.pluto.om.ControllerFactory controllerFactory = new org.apache.pluto.portalImpl.om.ControllerFactoryImpl();
                
        ServletDefinitionListCtrl servletDefinitionSetCtrl = (ServletDefinitionListCtrl) controllerFactory
            .get(webApp.getServletDefinitionList());
        Collection servletMappings = webApp.getServletMappings();
                
        Iterator portlets = portletApp.getPortletDefinitionList().iterator();
        while (portlets.hasNext()) {
                
        PortletDefinition portlet = (PortletDefinition) portlets.next();
                
        // check if already exists
        ServletDefinition servlet = webApp.getServletDefinitionList()
                .get(portlet.getName());
        if (servlet != null) {
            ServletDefinitionCtrl _servletCtrl = (ServletDefinitionCtrl) controllerFactory
                    .get(servlet);
            _servletCtrl.setServletClass("org.apache.pluto.core.PortletServlet");
        } else {
            servlet = servletDefinitionSetCtrl.add(portlet.getName(),
                    "org.apache.pluto.core.PortletServlet");
        }
                
        ServletDefinitionCtrl servletCtrl = (ServletDefinitionCtrl) controllerFactory
                .get(servlet);
                
        DisplayNameImpl dispName = new DisplayNameImpl();
        dispName.setDisplayName(portlet.getName() + " Wrapper");
        dispName.setLocale(Locale.ENGLISH);
        DisplayNameSetImpl dispSet = new DisplayNameSetImpl();
        dispSet.add(dispName);
        servletCtrl.setDisplayNames(dispSet);
        DescriptionImpl desc = new DescriptionImpl();
        desc.setDescription("Automated generated Portlet Wrapper");
        desc.setLocale(Locale.ENGLISH);
        DescriptionSetImpl descSet = new DescriptionSetImpl();
        descSet.add(desc);
        servletCtrl.setDescriptions(descSet);
        ParameterSet parameters = servlet.getInitParameterSet();
                
        ParameterSetCtrl parameterSetCtrl = (ParameterSetCtrl) controllerFactory
                .get(parameters);
                
        Parameter parameter1 = parameters.get("portlet-class");
        if (parameter1 == null) {
            parameterSetCtrl.add("portlet-class", portlet.getClassName());
        } else {
            ParameterCtrl parameterCtrl = (ParameterCtrl) controllerFactory.get(parameter1);
            parameterCtrl.setValue(portlet.getClassName());
                
        }
        Parameter parameter2 = parameters.get("portlet-guid");
        if (parameter2 == null) {
            parameterSetCtrl.add("portlet-guid", portlet.getId().toString());
        } else {
            ParameterCtrl parameterCtrl = (ParameterCtrl) controllerFactory.get(parameter2);
            parameterCtrl.setValue(portlet.getId().toString());
                
        }
                
        boolean found = false;
        Iterator mappings = servletMappings.iterator();
        while (mappings.hasNext()) {
            ServletMappingImpl servletMapping = (ServletMappingImpl) mappings.next();
            if (servletMapping.getServletName().equals(portlet.getName())) {
                found = true;
                servletMapping.setUrlPattern("/" + portlet.getName().replace(' ', '_')
                        + "/*");
            }
        }
        if (!found) {
            ServletMappingImpl servletMapping = new ServletMappingImpl();
            servletMapping.setServletName(portlet.getName());
            servletMapping.setUrlPattern("/" + portlet.getName().replace(' ', '_') + "/*");
            servletMappings.add(servletMapping);
        }
                
        SecurityRoleRefSet servletSecurityRoleRefs = ((ServletDefinitionImpl) servlet)
                .getInitSecurityRoleRefSet();
                
        SecurityRoleRefSetCtrl servletSecurityRoleRefSetCtrl = (SecurityRoleRefSetCtrl) controllerFactory
                .get(servletSecurityRoleRefs);
                
        SecurityRoleSet webAppSecurityRoles = webApp.getSecurityRoles();
                
        SecurityRoleRefSet portletSecurityRoleRefs = portlet.getInitSecurityRoleRefSet();
                
        Iterator p = portletSecurityRoleRefs.iterator();
        while (p.hasNext()) {
            SecurityRoleRef portletSecurityRoleRef = (SecurityRoleRef) p.next();
                
            if (portletSecurityRoleRef.getRoleLink() == null
                    && webAppSecurityRoles.get(portletSecurityRoleRef.getRoleName()) == null) {
                logger.info("Note: The web application has no security role defined which matches the role name \""
                                + portletSecurityRoleRef.getRoleName()
                                + "\" of the security-role-ref element defined for the wrapper-servlet with the name '"
                                + portlet.getName() + "'.");
                break;
            }
            SecurityRoleRef servletSecurityRoleRef = servletSecurityRoleRefs
                    .get(portletSecurityRoleRef.getRoleName());
            if (null != servletSecurityRoleRef) {
                logger.info("Note: Replaced already existing element of type <security-role-ref> with value \""
                                + portletSecurityRoleRef.getRoleName()
                                + "\" for subelement of type <role-name> for the wrapper-servlet with the name '"
                                + portlet.getName() + "'.");
                servletSecurityRoleRefSetCtrl.remove(servletSecurityRoleRef);
            }
            servletSecurityRoleRefSetCtrl.add(portletSecurityRoleRef);
        }
                
        }
        */

        /*
         * TODO is this necessary? TagDefinitionImpl portletTagLib = new
         * TagDefinitionImpl(); Collection taglibs =
         * webApp.getCastorTagDefinitions(); taglibs.add(portletTagLib);
         */

        // Duplicate jar-file with replaced web.xml
        FileOutputStream fos = new FileOutputStream(tmp);
        JarOutputStream tempJar = new JarOutputStream(fos);
        byte[] buffer = new byte[1024];
        int bytesRead;
        for (Enumeration entries = jar.entries(); entries.hasMoreElements();) {
            JarEntry entry = (JarEntry) entries.nextElement();
            JarEntry newEntry = new JarEntry(entry.getName());
            tempJar.putNextEntry(newEntry);

            if (entry.getName().equals(WEB_XML)) {
                // Swap web.xml
                /*
                log.debug("Swapping web.xml");
                OutputFormat of = new OutputFormat();
                of.setIndenting(true);
                of.setIndent(4); // 2-space indention
                of.setLineWidth(16384);
                of.setDoctype(Constants.WEB_PORTLET_PUBLIC_ID, Constants.WEB_PORTLET_DTD);
                        
                XMLSerializer serializer = new XMLSerializer(tempJar, of);
                Marshaller marshaller = new Marshaller(serializer.asDocumentHandler());
                marshaller.setMapping(sdmXml);
                marshaller.marshal(webApp);
                */

                PortletAppDescriptorService portletAppDescriptorService = new StreamPortletAppDescriptorServiceImpl(
                        appName, pis, null);
                File tmpf = File.createTempFile("infoglue-web-xml", null);
                WebAppDescriptorService webAppDescriptorService = new StreamWebAppDescriptorServiceImpl(appName,
                        wis, new FileOutputStream(tmpf));

                org.apache.pluto.driver.deploy.Deploy d = new org.apache.pluto.driver.deploy.Deploy(
                        webAppDescriptorService, portletAppDescriptorService);
                d.updateDescriptors();
                FileInputStream fis = new FileInputStream(tmpf);
                while ((bytesRead = fis.read(buffer)) != -1) {
                    tempJar.write(buffer, 0, bytesRead);
                }
                tmpf.delete();
            } else {
                InputStream entryStream = jar.getInputStream(entry);
                if (entryStream != null) {
                    while ((bytesRead = entryStream.read(buffer)) != -1) {
                        tempJar.write(buffer, 0, bytesRead);
                    }
                }
            }
        }
        tempJar.flush();
        tempJar.close();
        fos.flush();
        fos.close();
        /*
         * String strTo = dirDelim + "WEB-INF" + dirDelim + "tld" + dirDelim +
         * "portlet.tld"; String strFrom = "webapps" + dirDelim + strTo;
         * 
         * copy(strFrom, webAppsDir + webModule + strTo);
         */
    } catch (Exception e) {
        log.error("Failed to prepare archive", e);
        throw new IOException(e.getMessage());
    }

    return portletApp;
}