Search in sources :

Example 36 with Analyzer

use of aQute.bnd.osgi.Analyzer in project bnd by bndtools.

the class BaselineCommands method _schema.

/**
	 * Create a schema of a set of jars outling the packages and their versions.
	 * This will create a list of packages with multiple versions, link to their
	 * specifications, and the deltas between versions.
	 * 
	 * <pre>
	 *  bnd package schema
	 * <file.jar>*
	 * </pre>
	 * 
	 * @param opts
	 * @throws Exception
	 */
public void _schema(schemaOptions opts) throws Exception {
    MultiMap<String, PSpec> map = new MultiMap<String, PSpec>();
    Tag top = new Tag("jschema");
    int n = 1000;
    for (String spec : opts._arguments()) {
        File f = bnd.getFile(spec);
        if (!f.isFile()) {
            bnd.messages.NoSuchFile_(f);
        } else {
            // For each specification jar we found
            logger.debug("spec {}", f);
            // spec
            Jar jar = new Jar(f);
            Manifest m = jar.getManifest();
            Attributes main = m.getMainAttributes();
            Tag specTag = new Tag(top, "specification");
            specTag.addAttribute("jar", spec);
            specTag.addAttribute("name", main.getValue("Specification-Name"));
            specTag.addAttribute("title", main.getValue("Specification-Title"));
            specTag.addAttribute("jsr", main.getValue("Specification-JSR"));
            specTag.addAttribute("url", main.getValue("Specification-URL"));
            specTag.addAttribute("version", main.getValue("Specification-Version"));
            specTag.addAttribute("vendor", main.getValue("Specification-Vendor"));
            specTag.addAttribute("id", n);
            specTag.addContent(main.getValue(Constants.BUNDLE_DESCRIPTION));
            Parameters exports = OSGiHeader.parseHeader(m.getMainAttributes().getValue(Constants.EXPORT_PACKAGE));
            // Create a map with versions. Ensure import ranges overwrite
            // the
            // exported versions
            Parameters versions = new Parameters();
            versions.putAll(exports);
            versions.putAll(OSGiHeader.parseHeader(m.getMainAttributes().getValue(Constants.IMPORT_PACKAGE)));
            Analyzer analyzer = new Analyzer();
            analyzer.setJar(jar);
            analyzer.analyze();
            Tree tree = differ.tree(analyzer);
            for (Entry<String, Attrs> entry : exports.entrySet()) {
                // For each exported package in the specification JAR
                Attrs attrs = entry.getValue();
                String packageName = entry.getKey();
                PackageRef packageRef = analyzer.getPackageRef(packageName);
                String version = attrs.get(Constants.VERSION_ATTRIBUTE);
                PSpec pspec = new PSpec();
                pspec.packageName = packageName;
                pspec.version = new Version(version);
                pspec.id = n;
                pspec.attrs = attrs;
                pspec.tree = tree;
                Collection<PackageRef> uses = analyzer.getUses().get(packageRef);
                if (uses != null) {
                    for (PackageRef x : uses) {
                        if (x.isJava())
                            continue;
                        String imp = x.getFQN();
                        if (imp.equals(packageName))
                            continue;
                        String v = null;
                        if (versions.containsKey(imp))
                            v = versions.get(imp).get(Constants.VERSION_ATTRIBUTE);
                        pspec.uses.put(imp, v);
                    }
                }
                map.add(packageName, pspec);
            }
            jar.close();
            n++;
        }
    }
    // We now gather all the information about all packages in the map.
    // Next phase is generating the XML. Sorting the packages is
    // important because XSLT is brain dead.
    SortedList<String> names = new SortedList<String>(map.keySet());
    Tag packagesTag = new Tag(top, "packages");
    Tag baselineTag = new Tag(top, "baseline");
    for (String pname : names) {
        // For each distinct package name
        SortedList<PSpec> specs = new SortedList<PSpec>(map.get(pname));
        PSpec older = null;
        Parameters olderExport = null;
        for (PSpec newer : specs) {
            // For each package in the total set
            Tag pack = new Tag(packagesTag, "package");
            pack.addAttribute("name", newer.packageName);
            pack.addAttribute("version", newer.version);
            pack.addAttribute("spec", newer.id);
            Parameters newerExport = new Parameters();
            newerExport.put(pname, newer.attrs);
            if (older != null) {
                String compareId = newer.packageName + "-" + newer.id + "-" + older.id;
                pack.addAttribute("delta", compareId);
                logger.debug(" newer={} older={}", newerExport, olderExport);
                Set<Info> infos = baseline.baseline(newer.tree, newerExport, older.tree, olderExport, new Instructions(pname));
                for (Info info : infos) {
                    Tag tag = getTag(info);
                    tag.addAttribute("id", compareId);
                    tag.addAttribute("newerSpec", newer.id);
                    tag.addAttribute("olderSpec", older.id);
                    baselineTag.addContent(tag);
                }
                older.tree = null;
                older.attrs = null;
                older = newer;
            }
            for (Entry<String, String> uses : newer.uses.entrySet()) {
                Tag reference = new Tag(pack, "import");
                reference.addAttribute("name", uses.getKey());
                reference.addAttribute("version", uses.getValue());
            }
            older = newer;
            olderExport = newerExport;
        }
    }
    String o = opts.output("schema.xml");
    File of = bnd.getFile(o);
    File pof = of.getParentFile();
    IO.mkdirs(pof);
    try (PrintWriter pw = IO.writer(of, UTF_8)) {
        pw.print("<?xml version='1.0' encoding='UTF-8'?>\n");
        top.print(0, pw);
    }
    if (opts.xsl() != null) {
        URL home = bnd.getBase().toURI().toURL();
        URL xslt = new URL(home, opts.xsl());
        String path = of.getAbsolutePath();
        if (path.endsWith(".xml"))
            path = path.substring(0, path.length() - 4);
        path = path + ".html";
        File html = new File(path);
        logger.debug("xslt {} {} {} {}", xslt, of, html, html.exists());
        try (OutputStream out = IO.outputStream(html);
            InputStream in = xslt.openStream()) {
            Transformer transformer = transformerFactory.newTransformer(new StreamSource(in));
            transformer.transform(new StreamSource(of), new StreamResult(out));
        }
    }
}
Also used : Transformer(javax.xml.transform.Transformer) OutputStream(java.io.OutputStream) Attributes(java.util.jar.Attributes) Attrs(aQute.bnd.header.Attrs) SortedList(aQute.lib.collections.SortedList) Analyzer(aQute.bnd.osgi.Analyzer) URL(java.net.URL) MultiMap(aQute.lib.collections.MultiMap) Version(aQute.bnd.version.Version) Tree(aQute.bnd.service.diff.Tree) PackageRef(aQute.bnd.osgi.Descriptors.PackageRef) PrintWriter(java.io.PrintWriter) Parameters(aQute.bnd.header.Parameters) StreamResult(javax.xml.transform.stream.StreamResult) InputStream(java.io.InputStream) StreamSource(javax.xml.transform.stream.StreamSource) Instructions(aQute.bnd.osgi.Instructions) Manifest(java.util.jar.Manifest) Info(aQute.bnd.differ.Baseline.Info) BundleInfo(aQute.bnd.differ.Baseline.BundleInfo) Jar(aQute.bnd.osgi.Jar) Tag(aQute.lib.tag.Tag) File(java.io.File)

Example 37 with Analyzer

use of aQute.bnd.osgi.Analyzer in project bnd by bndtools.

the class WrapTask method execute.

@Override
public void execute() throws BuildException {
    boolean failed = false;
    try {
        if (jars == null)
            throw new BuildException("No files set", getLocation());
        if (output != null && jars.size() > 1 && !output.isDirectory()) {
            throw new BuildException("Multiple jars must be wrapped but the output given is not a directory " + output, getLocation());
        }
        if (definitions != null && jars.size() > 1 && !definitions.isDirectory()) {
            throw new BuildException("Multiple jars must be wrapped but the definitions parameters is not a directory " + definitions, getLocation());
        }
        for (File file : jars) {
            if (!file.isFile()) {
                failed = true;
                System.err.println("Non existent file to wrap " + file);
                continue;
            }
            try (Analyzer wrapper = new Analyzer()) {
                wrapper.setPedantic(isPedantic());
                wrapper.setTrace(isTrace());
                wrapper.setExceptions(exceptions);
                wrapper.setBase(getProject().getBaseDir());
                wrapper.addClasspath(classpath);
                if (failok)
                    wrapper.setFailOk(true);
                wrapper.setJar(file);
                wrapper.addProperties(getProject().getProperties());
                wrapper.setDefaults(bsn, version);
                File outputFile = wrapper.getOutputFile(output == null ? null : output.getAbsolutePath());
                if (definitions != null) {
                    File properties = definitions;
                    if (properties.isDirectory()) {
                        String pfile = wrapper.replaceExtension(outputFile.getName(), Constants.DEFAULT_JAR_EXTENSION, Constants.DEFAULT_BND_EXTENSION);
                        properties = new File(definitions, pfile);
                    }
                    if (properties.isFile()) {
                        wrapper.setProperties(properties);
                    }
                }
                Manifest manifest = wrapper.calcManifest();
                if (wrapper.isOk()) {
                    wrapper.getJar().setManifest(manifest);
                    boolean saved = wrapper.save(outputFile, force);
                    log(String.format("%30s %6d %s%n", wrapper.getJar().getBsn() + "-" + wrapper.getJar().getVersion(), outputFile.length(), saved ? "" : "(not modified)"));
                }
                failed |= report(wrapper);
            }
        }
    } catch (Exception e) {
        if (exceptions)
            e.printStackTrace();
        if (!failok)
            throw new BuildException("Failed to build jar file: " + e, getLocation());
    }
    if (failed && !failok)
        throw new BuildException("Failed to wrap jar file", getLocation());
}
Also used : BuildException(org.apache.tools.ant.BuildException) Analyzer(aQute.bnd.osgi.Analyzer) Manifest(java.util.jar.Manifest) File(java.io.File) BuildException(org.apache.tools.ant.BuildException)

Example 38 with Analyzer

use of aQute.bnd.osgi.Analyzer in project bnd by bndtools.

the class bnd method _wrap.

/**
	 * Wrap a jar to a bundle.
	 * 
	 * @throws Exception
	 */
@Description("Wrap a jar")
public void _wrap(wrapOptions options) throws Exception {
    List<File> classpath = Create.list();
    File properties = getBase();
    if (options.properties() != null) {
        properties = getFile(options.properties());
    }
    if (options.classpath() != null)
        for (String cp : options.classpath()) {
            classpath.add(getFile(cp));
        }
    for (String j : options._arguments()) {
        File file = getFile(j);
        if (!file.isFile()) {
            error("File does not exist %s", file);
            continue;
        }
        try (Analyzer wrapper = new Analyzer(this)) {
            wrapper.use(this);
            for (File f : classpath) wrapper.addClasspath(f);
            wrapper.setJar(file);
            File outputFile = wrapper.getOutputFile(options.output());
            if (outputFile.getCanonicalFile().equals(file.getCanonicalFile())) {
                // #267: CommandLine wrap deletes target even if file equals
                // source
                error("Output file %s and source file %s are the same file, they must be different", outputFile, file);
                return;
            }
            IO.delete(outputFile);
            String stem = file.getName();
            if (stem.endsWith(".jar"))
                stem = stem.substring(0, stem.length() - 4) + ".bnd";
            File p = getPropertiesFile(properties, file, stem);
            if (p == null) {
                wrapper.setImportPackage("*;resolution:=optional");
                wrapper.setExportPackage("*");
                warning("Using defaults for wrap, which means no export versions");
            } else if (p.isFile())
                wrapper.setProperties(p);
            else {
                error("No valid property file: %s", p);
            }
            if (options.bsn() != null)
                wrapper.setBundleSymbolicName(options.bsn());
            if (options.version() != null)
                wrapper.setBundleVersion(options.version());
            Manifest m = wrapper.calcManifest();
            if (wrapper.isOk()) {
                wrapper.getJar().setManifest(m);
                wrapper.save(outputFile, options.force());
            }
            getInfo(wrapper, file.toString());
        }
    }
}
Also used : Analyzer(aQute.bnd.osgi.Analyzer) Manifest(java.util.jar.Manifest) PomFromManifest(aQute.bnd.maven.PomFromManifest) File(java.io.File) Description(aQute.lib.getopt.Description)

Example 39 with Analyzer

use of aQute.bnd.osgi.Analyzer in project bnd by bndtools.

the class bnd method _version.

/**
	 * Show the version of this bnd
	 * 
	 * @throws IOException
	 */
@Description("Show version information about bnd")
public void _version(versionOptions o) throws IOException {
    if (!o.xtra()) {
        Analyzer a = new Analyzer();
        out.println(a.getBndVersion());
        a.close();
        return;
    }
    Enumeration<URL> e = getClass().getClassLoader().getResources("META-INF/MANIFEST.MF");
    while (e.hasMoreElements()) {
        URL u = e.nextElement();
        Manifest m = new Manifest(u.openStream());
        String bsn = m.getMainAttributes().getValue(Constants.BUNDLE_SYMBOLICNAME);
        if (bsn != null && bsn.equals("biz.aQute.bnd")) {
            Attributes attrs = m.getMainAttributes();
            long lastModified = 0;
            try {
                lastModified = Long.parseLong(attrs.getValue(Constants.BND_LASTMODIFIED));
            } catch (Exception ee) {
            // Ignore
            }
            out.printf("%-40s %s\n", "Version", attrs.getValue(Constants.BUNDLE_VERSION));
            if (lastModified > 0)
                out.printf("%-40s %s\n", "From", new Date(lastModified));
            Parameters p = OSGiHeader.parseHeader(attrs.getValue(Constants.BUNDLE_LICENSE));
            for (String l : p.keySet()) out.printf("%-40s %s\n", "License", p.get(l).get("description"));
            out.printf("%-40s %s\n", "Copyright", attrs.getValue(Constants.BUNDLE_COPYRIGHT));
            out.printf("%-40s %s\n", "Git-SHA", attrs.getValue("Git-SHA"));
            out.printf("%-40s %s\n", "Git-Descriptor", attrs.getValue("Git-Descriptor"));
            out.printf("%-40s %s\n", "Sources", attrs.getValue("Bundle-SCM"));
            return;
        }
    }
    error("Could not locate version");
}
Also used : Parameters(aQute.bnd.header.Parameters) Attributes(java.util.jar.Attributes) Analyzer(aQute.bnd.osgi.Analyzer) Manifest(java.util.jar.Manifest) PomFromManifest(aQute.bnd.maven.PomFromManifest) URL(java.net.URL) InvocationTargetException(java.lang.reflect.InvocationTargetException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) IOException(java.io.IOException) XPathExpressionException(javax.xml.xpath.XPathExpressionException) ZipException(java.util.zip.ZipException) Date(java.util.Date) Description(aQute.lib.getopt.Description)

Example 40 with Analyzer

use of aQute.bnd.osgi.Analyzer in project bnd by bndtools.

the class AnalyzerTest method testDsNoExport.

public static void testDsNoExport() throws Exception {
    Properties base = new Properties();
    base.put(Analyzer.IMPORT_PACKAGE, "*");
    base.put(Analyzer.EXPORT_PACKAGE, "!*");
    File tmp = IO.getFile("jar/ds.jar");
    try (Analyzer h = new Analyzer()) {
        h.setJar(tmp);
        h.setProperties(base);
        h.calcManifest().write(System.err);
        assertPresent(h.getImports().keySet(), "org.osgi.service.packageadmin, " + "org.xml.sax, org.osgi.service.log," + " javax.xml.parsers," + " org.xml.sax.helpers," + " org.osgi.framework," + " org.eclipse.osgi.util," + " org.osgi.util.tracker, " + "org.osgi.service.component, " + "org.osgi.service.cm");
        assertNotPresent(h.getExports().keySet(), "org.eclipse.equinox.ds.parser, " + "org.eclipse.equinox.ds.tracker, " + "org.eclipse.equinox.ds, " + "org.eclipse.equinox.ds.instance, " + "org.eclipse.equinox.ds.model, " + "org.eclipse.equinox.ds.resolver, " + "org.eclipse.equinox.ds.workqueue");
        System.err.println(h.getUnreachable());
    }
}
Also used : Properties(java.util.Properties) Analyzer(aQute.bnd.osgi.Analyzer) File(java.io.File)

Aggregations

Analyzer (aQute.bnd.osgi.Analyzer)55 File (java.io.File)21 Clazz (aQute.bnd.osgi.Clazz)14 Properties (java.util.Properties)14 Manifest (java.util.jar.Manifest)12 Jar (aQute.bnd.osgi.Jar)11 PackageRef (aQute.bnd.osgi.Descriptors.PackageRef)9 ClassDataCollector (aQute.bnd.osgi.ClassDataCollector)8 Parameters (aQute.bnd.header.Parameters)7 FileResource (aQute.bnd.osgi.FileResource)7 FileInputStream (java.io.FileInputStream)6 TypeRef (aQute.bnd.osgi.Descriptors.TypeRef)5 Description (aQute.lib.getopt.Description)5 Attrs (aQute.bnd.header.Attrs)4 Descriptors (aQute.bnd.osgi.Descriptors)4 Packages (aQute.bnd.osgi.Packages)4 Resource (aQute.bnd.osgi.Resource)4 Map (java.util.Map)4 PomFromManifest (aQute.bnd.maven.PomFromManifest)3 Domain (aQute.bnd.osgi.Domain)3