Example usage for java.util.jar JarFile getEntry

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

Introduction

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

Prototype

public ZipEntry getEntry(String name) 

Source Link

Document

Returns the ZipEntry for the given base entry name or null if not found.

Usage

From source file:org.openmrs.module.ModuleFileParser.java

/**
 * load in messages/*from  w  w w .  j a v a  2  s.  c  o  m*/
 *
 * @param root
 * @param configVersion
 * @return
 */
private Map<String, Properties> getMessages(Element root, String configVersion, JarFile jarfile,
        String moduleId, String version) {

    Map<String, Properties> messages = new HashMap<String, Properties>();

    NodeList messageNodes = root.getElementsByTagName("messages");
    if (messageNodes.getLength() > 0) {
        log.debug("# message nodes: " + messageNodes.getLength());
        int i = 0;
        while (i < messageNodes.getLength()) {
            Node node = messageNodes.item(i);
            NodeList nodes = node.getChildNodes();
            int x = 0;
            String lang = "", file = "";
            while (x < nodes.getLength()) {
                Node childNode = nodes.item(x);
                if ("lang".equals(childNode.getNodeName())) {
                    lang = childNode.getTextContent().trim();
                } else if ("file".equals(childNode.getNodeName())) {
                    file = childNode.getTextContent().trim();
                }
                x++;
            }
            log.debug("lang: " + lang + " file: " + file);

            // lang and file are required
            if (lang.length() > 0 && file.length() > 0) {
                InputStream inStream = null;
                try {
                    //if in development mode, load message properties file from the root dev folder
                    File devDir = ModuleUtil.getDevelopmentDirectory(moduleId);
                    if (devDir != null) {
                        File pathName = new File(devDir, "api" + File.separator + "target" + File.separator
                                + "classes" + File.separator + file);
                        inStream = new FileInputStream(pathName);
                    } else {
                        inStream = ModuleUtil.getResourceFromApi(jarfile, moduleId, version, file);
                    }

                    if (inStream == null) {
                        // Try the old way. Loading from the root of the omod
                        ZipEntry entry = jarfile.getEntry(file);
                        if (entry == null) {
                            throw new ModuleException(Context.getMessageSourceService().getMessage(
                                    "Module.error.noMessagePropsFile", new Object[] { file, lang },
                                    Context.getLocale()));
                        }
                        inStream = jarfile.getInputStream(entry);
                    }
                    Properties props = new Properties();
                    OpenmrsUtil.loadProperties(props, inStream);
                    messages.put(lang, props);
                } catch (IOException e) {
                    log.warn("Unable to load properties: " + file);
                } finally {
                    IOUtils.closeQuietly(inStream);
                }
            } else {
                log.warn("'lang' and 'file' are required for extensions. Given '" + lang + "' and '" + file
                        + "'");
            }
            i++;
        }
    }

    return messages;
}

From source file:com.opensymphony.xwork2.util.finder.ResourceFinder.java

private URL findResource(String resourceName, URL... search) {
    for (int i = 0; i < search.length; i++) {
        URL currentUrl = search[i];
        if (currentUrl == null) {
            continue;
        }/*from w  ww  . j  a  v a  2  s . c om*/
        JarFile jarFile = null;
        try {
            String protocol = currentUrl.getProtocol();
            if ("jar".equals(protocol)) {
                /*
                * If the connection for currentUrl or resURL is
                * used, getJarFile() will throw an exception if the
                * entry doesn't exist.
                */
                URL jarURL = ((JarURLConnection) currentUrl.openConnection()).getJarFileURL();
                try {
                    JarURLConnection juc = (JarURLConnection) new URL("jar", "", jarURL.toExternalForm() + "!/")
                            .openConnection();
                    jarFile = juc.getJarFile();
                } catch (IOException e) {
                    // Don't look for this jar file again
                    search[i] = null;
                    throw e;
                }

                String entryName;
                if (currentUrl.getFile().endsWith("!/")) {
                    entryName = resourceName;
                } else {
                    String file = currentUrl.getFile();
                    int sepIdx = file.lastIndexOf("!/");
                    if (sepIdx == -1) {
                        // Invalid URL, don't look here again
                        search[i] = null;
                        continue;
                    }
                    sepIdx += 2;
                    StringBuilder sb = new StringBuilder(file.length() - sepIdx + resourceName.length());
                    sb.append(file.substring(sepIdx));
                    sb.append(resourceName);
                    entryName = sb.toString();
                }
                if ("META-INF/".equals(entryName) && jarFile.getEntry("META-INF/MANIFEST.MF") != null) {
                    return targetURL(currentUrl, "META-INF/MANIFEST.MF");
                }
                if (jarFile.getEntry(entryName) != null) {
                    return targetURL(currentUrl, resourceName);
                }
            } else if ("file".equals(protocol)) {
                String baseFile = currentUrl.getFile();
                String host = currentUrl.getHost();
                int hostLength = 0;
                if (host != null) {
                    hostLength = host.length();
                }
                StringBuilder buf = new StringBuilder(
                        2 + hostLength + baseFile.length() + resourceName.length());

                if (hostLength > 0) {
                    buf.append("//").append(host);
                }
                // baseFile always ends with '/'
                buf.append(baseFile);
                String fixedResName = resourceName;
                // Do not create a UNC path, i.e. \\host
                while (fixedResName.startsWith("/") || fixedResName.startsWith("\\")) {
                    fixedResName = fixedResName.substring(1);
                }
                buf.append(fixedResName);
                String filename = buf.toString();
                File file = new File(filename);
                File file2 = new File(URLDecoder.decode(filename));

                if (file.exists() || file2.exists()) {
                    return targetURL(currentUrl, fixedResName);
                }
            } else {
                URL resourceURL = targetURL(currentUrl, resourceName);
                URLConnection urlConnection = resourceURL.openConnection();

                try {
                    urlConnection.getInputStream().close();
                } catch (SecurityException e) {
                    return null;
                }
                // HTTP can return a stream on a non-existent file
                // So check for the return code;
                if (!"http".equals(resourceURL.getProtocol())) {
                    return resourceURL;
                }

                int code = ((HttpURLConnection) urlConnection).getResponseCode();
                if (code >= 200 && code < 300) {
                    return resourceURL;
                }
            }
        } catch (MalformedURLException e) {
            // Keep iterating through the URL list
        } catch (IOException e) {
        } catch (SecurityException e) {
        }
    }
    return null;
}

From source file:org.apache.tomcat.maven.plugin.tomcat8.run.RunMojo.java

@Override
protected void enhanceContext(final Context context) throws MojoExecutionException {
    super.enhanceContext(context);

    try {//  w ww  .ja v  a2s .c  o  m
        ClassLoaderEntriesCalculatorRequest request = new ClassLoaderEntriesCalculatorRequest() //
                .setDependencies(dependencies) //
                .setLog(getLog()) //
                .setMavenProject(project) //
                .setAddWarDependenciesInClassloader(addWarDependenciesInClassloader) //
                .setUseTestClassPath(useTestClasspath);
        final ClassLoaderEntriesCalculatorResult classLoaderEntriesCalculatorResult = classLoaderEntriesCalculator
                .calculateClassPathEntries(request);
        final List<String> classLoaderEntries = classLoaderEntriesCalculatorResult.getClassPathEntries();
        final List<File> tmpDirectories = classLoaderEntriesCalculatorResult.getTmpDirectories();

        final List<String> jarPaths = extractJars(classLoaderEntries);

        List<URL> urls = new ArrayList<URL>(jarPaths.size());

        for (String jarPath : jarPaths) {
            try {
                urls.add(new File(jarPath).toURI().toURL());
            } catch (MalformedURLException e) {
                throw new MojoExecutionException(e.getMessage(), e);
            }
        }

        getLog().debug("classLoaderEntriesCalculator urls: " + urls);

        final URLClassLoader urlClassLoader = new URLClassLoader(urls.toArray(new URL[urls.size()]));

        final ClassRealm pluginRealm = getTomcatClassLoader();

        context.setResources(
                new MyDirContext(new File(project.getBuild().getOutputDirectory()).getAbsolutePath(), //
                        getPath(), //
                        getLog()) {
                    @Override
                    public WebResource getClassLoaderResource(String path) {

                        log.debug("RunMojo#getClassLoaderResource: " + path);
                        URL url = urlClassLoader.getResource(StringUtils.removeStart(path, "/"));
                        // search in parent (plugin) classloader
                        if (url == null) {
                            url = pluginRealm.getResource(StringUtils.removeStart(path, "/"));
                        }

                        if (url == null) {
                            // try in reactors
                            List<WebResource> webResources = findResourcesInDirectories(path, //
                                    classLoaderEntriesCalculatorResult.getBuildDirectories());

                            // so we return the first one
                            if (!webResources.isEmpty()) {
                                return webResources.get(0);
                            }
                        }

                        if (url == null) {
                            return new EmptyResource(this, getPath());
                        }

                        return urlToWebResource(url, path);
                    }

                    @Override
                    public WebResource getResource(String path) {
                        log.debug("RunMojo#getResource: " + path);
                        return super.getResource(path);
                    }

                    @Override
                    public WebResource[] getResources(String path) {
                        log.debug("RunMojo#getResources: " + path);
                        return super.getResources(path);
                    }

                    @Override
                    protected WebResource[] getResourcesInternal(String path, boolean useClassLoaderResources) {
                        log.debug("RunMojo#getResourcesInternal: " + path);
                        return super.getResourcesInternal(path, useClassLoaderResources);
                    }

                    @Override
                    public WebResource[] getClassLoaderResources(String path) {
                        try {
                            Enumeration<URL> enumeration = urlClassLoader
                                    .findResources(StringUtils.removeStart(path, "/"));
                            List<URL> urlsFound = new ArrayList<URL>();
                            List<WebResource> webResources = new ArrayList<WebResource>();
                            while (enumeration.hasMoreElements()) {
                                URL url = enumeration.nextElement();
                                urlsFound.add(url);
                                webResources.add(urlToWebResource(url, path));
                            }
                            log.debug("RunMojo#getClassLoaderResources: " + path + " found : "
                                    + urlsFound.toString());

                            webResources.addAll(findResourcesInDirectories(path,
                                    classLoaderEntriesCalculatorResult.getBuildDirectories()));

                            return webResources.toArray(new WebResource[webResources.size()]);

                        } catch (IOException e) {
                            throw new RuntimeException(e.getMessage(), e);
                        }
                    }

                    private List<WebResource> findResourcesInDirectories(String path,
                            List<String> directories) {
                        try {
                            List<WebResource> webResources = new ArrayList<WebResource>();

                            for (String directory : directories) {

                                File file = new File(directory, path);
                                if (file.exists()) {
                                    webResources.add(urlToWebResource(file.toURI().toURL(), path));
                                }

                            }

                            return webResources;
                        } catch (MalformedURLException e) {
                            throw new RuntimeException(e.getMessage(), e);
                        }
                    }

                    private WebResource urlToWebResource(URL url, String path) {
                        JarFile jarFile = null;

                        try {
                            // url.getFile is
                            // file:/Users/olamy/mvn-repo/org/springframework/spring-web/4.0.0.RELEASE/spring-web-4.0.0.RELEASE.jar!/org/springframework/web/context/ContextLoaderListener.class

                            int idx = url.getFile().indexOf('!');

                            if (idx >= 0) {
                                String filePath = StringUtils.removeStart(url.getFile().substring(0, idx),
                                        "file:");

                                jarFile = new JarFile(filePath);

                                JarEntry jarEntry = jarFile.getJarEntry(StringUtils.removeStart(path, "/"));

                                return new JarResource(this, //
                                        getPath(), //
                                        filePath, //
                                        url.getPath().substring(0, idx), //
                                        jarEntry, //
                                        "", //
                                        null);
                            } else {
                                return new FileResource(this, webAppPath, new File(url.getFile()), true);
                            }

                        } catch (IOException e) {
                            throw new RuntimeException(e.getMessage(), e);
                        } finally {
                            IOUtils.closeQuietly(jarFile);
                        }
                    }

                });

        Runtime.getRuntime().addShutdownHook(new Thread() {
            @Override
            public void run() {
                for (File tmpDir : tmpDirectories) {
                    try {
                        FileUtils.deleteDirectory(tmpDir);
                    } catch (IOException e) {
                        // ignore
                    }
                }
            }
        });

        if (classLoaderEntries != null) {
            WebResourceSet webResourceSet = new FileResourceSet() {
                @Override
                public WebResource getResource(String path) {

                    if (StringUtils.startsWithIgnoreCase(path, "/WEB-INF/LIB")) {
                        File file = new File(StringUtils.removeStartIgnoreCase(path, "/WEB-INF/LIB"));
                        return new FileResource(context.getResources(), getPath(), file, true);
                    }
                    if (StringUtils.equalsIgnoreCase(path, "/WEB-INF/classes")) {
                        return new FileResource(context.getResources(), getPath(),
                                new File(project.getBuild().getOutputDirectory()), true);
                    }

                    File file = new File(project.getBuild().getOutputDirectory(), path);
                    if (file.exists()) {
                        return new FileResource(context.getResources(), getPath(), file, true);
                    }

                    //if ( StringUtils.endsWith( path, ".class" ) )
                    {
                        // so we search the class file in the jars
                        for (String jarPath : jarPaths) {
                            File jar = new File(jarPath);
                            if (!jar.exists()) {
                                continue;
                            }

                            try (JarFile jarFile = new JarFile(jar)) {
                                JarEntry jarEntry = (JarEntry) jarFile
                                        .getEntry(StringUtils.removeStart(path, "/"));
                                if (jarEntry != null) {
                                    return new JarResource(context.getResources(), //
                                            getPath(), //
                                            jarFile.getName(), //
                                            jar.toURI().toString(), //
                                            jarEntry, //
                                            path, //
                                            jarFile.getManifest());
                                }
                            } catch (IOException e) {
                                getLog().debug("skip error building jar file: " + e.getMessage(), e);
                            }

                        }
                    }

                    return new EmptyResource(null, path);
                }

                @Override
                public String[] list(String path) {
                    if (StringUtils.startsWithIgnoreCase(path, "/WEB-INF/LIB")) {
                        return jarPaths.toArray(new String[jarPaths.size()]);
                    }
                    if (StringUtils.equalsIgnoreCase(path, "/WEB-INF/classes")) {
                        return new String[] { new File(project.getBuild().getOutputDirectory()).getPath() };
                    }
                    return super.list(path);
                }

                @Override
                public Set<String> listWebAppPaths(String path) {

                    if (StringUtils.equalsIgnoreCase("/WEB-INF/lib/", path)) {
                        // adding outputDirectory as well?
                        return new HashSet<String>(jarPaths);
                    }

                    File filePath = new File(getWarSourceDirectory(), path);

                    if (filePath.isDirectory()) {
                        Set<String> paths = new HashSet<String>();

                        String[] files = filePath.list();
                        if (files == null) {
                            return paths;
                        }

                        for (String file : files) {
                            paths.add(file);
                        }

                        return paths;

                    } else {
                        return Collections.emptySet();
                    }
                }

                @Override
                public boolean mkdir(String path) {
                    return super.mkdir(path);
                }

                @Override
                public boolean write(String path, InputStream is, boolean overwrite) {
                    return super.write(path, is, overwrite);
                }

                @Override
                protected void checkType(File file) {
                    //super.checkType( file );
                }

            };

            context.getResources().addJarResources(webResourceSet);
        }

    } catch (TomcatRunException e) {
        throw new MojoExecutionException(e.getMessage(), e);
    }

}

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

public static String getRClassForBean(JarFile jarFile, String beanClassName) throws Exception {
    BufferedReader br = new BufferedReader(new InputStreamReader(
            jarFile.getInputStream(jarFile.getEntry(beanClassName.replace('.', '/') + ".java"))));
    do {//from ww w  .  ja  v a2 s  .  co m
        String line = br.readLine();
        if (line != null) {
            int p = line.indexOf(LOC_STR_LEFT);
            if (p != -1) {
                return line.substring(p + LOC_STR_LEFT.length(), line.indexOf(LOC_STR_RIGHT)).trim();
            }
        } else
            break;
    } while (true);
    return null;
}

From source file:com.icesoft.faces.webapp.parser.JspPageToDocument.java

/**
 * @param context// w  w w  .  j  av  a 2 s  .  c o m
 * @param namespaceURL
 * @return InputStream
 * @throws IOException
 */
public static InputStream getTldInputStream(ExternalContext context, String namespaceURL) throws IOException {

    // InputStream in = null;
    JarFile jarFile = null;
    String[] location = null;

    namespaceURL = String.valueOf(namespaceURL);

    // "jsp" is only a placeholder for standard JSP tags that are
    // not supported, so just return null

    if ("jsp".equals(namespaceURL)) {
        return null;
    }

    if ("http://java.sun.com/JSP/Page".equals(namespaceURL)) {
        return null;
    }

    // TldLocationsCache may fail esp. with SecurityException on SUN app server
    TldLocationsCache tldCache = new TldLocationsCache(context);
    try {
        location = tldCache.getLocation(namespaceURL);
    } catch (Exception e) {
        if (log.isDebugEnabled()) {
            log.debug(e.getMessage(), e);
        }
    }

    if (null == location) {
        if (namespaceURL.startsWith("/") && namespaceURL.endsWith(".tld")) {
            location = new String[] { namespaceURL };
        }
    }

    if (null == location) {
        location = scanJars(context, namespaceURL);
    }

    if (null == location) {
        //look for Sun implementation
        URL tagURL = JspPageToDocument.class.getClassLoader().getResource(SUN_TAG_CLASS);
        if (null != tagURL) {

            // Bug 876
            // Not all app servers (ie WebLogic 8.1) return
            // an actual JarURLConnection.
            URLConnection conn = tagURL.openConnection();

            //ICE-3683: Special processing for JBoss 5 micro-container with VFS
            if (tagURL.getProtocol().equals("vfszip")) {
                String tagPath = tagURL.toExternalForm();
                String jarPath = tagPath.substring(0, tagPath.indexOf(SUN_TAG_CLASS));

                String tldPath = jarPath;
                if (namespaceURL.endsWith("html")) {
                    tldPath += HTML_TLD_SUFFIX;
                } else if (namespaceURL.endsWith("core")) {
                    tldPath += CORE_TLD_SUFFIX;
                }

                URL tldURL = new URL(tldPath);
                return tldURL.openConnection().getInputStream();
            }

            if (conn instanceof JarURLConnection) {
                location = scanJar((JarURLConnection) conn, namespaceURL);
            } else {
                //OSGi-based servers (such as GlassFishv3 and WebSphere7)
                //do not provide JarURLConnection to their resources so
                //we handle the JSF TLDs as a special case.
                if (namespaceURL.endsWith("html")) {
                    location = getBundleLocation(tagURL, HTML_TLD_SUFFIX);
                } else if (namespaceURL.endsWith("core")) {
                    location = getBundleLocation(tagURL, CORE_TLD_SUFFIX);
                }
            }
        }
    }

    if (null == location) {
        try {
            // scan WebSphere dirs for JSF jars
            String separator = System.getProperty("path.separator");
            String wsDirs = System.getProperty("ws.ext.dirs");

            String[] dirs = null;
            if (null != wsDirs) {
                dirs = wsDirs.split(separator);
            } else {
                dirs = new String[] {};
            }
            Iterator theDirs = Arrays.asList(dirs).iterator();
            while (theDirs.hasNext()) {
                String dir = (String) theDirs.next();
                try {
                    location = scanJars(dir, namespaceURL);
                } catch (Exception e) {
                    //catch all possible exceptions including runtime exception
                    //so that the rest of jars still can be scanned.
                }
                if (null != location) {
                    break;
                }
            }
        } catch (Exception e) {
            if (log.isDebugEnabled()) {
                log.debug(e.getMessage(), e);
            }
        }
    }

    if (null == location) {
        //look for MyFaces implementation
        URL tagURL = JspPageToDocument.class.getClassLoader().getResource(MYFACES_TAG_CLASS);

        if (null != tagURL) {
            URLConnection conn = tagURL.openConnection();

            if (conn instanceof JarURLConnection) {
                location = scanJar((JarURLConnection) conn, namespaceURL);
            } else {
                //OSGi-based servers (such as GlassFishv3 and WebSphere7)
                //do not provide JarURLConnection to their resources so
                //we handle the JSF TLDs as a special case.
                if (namespaceURL.endsWith("html")) {
                    location = getBundleLocation(tagURL, HTML_TLD_SUFFIX);
                } else if (namespaceURL.endsWith("core")) {
                    location = getBundleLocation(tagURL, CORE_TLD_SUFFIX);
                }
            }
        }
    }

    if (null == location) {
        String msg = "Can't find TLD for location [" + namespaceURL
                + "]. JAR containing the TLD may not be in the classpath";
        log.error(msg);
        return null;
    } else {
        if (log.isTraceEnabled()) {
            for (int i = 0; i < location.length; i++) {
                log.trace("Found TLD location for " + namespaceURL + " = " + location[i]);
            }
        }
    }

    if (!location[0].endsWith("jar")) {
        InputStream tldStream = context.getResourceAsStream(location[0]);
        if (null == tldStream) {
            tldStream = (new URL(location[0])).openConnection().getInputStream();
        }
        return tldStream;
    } else {
        // Tag library is packaged in JAR file
        URL jarFileUrl = new URL("jar:" + location[0] + "!/");
        JarURLConnection conn = (JarURLConnection) jarFileUrl.openConnection();
        conn.setUseCaches(false);
        conn.connect();
        jarFile = conn.getJarFile();
        ZipEntry jarEntry = jarFile.getEntry(location[1]);
        return jarFile.getInputStream(jarEntry);
    }

}