Example usage for java.util.jar JarFile getManifest

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

Introduction

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

Prototype

public Manifest getManifest() throws IOException 

Source Link

Document

Returns the jar file manifest, or null if none.

Usage

From source file:org.apache.maven.shared.osgi.DefaultMaven2OsgiConverter.java

/**
 * Get the symbolic name as groupId + "." + artifactId, with the following exceptions
 * <ul>//  w ww.  j  a va 2s .  c  om
 * <li>if artifact.getFile is not null and the jar contains a OSGi Manifest with
 * Bundle-SymbolicName property then that value is returned</li>
 * <li>if groupId has only one section (no dots) and artifact.getFile is not null then the
 * first package name with classes is returned. eg. commons-logging:commons-logging ->
 * org.apache.commons.logging</li>
 * <li>if artifactId is equal to last section of groupId then groupId is returned. eg.
 * org.apache.maven:maven -> org.apache.maven</li>
 * <li>if artifactId starts with last section of groupId that portion is removed. eg.
 * org.apache.maven:maven-core -> org.apache.maven.core</li>
 * </ul>
 */
public String getBundleSymbolicName(Artifact artifact) {
    if ((artifact.getFile() != null) && artifact.getFile().isFile()) {
        Analyzer analyzer = new Analyzer();

        JarFile jar = null;
        try {
            jar = new JarFile(artifact.getFile(), false);

            if (jar.getManifest() != null) {
                String symbolicNameAttribute = jar.getManifest().getMainAttributes()
                        .getValue(Analyzer.BUNDLE_SYMBOLICNAME);
                Map bundleSymbolicNameHeader = analyzer.parseHeader(symbolicNameAttribute);

                Iterator it = bundleSymbolicNameHeader.keySet().iterator();
                if (it.hasNext()) {
                    return (String) it.next();
                }
            }
        } catch (IOException e) {
            throw new ManifestReadingException(
                    "Error reading manifest in jar " + artifact.getFile().getAbsolutePath(), e);
        } finally {
            if (jar != null) {
                try {
                    jar.close();
                } catch (IOException e) {
                }
            }
        }
    }

    int i = artifact.getGroupId().lastIndexOf('.');
    if ((i < 0) && (artifact.getFile() != null) && artifact.getFile().isFile()) {
        String groupIdFromPackage = getGroupIdFromPackage(artifact.getFile());
        if (groupIdFromPackage != null) {
            return groupIdFromPackage;
        }
    }
    String lastSection = artifact.getGroupId().substring(++i);
    if (artifact.getArtifactId().equals(lastSection)) {
        return artifact.getGroupId();
    }
    if (artifact.getArtifactId().startsWith(lastSection)) {
        String artifactId = artifact.getArtifactId().substring(lastSection.length());
        if (Character.isLetterOrDigit(artifactId.charAt(0))) {
            return getBundleSymbolicName(artifact.getGroupId(), artifactId);
        } else {
            return getBundleSymbolicName(artifact.getGroupId(), artifactId.substring(1));
        }
    }
    return getBundleSymbolicName(artifact.getGroupId(), artifact.getArtifactId());
}

From source file:com.liferay.ide.maven.core.util.DefaultMaven2OsgiConverter.java

/**
 * Get the symbolic name as groupId + "." + artifactId, with the following exceptions
 * <ul>/*from   www.ja v a  2s  .c om*/
 * <li>if artifact.getFile is not null and the jar contains a OSGi Manifest with
 * Bundle-SymbolicName property then that value is returned</li>
 * <li>if groupId has only one section (no dots) and artifact.getFile is not null then the
 * first package name with classes is returned. eg. commons-logging:commons-logging ->
 * org.apache.commons.logging</li>
 * <li>if artifactId is equal to last section of groupId then groupId is returned. eg.
 * org.apache.maven:maven -> org.apache.maven</li>
 * <li>if artifactId starts with last section of groupId that portion is removed. eg.
 * org.apache.maven:maven-core -> org.apache.maven.core</li>
 * </ul>
 */
public String getBundleSymbolicName(Artifact artifact) {
    if ((artifact.getFile() != null) && artifact.getFile().exists()) {
        Analyzer analyzer = new Analyzer();

        try {
            JarFile jar = new JarFile(artifact.getFile(), false);

            if (jar.getManifest() != null) {
                String symbolicNameAttribute = jar.getManifest().getMainAttributes()
                        .getValue(Analyzer.BUNDLE_SYMBOLICNAME);
                Map bundleSymbolicNameHeader = analyzer.parseHeader(symbolicNameAttribute);

                Iterator it = bundleSymbolicNameHeader.keySet().iterator();
                if (it.hasNext()) {
                    return (String) it.next();
                }
            }
        } catch (IOException e) {
            throw new RuntimeException("Error reading manifest in jar " + artifact.getFile().getAbsolutePath(),
                    e);
        }
    }

    int i = artifact.getGroupId().lastIndexOf('.');
    if ((i < 0) && (artifact.getFile() != null) && artifact.getFile().exists()) {
        String groupIdFromPackage = getGroupIdFromPackage(artifact.getFile());
        if (groupIdFromPackage != null) {
            return groupIdFromPackage;
        }
    }
    String lastSection = artifact.getGroupId().substring(++i);
    if (artifact.getArtifactId().equals(lastSection)) {
        return artifact.getGroupId();
    }
    if (artifact.getArtifactId().startsWith(lastSection)) {
        String artifactId = artifact.getArtifactId().substring(lastSection.length());
        if (Character.isLetterOrDigit(artifactId.charAt(0))) {
            return getBundleSymbolicName(artifact.getGroupId(), artifactId);
        } else {
            return getBundleSymbolicName(artifact.getGroupId(), artifactId.substring(1));
        }
    }
    return getBundleSymbolicName(artifact.getGroupId(), artifact.getArtifactId());
}

From source file:org.jahia.loganalyzer.internal.JahiaLogAnalyzerImpl.java

@Override
public void retrieveBuildInformation() {
    try {/*w  w w  . j  av a  2  s.co m*/
        URL urlToMavenPom = JahiaLogAnalyzerImpl.class.getClassLoader()
                .getResource("/META-INF/jahia-loganalyzer-marker.txt");
        if (urlToMavenPom != null) {
            URLConnection urlConnection = urlToMavenPom.openConnection();
            if (urlConnection instanceof JarURLConnection) {
                JarURLConnection conn = (JarURLConnection) urlConnection;
                JarFile jarFile = conn.getJarFile();
                Manifest manifest = jarFile.getManifest();
                Attributes attributes = manifest.getMainAttributes();
                buildNumber = attributes.getValue("Implementation-Build");
                version = attributes.getValue("Implementation-Version");
                String buildTimestampValue = attributes.getValue("Implementation-Timestamp");
                if (buildTimestampValue != null) {
                    try {
                        long buildTimestampTime = Long.parseLong(buildTimestampValue);
                        buildTimestamp = new Date(buildTimestampTime);
                    } catch (NumberFormatException nfe) {
                        nfe.printStackTrace();
                    }
                }
            }
        }
    } catch (IOException ioe) {
        log.error("Error while trying to retrieve build information", ioe);
    } catch (NumberFormatException nfe) {
        log.error("Error while trying to retrieve build information", nfe);
    }
}

From source file:org.wso2.carbon.server.extensions.DropinsBundleDeployer.java

/**
 * This method scan through the dropins directory and construct corresponding BundleInfoLine objects
 *
 * @param bundleFileList list of bundles available in the dropins directory.
 * @return An array of BundleInfoLine objects
 * @throws Exception in the event of an error
 *///from ww  w.  ja v a2s .  c  om
private BundleInfoLine[] getNewBundleInfoLines(File[] bundleFileList) throws Exception {
    ArrayList<BundleInfoLine> bundleInfoArray = new ArrayList<BundleInfoLine>();

    for (File file : bundleFileList) {
        JarFile jarFile = new JarFile(file.getAbsoluteFile());
        if (jarFile.getManifest() == null || jarFile.getManifest().getMainAttributes() == null) {
            log.error("Invalid Bundle found in the dropins directory: " + file.getName());
            continue;
        }

        String bundleSymbolicName = jarFile.getManifest().getMainAttributes()
                .getValue(LauncherConstants.BUNDLE_SYMBOLIC_NAME);
        String bundleVersion = jarFile.getManifest().getMainAttributes()
                .getValue(LauncherConstants.BUNDLE_VERSION);

        if (bundleSymbolicName == null || bundleVersion == null) {
            log.error("Required Bundle manifest headers do not exists: " + file.getAbsoluteFile());
            continue;
        } else {
            //BSN can have values like, Bundle-SymbolicName: com.example.acme;singleton:=true
            // refer - http://wiki.osgi.org/wiki/Bundle-SymbolicName for more details
            if (bundleSymbolicName.contains(";")) {
                bundleSymbolicName = bundleSymbolicName.split(";")[0];
            }
        }

        //Checking whether this bundle is a fragment or not.
        boolean isFragment = jarFile.getManifest().getMainAttributes()
                .getValue(LauncherConstants.FRAGMENT_HOST) != null;

        bundleInfoArray.add(new BundleInfoLine(bundleSymbolicName, bundleVersion,
                "../dropins/" + file.getName(), 4, isFragment));
    }
    return bundleInfoArray.toArray(new BundleInfoLine[bundleInfoArray.size()]);
}

From source file:generate.MapGenerateAction.java

@Override
public String execute() {

    String file_path = "/home/chanakya/NetBeansProjects/Concepto/UploadedFiles";
    try {//from   w w  w  .  j  a  v a2s .  c om
        File fileToCreate = new File(file_path, concept_map.getUploadedFileFileName());
        FileUtils.copyFile(concept_map.getUploadedFile(), fileToCreate);
    } catch (Throwable t) {
        System.out.println("E1: " + t.getMessage());
        return ERROR;
    }
    try {
        List<String> temp_text = FileUtils.readLines(concept_map.getUploadedFile());
        StringBuilder text = new StringBuilder();
        for (String s : temp_text) {
            text.append(s);
        }
        concept_map.setInput_text(text.toString());
    } catch (IOException e) {
        //e.printStackTrace();
        System.out.println("E2: " + e.getMessage());
        return ERROR;
    }
    String temp_filename = concept_map.getUploadedFileFileName().split("\\.(?=[^\\.]+$)")[0];
    temp_filename = temp_filename.trim();

    try {
        String temp = "java -jar /home/chanakya/NetBeansProjects/Concepto/src/java/generate/MajorCore.jar "
                + file_path + " " + temp_filename;
        System.out.println(temp);
        File jarfile = new File("/home/chanakya/NetBeansProjects/Concepto/src/java/generate/MajorCore.jar");
        JarFile jar = new JarFile(jarfile);
        Manifest manifest = jar.getManifest();
        Attributes attrs = manifest.getMainAttributes();
        String mainClassName = attrs.getValue(Attributes.Name.MAIN_CLASS);
        System.out.println(mainClassName);
        URL url = new URL("file", null, jarfile.getAbsolutePath());
        ClassLoader cl = new URLClassLoader(new URL[] { url });
        Class mainClass = cl.loadClass(mainClassName);
        Method mainMethod = mainClass.getMethod("main", new Class[] { String[].class });
        String[] args = new String[2];
        args[0] = file_path;
        args[1] = temp_filename;
        System.out.println(args[0]);
        System.out.println(args[1]);
        try {
            mainMethod.invoke(mainClass, new Object[] { args });
        } catch (InvocationTargetException e) {
            System.out.println("This is the exception: " + e.getTargetException().toString());
        }
    } catch (IllegalArgumentException | IllegalAccessException | NoSuchMethodException | ClassNotFoundException
            | IOException e) {
        System.out.println("E3: " + e.getMessage());
        return ERROR;
    }

    try {
        String temp2 = "java -jar /home/chanakya/NetBeansProjects/Concepto/src/java/generate/MajorCoreII.jar "
                + file_path + " " + temp_filename;
        System.out.println(temp2);
        File jarfile = new File("/home/chanakya/NetBeansProjects/Concepto/src/java/generate/MajorCoreII.jar");
        JarFile jar = new JarFile(jarfile);
        Manifest manifest = jar.getManifest();
        Attributes attrs = manifest.getMainAttributes();
        String mainClassName = attrs.getValue(Attributes.Name.MAIN_CLASS);
        System.out.println(mainClassName);
        URL url = new URL("file", null, jarfile.getAbsolutePath());
        ClassLoader cl = new URLClassLoader(new URL[] { url });
        Class mainClass = cl.loadClass(mainClassName);
        Method mainMethod = mainClass.getMethod("main", new Class[] { String[].class });
        String[] args = new String[2];
        args[0] = file_path;
        args[1] = temp_filename;
        mainMethod.invoke(mainClass, new Object[] { args });
    } catch (InvocationTargetException | IllegalArgumentException | IllegalAccessException
            | NoSuchMethodException | ClassNotFoundException | IOException e) {
        System.out.println("E4: " + e.getMessage());
        return ERROR;
    }

    String cmd = "python /home/chanakya/NetBeansProjects/Concepto/src/java/generate/add_to_graph.py \"/home/chanakya/NetBeansProjects/Concepto/UploadedFiles/"
            + temp_filename + "_OllieOutput.txt\"";
    String[] finalCommand;
    finalCommand = new String[3];
    finalCommand[0] = "/bin/sh";
    finalCommand[1] = "-c";
    finalCommand[2] = cmd;
    System.out.println("CMD: " + cmd);
    try {
        //ProcessBuilder builder = new ProcessBuilder(finalCommand);
        //builder.redirectErrorStream(true);
        //Process process = builder.start();
        Process process = Runtime.getRuntime().exec(finalCommand);
        int exitVal = process.waitFor();
        System.out.println("Process exitValue2: " + exitVal);
    } catch (Throwable t) {
        System.out.println("E5: " + t.getMessage());
        return ERROR;
    }

    cmd = "python /home/chanakya/NetBeansProjects/Concepto/src/java/generate/json_correct.py";
    finalCommand = new String[3];
    finalCommand[0] = "/bin/sh";
    finalCommand[1] = "-c";
    finalCommand[2] = cmd;

    try {
        //Process process = Runtime.getRuntime().exec(finalCommand);

        ProcessBuilder builder = new ProcessBuilder(finalCommand);
        // builder.redirectErrorStream(true);
        Process process = builder.start();
        int exitVal = process.waitFor();
        System.out.println("Process exitValue3: " + exitVal);
    } catch (Throwable t) {
        System.out.println("E6: " + t.getMessage());
        return ERROR;
    }

    try {
        List<String> temp_text_1 = FileUtils
                .readLines(FileUtils.getFile("/home/chanakya/NetBeansProjects/Concepto/web", "new_graph.json"));
        StringBuilder text_1 = new StringBuilder();
        for (String s : temp_text_1) {
            text_1.append(s);
        }
        concept_map.setOutput_text(text_1.toString());
    } catch (IOException e) {
        System.out.println("E7: " + e.getMessage());
        return ERROR;
    }
    Random rand = new Random();
    int unique_id = rand.nextInt(99999999);
    System.out.println("Going In DB");
    try {
        MongoClient mongo = new MongoClient();
        DB db = mongo.getDB("Major");
        DBCollection collection = db.getCollection("ConceptMap");
        BasicDBObject document = new BasicDBObject();
        document.append("InputText", concept_map.getInput_text());
        document.append("OutputText", concept_map.getOutput_text());
        document.append("ChapterName", concept_map.getChapter_name());
        document.append("ChapterNumber", concept_map.getChapter_number());
        document.append("SectionName", concept_map.getSection_name());
        document.append("SectionNumber", concept_map.getSection_number());
        document.append("UniqueID", Integer.toString(unique_id));
        collection.insert(document);
        //collection.save(document);
    } catch (MongoException e) {
        System.out.println("E8: " + e.getMessage());
        return ERROR;
    } catch (UnknownHostException ex) {
        Logger.getLogger(MapGenerateAction.class.getName()).log(Level.SEVERE, null, ex);
        System.out.println("E9");
        return ERROR;
    }
    System.out.println("Out DB");
    return SUCCESS;
}

From source file:org.apache.struts2.osgi.host.BaseOsgiHost.java

/**
 * Gets the version used to export the packages. it tries to get it from MANIFEST.MF, or the file name
 *///from w  w  w  .  j a  va  2  s.  c  om
protected String getVersion(URL url) {
    if ("jar".equals(url.getProtocol())) {
        try {
            FileManager fileManager = ServletActionContext.getContext().getInstance(FileManagerFactory.class)
                    .getFileManager();
            JarFile jarFile = new JarFile(new File(fileManager.normalizeToFileProtocol(url).toURI()));
            Manifest manifest = jarFile.getManifest();
            if (manifest != null) {
                String version = manifest.getMainAttributes().getValue("Bundle-Version");
                if (StringUtils.isNotBlank(version)) {
                    return getVersionFromString(version);
                }
            } else {
                //try to get the version from the file name
                return getVersionFromString(jarFile.getName());
            }
        } catch (Exception e) {
            if (LOG.isErrorEnabled()) {
                LOG.error("Unable to extract version from [#0], defaulting to '1.0.0'", url.toExternalForm());
            }
        }
    }
    return "1.0.0";
}

From source file:com.twosigma.beaker.autocomplete.ClasspathScanner.java

private boolean findClasses(File root, File file, boolean includeJars) {
    if (file != null && file.isDirectory()) {
        File[] lf = file.listFiles();
        if (lf != null)
            for (File child : lf) {
                if (!findClasses(root, child, includeJars)) {
                    return false;
                }//  w  w w.ja  v  a  2  s  .c  o m
            }
    } else {
        if (file.getName().toLowerCase().endsWith(".jar") && includeJars) {
            JarFile jar = null;
            try {
                jar = new JarFile(file);
            } catch (Exception ex) {
            }
            if (jar != null) {
                try {
                    Manifest mf = jar.getManifest();
                    if (mf != null) {
                        String cp = mf.getMainAttributes().getValue("Class-Path");
                        if (StringUtils.isNotEmpty(cp)) {
                            for (String fn : cp.split(" ")) {
                                File child = new File(
                                        file.getParent() + System.getProperty("file.separator") + fn);
                                if (child.getAbsolutePath().equals(jar.getName())) {
                                    continue; //skip bad jars, that contain references to themselves in MANIFEST.MF
                                }
                                if (child.exists()) {
                                    if (!findClasses(root, child, includeJars)) {
                                        return false;
                                    }
                                }
                            }
                        }
                    }
                } catch (IOException e) {
                }

                Enumeration<JarEntry> entries = jar.entries();
                while (entries.hasMoreElements()) {
                    JarEntry entry = entries.nextElement();
                    String name = entry.getName();
                    int extIndex = name.lastIndexOf(".class");
                    if (extIndex > 0 && !name.contains("$")) {
                        String cname = name.substring(0, extIndex).replace("/", ".");
                        int pIndex = cname.lastIndexOf('.');
                        if (pIndex > 0) {
                            String pname = cname.substring(0, pIndex);
                            cname = cname.substring(pIndex + 1);
                            if (!packages.containsKey(pname))
                                packages.put(pname, new ArrayList<String>());
                            packages.get(pname).add(cname);
                        }
                    }
                }
            }
        } else if (file.getName().toLowerCase().endsWith(".class")) {
            String cname = createClassName(root, file);
            if (!cname.contains("$")) {
                int pIndex = cname.lastIndexOf('.');
                if (pIndex > 0) {
                    String pname = cname.substring(0, pIndex + 1);
                    cname = cname.substring(pIndex);
                    if (!packages.containsKey(pname))
                        packages.put(pname, new ArrayList<String>());
                    packages.get(pname).add(cname);
                }
            }
        } else {
            examineFile(root, file);
        }
    }

    return true;
}

From source file:com.twosigma.beakerx.autocomplete.ClasspathScanner.java

private boolean findClasses(File root, File file, boolean includeJars) {
    if (file != null && file.isDirectory()) {
        File[] lf = file.listFiles();
        if (lf != null)
            for (File child : lf) {
                if (!findClasses(root, child, includeJars)) {
                    return false;
                }//w  ww .  j av a 2s  .  com
            }
    } else {
        if (file.getName().toLowerCase().endsWith(".jar") && includeJars) {
            JarFile jar = null;
            try {
                jar = new JarFile(file);
            } catch (Exception ex) {
            }
            if (jar != null) {
                try {
                    Manifest mf = jar.getManifest();
                    if (mf != null) {
                        String cp = mf.getMainAttributes().getValue("Class-Path");
                        if (StringUtils.isNotEmpty(cp)) {
                            for (String fn : cp.split(" ")) {
                                if (!fn.equals(".")) {
                                    File child = new File(
                                            file.getParent() + System.getProperty("file.separator") + fn);
                                    if (child.getAbsolutePath().equals(jar.getName())) {
                                        continue; //skip bad jars, that contain references to themselves in MANIFEST.MF
                                    }
                                    if (child.exists()) {
                                        if (!findClasses(root, child, includeJars)) {
                                            return false;
                                        }
                                    }
                                }
                            }
                        }
                    }
                } catch (IOException e) {
                }

                Enumeration<JarEntry> entries = jar.entries();
                while (entries.hasMoreElements()) {
                    JarEntry entry = entries.nextElement();
                    String name = entry.getName();
                    int extIndex = name.lastIndexOf(".class");
                    if (extIndex > 0 && !name.contains("$")) {
                        String cname = name.substring(0, extIndex).replace("/", ".");
                        int pIndex = cname.lastIndexOf('.');
                        if (pIndex > 0) {
                            String pname = cname.substring(0, pIndex);
                            cname = cname.substring(pIndex + 1);
                            if (!packages.containsKey(pname))
                                packages.put(pname, new ArrayList<String>());
                            packages.get(pname).add(cname);
                        }
                    }
                }
            }
        } else if (file.getName().toLowerCase().endsWith(".class")) {
            String cname = createClassName(root, file);
            if (!cname.contains("$")) {
                int pIndex = cname.lastIndexOf('.');
                if (pIndex > 0) {
                    String pname = cname.substring(0, pIndex + 1);
                    cname = cname.substring(pIndex);
                    if (!packages.containsKey(pname))
                        packages.put(pname, new ArrayList<String>());
                    packages.get(pname).add(cname);
                }
            }
        } else {
            examineFile(root, file);
        }
    }

    return true;
}

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;// w w w.j a v  a2  s . 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:com.impetus.kundera.classreading.ClasspathReader.java

/**
 * Scan class resource in the provided urls with the additional Class-Path
 * of each jar checking//from  w w  w.  j a  v a  2  s. co m
 * 
 * @param classRelativePath
 *            relative path to a class resource
 * @param urls
 *            urls to be checked
 * @return list of class path included in the base package
 */
private URL[] findResourcesInUrls(String classRelativePath, URL[] urls) {
    List<URL> list = new ArrayList<URL>();
    for (URL url : urls) {
        if (AllowedProtocol.isValidProtocol(url.getProtocol().toUpperCase())
                && url.getPath().endsWith(".jar")) {
            try {
                JarFile jarFile = new JarFile(URLDecoder.decode(url.getFile(), Constants.CHARSET_UTF8));

                // Checking the dependencies of this jar file
                Manifest manifest = jarFile.getManifest();
                if (manifest != null) {
                    String classPath = manifest.getMainAttributes().getValue("Class-Path");
                    // Scan all entries in the classpath if they are
                    // specified in the jar
                    if (!StringUtils.isEmpty(classPath)) {
                        List<URL> subList = new ArrayList<URL>();
                        for (String cpEntry : classPath.split(" ")) {
                            try {
                                subList.add(new URL(cpEntry));
                            } catch (MalformedURLException e) {
                                URL subResources = ClasspathReader.class.getClassLoader().getResource(cpEntry);
                                if (subResources != null) {
                                    subList.add(subResources);
                                }
                                // logger.warn("Incorrect URL in the classpath of a jar file ["
                                // + url.toString()
                                // + "]: " + cpEntry);
                            }
                        }
                        list.addAll(Arrays.asList(findResourcesInUrls(classRelativePath,
                                subList.toArray(new URL[subList.size()]))));
                    }
                }
                JarEntry present = jarFile.getJarEntry(classRelativePath + ".class");
                if (present != null) {
                    list.add(url);
                }
            } catch (IOException e) {
                logger.warn("Error during loading from context , Caused by:" + e.getMessage());
            }

        } else if (url.getPath().endsWith("/")) {
            File file = new File(url.getPath() + classRelativePath + ".class");
            if (file.exists()) {
                try {
                    list.add(file.toURL());
                } catch (MalformedURLException e) {
                    throw new ResourceReadingException(e);
                }
            }
        }

    }
    return list.toArray(new URL[list.size()]);
}