Example usage for java.util.jar JarFile getJarEntry

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

Introduction

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

Prototype

public JarEntry getJarEntry(String name) 

Source Link

Document

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

Usage

From source file:org.tobarsegais.webapp.ServletContextListenerImpl.java

public void contextInitialized(ServletContextEvent sce) {
    ServletContext application = sce.getServletContext();
    Map<String, String> bundles = new HashMap<String, String>();
    Map<String, Toc> contents = new LinkedHashMap<String, Toc>();
    List<IndexEntry> keywords = new ArrayList<IndexEntry>();
    Directory index = new RAMDirectory();
    Analyzer analyzer = new StandardAnalyzer(LUCENE_VERSON);
    IndexWriterConfig indexWriterConfig = new IndexWriterConfig(LUCENE_VERSON, analyzer);
    IndexWriter indexWriter;//from ww w .j  a  v a2s .  c  o  m
    try {
        indexWriter = new IndexWriter(index, indexWriterConfig);
    } catch (IOException e) {
        application.log("Cannot create search index. Search will be unavailable.", e);
        indexWriter = null;
    }
    for (String path : (Set<String>) application.getResourcePaths(BUNDLE_PATH)) {
        if (path.endsWith(".jar")) {
            String key = path.substring("/WEB-INF/bundles/".length(), path.lastIndexOf(".jar"));
            application.log("Parsing " + path);
            URLConnection connection = null;
            try {
                URL url = new URL("jar:" + application.getResource(path) + "!/");
                connection = url.openConnection();
                if (!(connection instanceof JarURLConnection)) {
                    application.log(path + " is not a jar file, ignoring");
                    continue;
                }
                JarURLConnection jarConnection = (JarURLConnection) connection;
                JarFile jarFile = jarConnection.getJarFile();
                Manifest manifest = jarFile.getManifest();
                if (manifest != null) {
                    String symbolicName = manifest.getMainAttributes().getValue("Bundle-SymbolicName");
                    if (symbolicName != null) {
                        int i = symbolicName.indexOf(';');
                        if (i != -1) {
                            symbolicName = symbolicName.substring(0, i);
                        }
                        bundles.put(symbolicName, key);
                        key = symbolicName;
                    }
                }

                JarEntry pluginEntry = jarFile.getJarEntry("plugin.xml");
                if (pluginEntry == null) {
                    application.log(path + " does not contain a plugin.xml file, ignoring");
                    continue;
                }
                Plugin plugin = Plugin.read(jarFile.getInputStream(pluginEntry));

                Extension tocExtension = plugin.getExtension("org.eclipse.help.toc");
                if (tocExtension == null || tocExtension.getFile("toc") == null) {
                    application.log(path + " does not contain a 'org.eclipse.help.toc' extension, ignoring");
                    continue;
                }
                JarEntry tocEntry = jarFile.getJarEntry(tocExtension.getFile("toc"));
                if (tocEntry == null) {
                    application.log(path + " is missing the referenced toc: " + tocExtension.getFile("toc")
                            + ", ignoring");
                    continue;
                }
                Toc toc;
                try {
                    toc = Toc.read(jarFile.getInputStream(tocEntry));
                } catch (IllegalStateException e) {
                    application.log("Could not parse " + path + " due to " + e.getMessage(), e);
                    continue;
                }
                contents.put(key, toc);

                Extension indexExtension = plugin.getExtension("org.eclipse.help.index");
                if (indexExtension != null && indexExtension.getFile("index") != null) {
                    JarEntry indexEntry = jarFile.getJarEntry(indexExtension.getFile("index"));
                    if (indexEntry != null) {
                        try {
                            keywords.addAll(Index.read(key, jarFile.getInputStream(indexEntry)).getChildren());
                        } catch (IllegalStateException e) {
                            application.log("Could not parse " + path + " due to " + e.getMessage(), e);
                        }
                    } else {
                        application.log(
                                path + " is missing the referenced index: " + indexExtension.getFile("index"));
                    }

                }
                application.log(path + " successfully parsed and added as " + key);
                if (indexWriter != null) {
                    application.log("Indexing content of " + path);
                    Set<String> files = new HashSet<String>();
                    Stack<Iterator<? extends TocEntry>> stack = new Stack<Iterator<? extends TocEntry>>();
                    stack.push(Collections.singleton(toc).iterator());
                    while (!stack.empty()) {
                        Iterator<? extends TocEntry> cur = stack.pop();
                        if (cur.hasNext()) {
                            TocEntry entry = cur.next();
                            stack.push(cur);
                            if (!entry.getChildren().isEmpty()) {
                                stack.push(entry.getChildren().iterator());
                            }
                            String file = entry.getHref();
                            if (file == null) {
                                continue;
                            }
                            int hashIndex = file.indexOf('#');
                            if (hashIndex != -1) {
                                file = file.substring(0, hashIndex);
                            }
                            if (files.contains(file)) {
                                // already indexed
                                // todo work out whether to just pull the section
                                continue;
                            }
                            Document document = new Document();
                            document.add(new Field("title", entry.getLabel(), Field.Store.YES,
                                    Field.Index.ANALYZED));
                            document.add(new Field("href", key + "/" + entry.getHref(), Field.Store.YES,
                                    Field.Index.NO));
                            JarEntry docEntry = jarFile.getJarEntry(file);
                            if (docEntry == null) {
                                // ignore missing file
                                continue;
                            }
                            InputStream inputStream = null;
                            try {
                                inputStream = jarFile.getInputStream(docEntry);
                                org.jsoup.nodes.Document docDoc = Jsoup.parse(IOUtils.toString(inputStream));
                                document.add(new Field("contents", docDoc.body().text(), Field.Store.NO,
                                        Field.Index.ANALYZED));
                                indexWriter.addDocument(document);
                            } finally {
                                IOUtils.closeQuietly(inputStream);
                            }
                        }
                    }
                }
            } catch (XMLStreamException e) {
                application.log("Could not parse " + path + " due to " + e.getMessage(), e);
            } catch (MalformedURLException e) {
                application.log("Could not parse " + path + " due to " + e.getMessage(), e);
            } catch (IOException e) {
                application.log("Could not parse " + path + " due to " + e.getMessage(), e);
            } finally {
                if (connection instanceof HttpURLConnection) {
                    // should never be the case, but we should try to be sure
                    ((HttpURLConnection) connection).disconnect();
                }
            }
        }
    }
    if (indexWriter != null) {
        try {
            indexWriter.close();
        } catch (IOException e) {
            application.log("Cannot create search index. Search will be unavailable.", e);
        }
        application.setAttribute("index", index);
    }

    application.setAttribute("toc", Collections.unmodifiableMap(contents));
    application.setAttribute("keywords", new Index(keywords));
    application.setAttribute("bundles", Collections.unmodifiableMap(bundles));
    application.setAttribute("analyzer", analyzer);
    application.setAttribute("contentsQueryParser", new QueryParser(LUCENE_VERSON, "contents", analyzer));
}

From source file:org.wso2.carbon.tomcat.internal.CarbonTomcat.java

/**
 * web-app addition/*from w w w  .  ja  va  2  s .  c  om*/
 *
 * @param host              virtual host for the webapp
 * @param contextPath       unique web-app context
 * @param webappFilePath    File location of the web-app
 * @param lifecycleListener tomcat life-cycle listener
 * @return {@link Context} object of the added web-app
 */
@Override
public Context addWebApp(Host host, String contextPath, String webappFilePath,
        LifecycleListener lifecycleListener) throws CarbonTomcatException {
    JarFile webappJarFile = null;
    JarEntry contextXmlFileEntry;
    Context ctx = null;
    boolean removeContext = false;
    try {
        Container child = host.findChild(contextPath);
        if (child != null) {
            if (ctx != null && host != null) {
                ctx.setRealm(null);
                try {
                    ctx.stop();
                } catch (LifecycleException x) {
                    log.error("Cannot stop context ", x);
                }
                host.removeChild(ctx);
            }
        }
        ctx = new StandardContext();
        ctx.setName(contextPath);
        ctx.setPath(contextPath);
        ctx.setDocBase(webappFilePath);
        ctx.setRealm(host.getRealm());
        //We dont need to init the DefaultWebXML since we maintain a web.xml file for a carbon server.
        // hence removing ctx.addLifecycleListener(new Tomcat.DefaultWebXmlListener()); code
        if (lifecycleListener != null) {
            ctx.addLifecycleListener(lifecycleListener);
        }
        SCIRegistrarContextConfig sciRegistrarContextConfig = new SCIRegistrarContextConfig();
        ctx.addLifecycleListener(sciRegistrarContextConfig);
        // Set global webXml to this context
        if (new File(globalWebXml).exists()) {
            sciRegistrarContextConfig.setDefaultWebXml(globalWebXml);
        } else {
            sciRegistrarContextConfig.setDefaultWebXml("org/apache/catalin/startup/NO_DEFAULT_XML");
        }

        if (new File(globalContextXml).exists()) {
            sciRegistrarContextConfig.setDefaultContextXml(globalContextXml);
        }

        File f = new File(webappFilePath);
        //During dir based webapp deployment
        if (f.isDirectory()) {
            File cf = new File(webappFilePath + File.separator + Constants.ApplicationContextXml);
            if (cf.exists()) {
                ctx.setConfigFile(cf.toURI().toURL());
            }
        } else {
            // Check for embedded contextXml file in this webapp
            webappJarFile = new JarFile(webappFilePath);
            contextXmlFileEntry = webappJarFile.getJarEntry(Constants.ApplicationContextXml);
            if (contextXmlFileEntry != null) {
                ctx.setConfigFile(new URL("jar:file:" + URLEncoder.encode(webappFilePath, "UTF-8") + "!/"
                        + Constants.ApplicationContextXml));
            }
        }
        if (ctx instanceof StandardContext) {
            ((StandardContext) ctx).setClearReferencesStopTimerThreads(true);
        }
        if (host == null) {
            host = this.getHost();
        }
        host.addChild(ctx);
        if (ctx.getState().equals(LifecycleState.STOPPED)) {
            ctx.setRealm(null);
            ctx.destroy();
            throw new Exception("Webapp failed to deploy, Lifecycle state is STOPPED");
        }
        if (log.isDebugEnabled()) {
            log.debug("Webapp context: " + ctx);
        }
    } catch (Exception e) {
        //since any exception can be thrown from Lifecycles, "Exception" is been caught.
        removeContext = true;
        throw new CarbonTomcatException("Webapp failed to deploy", e);
    } finally {
        if (removeContext && ctx != null && host != null) {
            ctx.setRealm(null);
            try {
                if (!ctx.getState().equals(LifecycleState.STOPPED)) {
                    ctx.stop();
                }
            } catch (LifecycleException e) {
                log.error("Cannot stop context ", e);
            }
            host.removeChild(ctx);
            log.error("Webapp " + ctx + " failed to deploy");
        }
        if (webappJarFile != null) {
            try {
                webappJarFile.close();
            } catch (Throwable t) {
                ExceptionUtils.handleThrowable(t);
            }
        }
    }
    return ctx;
}

From source file:org.xchain.tools.monitoring.MonitoringMojo.java

private void mergeWarMonitoringInfo(MonitoringInfo monitoringInfo, File file) throws MojoExecutionException {
    JarFile artifactJar = null;
    JarEntry monitoringInfoEntry = null;
    InputStream in = null;/*from   ww  w. jav a 2 s  . c  o m*/
    try {
        getLog().info("Getting monitoring info from file " + file.toString());
        artifactJar = new JarFile(file);
        monitoringInfoEntry = artifactJar.getJarEntry("WEB-INF/classes/META-INF/monitoring-info.xml");
        if (monitoringInfoEntry != null) {
            in = artifactJar.getInputStream(monitoringInfoEntry);

            // digest the xml file and get all of the entries.
            Digester digester = new Digester();
            digester.push(monitoringInfo);
            digester.addRuleSet(new MonitoringInfoRuleSet());
            WithDefaultsRulesWrapper wrapper = new WithDefaultsRulesWrapper(digester.getRules());
            wrapper.addDefault(new LoggingRule());
            digester.setRules(wrapper);
            digester.parse(in);
        } else {
            getLog().info("Monitoring info file not found in " + file.toString());
        }
    } catch (SAXException se) {
        throw new MojoExecutionException("Could not parse a monitoring-info.xml file.", se);
    } catch (IOException ioe) {
        throw new MojoExecutionException("Could not open jar file.", ioe);
    } finally {
        if (in != null) {
            try {
                in.close();
            } catch (IOException ioe) {
                getLog().warn("Could not close a jar entry input stream.", ioe);
            }
        }
        try {
            artifactJar.close();
        } catch (IOException ioe) {
            getLog().warn("Could not close a jar.", ioe);
        }
    }
}

From source file:ro.agrade.jira.qanda.utils.ResourceUtils.java

/**
 * Gets an entry in the JAR. It's your responsability to close the input
 * stream, as usually//from w w w . j ava2 s.c om
 * @param jar the jar file
 * @param jarEntryName the jar entry name
 * @return the input stream, or null if no entry is found in the file
 * @throws IOException if the jar is invalid
 */
public static InputStream getJarInputStream(JarFile jar, String jarEntryName) throws IOException {
    if (LOG.isDebugEnabled()) {
        LOG.debug(String.format("Searching in JAR >>%s<<, entry >>%s<<", jar.getName(), jarEntryName));
    }
    JarEntry je = jar.getJarEntry(jarEntryName);
    if (je == null) {
        if (LOG.isDebugEnabled()) {
            LOG.debug(String.format("No such entry [%s] in JAR >>%s<<", jarEntryName, jar.getName()));
        }
        return null;
    }
    return jar.getInputStream(je);
}

From source file:rubah.runtime.classloader.RubahClassloader.java

@Override
public InputStream getResourceAsStream(String name) {
    JarFile jarFile = null;
    try {/*  w  ww.j  a  v a2 s .  com*/
        VersionManager u = VersionManager.getInstance();
        Version v = u.getRunningVersion();
        File f = VersionManager.getInstance().getJarFile(v);
        jarFile = new JarFile(f);
        JarEntry entry = jarFile.getJarEntry(name);

        if (entry != null) {
            try {
                byte[] ret = IOUtils.toByteArray(jarFile.getInputStream(entry));
                return new ByteArrayInputStream(ret);
            } catch (IOException e) {
                throw new Error(e);
            }
        }

    } catch (IOException e) {
        throw new Error(e);
    } finally {
        if (jarFile != null)
            try {
                jarFile.close();
            } catch (IOException e) {
                // Don't care
            }
    }

    return super.getResourceAsStream(name);
}

From source file:streamflow.service.FrameworkService.java

public FrameworkConfig processFrameworkConfig(File tempFrameworkFile) {
    FrameworkConfig frameworkConfig = null;

    try {/*from  w  ww.j  a v a  2  s .  c om*/
        JarFile frameworkJarFile = new JarFile(tempFrameworkFile.getAbsoluteFile());

        JarEntry frameworkYamlEntry = frameworkJarFile.getJarEntry("STREAMFLOW-INF/framework.yml");

        JarEntry frameworkJsonEntry = frameworkJarFile.getJarEntry("STREAMFLOW-INF/framework.json");

        if (frameworkYamlEntry != null) {
            String frameworkYaml = IOUtils.toString(frameworkJarFile.getInputStream(frameworkYamlEntry));

            // Attempt to deserialize the inbuilt streams-framework.json 
            frameworkConfig = yamlMapper.readValue(frameworkYaml, FrameworkConfig.class);
        } else if (frameworkJsonEntry != null) {
            String frameworkJson = IOUtils.toString(frameworkJarFile.getInputStream(frameworkJsonEntry));

            // Attempt to deserialize the inbuilt streams-framework.json 
            frameworkConfig = jsonMapper.readValue(frameworkJson, FrameworkConfig.class);
        } else {
            frameworkConfig = processFrameworkAnnotations(tempFrameworkFile);
            if (frameworkConfig == null) {
                throw new EntityInvalidException(
                        "The framework configuration file was not found in the framework jar");
            }
        }
    } catch (IOException ex) {
        LOG.error("Error while loaded the framework configuration: ", ex);

        throw new EntityInvalidException("Error while loading the framework configuration: " + ex.getMessage());
    }

    return frameworkConfig;
}

From source file:streamflow.service.FrameworkService.java

public String loadFrameworkComponentIcon(ComponentConfig componentConfig, File frameworkFile) {
    String iconId = null;/*w  ww  . j  a v  a2 s  .  c o  m*/
    byte[] iconData = null;

    if (componentConfig.getIcon() != null) {
        try {
            JarFile frameworkJarFile = new JarFile(frameworkFile);

            JarEntry iconEntry = frameworkJarFile.getJarEntry(componentConfig.getIcon());
            if (iconEntry != null) {
                iconData = IOUtils.toByteArray(frameworkJarFile.getInputStream(iconEntry));
            }
        } catch (IOException ex) {
            LOG.error("Error occurred while loading the provided component icon: ", ex);
        }
    }

    if (iconData == null) {
        try {
            if (componentConfig.getType().equalsIgnoreCase(Component.STORM_SPOUT_TYPE)) {
                iconData = IOUtils.toByteArray(Thread.currentThread().getContextClassLoader()
                        .getResourceAsStream("icons/storm-spout.png"));
            } else if (componentConfig.getType().equalsIgnoreCase(Component.STORM_BOLT_TYPE)) {
                iconData = IOUtils.toByteArray(Thread.currentThread().getContextClassLoader()
                        .getResourceAsStream("icons/storm-bolt.png"));
            } else {
                iconData = IOUtils.toByteArray(Thread.currentThread().getContextClassLoader()
                        .getResourceAsStream("icons/storm-trident.png"));
            }
        } catch (IOException ex) {
            LOG.error("Error occurred while loading the default component icon: ", ex);
        }
    }

    if (iconData != null) {
        FileInfo iconFile = new FileInfo();
        iconFile.setFileName(iconFile.getFileName());
        iconFile.setFileType("image/png");
        iconFile.setFileSize(iconData.length);
        iconFile.setContentHash(DigestUtils.md5Hex(iconData));

        iconFile = fileService.saveFile(iconFile, iconData);

        iconId = iconFile.getId();
    }

    return iconId;
}

From source file:sx.blah.discord.modules.ModuleLoader.java

/**
 * Gets the jar file which contains a class with the given class name.
 *
 * @param files The jar files to search.
 * @param clazz The class name to search for.
 * @return The jar file which contains a class with the given class name (or null if one was not found).
 *///from  w  ww .  jav  a 2s  .  co  m
private static File findFileForClass(List<File> files, String clazz) {
    return files.stream().filter((file) -> {
        try {
            JarFile jarFile = new JarFile(file);
            return jarFile.getJarEntry(clazz.replaceAll("\\.", File.pathSeparator) + ".class") != null;
        } catch (IOException e) {
            return false;
        }
    }).findFirst().orElse(null);
}

From source file:tk.jomp16.plugin.PluginManager.java

@SuppressWarnings("ConstantConditions")
public void loadAll() throws Exception {
    File f = new File("plugins");

    for (File file : f.listFiles()) {
        if (file.getName().endsWith(".jar")) {
            System.out.println(file.getName());

            JarFile jarFile = new JarFile(file);
            JarEntry entry = jarFile.getJarEntry("plugin.json");

            if (entry != null) {
                PluginInfo pluginInfo = gson.fromJson(getPluginInfoInputStream(file), PluginInfo.class);
                Plugin plugin = new Plugin(pluginInfo, DigestUtils.md5Hex(new FileInputStream(file)),
                        pluginLoader.loadPluginEvent(file),
                        MainUI.isGui() ? pluginLoader.loadPluginUI(file) : null);

                plugins.add(plugin);//from w w w . j av a  2  s .c o m

                ircManager.registerPluginEvent(plugin);
            }
        }
    }
}

From source file:tk.jomp16.plugin.PluginManager.java

public boolean loadPlugin(String pluginName) throws Exception {
    File f = new File("plugins/" + pluginName + ".jar");

    if (f.exists()) {
        JarFile jarFile = new JarFile(f);
        JarEntry entry = jarFile.getJarEntry("plugin.json");

        if (entry != null) {
            PluginInfo pluginInfo = gson.fromJson(getPluginInfoInputStream(f), PluginInfo.class);
            Plugin plugin = new Plugin(pluginInfo, DigestUtils.md5Hex(new FileInputStream(f)),
                    pluginLoader.loadPluginEvent(f), MainUI.isGui() ? pluginLoader.loadPluginUI(f) : null);

            if (plugins.parallelStream()
                    .filter(plugin1 -> plugin1.getPluginInfo().getName()
                            .equals(plugin.getPluginInfo().getName()))
                    .count() != 0//  ww  w  .  j  av  a  2s. co m
                    && plugins.parallelStream()
                            .filter(plugin1 -> plugin1.getMd5sums().equals(plugin.getMd5sums())).count() != 0) {
                return false;
            }

            plugins.add(plugin);

            ircManager.registerPluginEvent(plugin);

            return true;
        }
    }

    return false;
}