Search in sources :

Example 1 with Instruction

use of aQute.bnd.osgi.Instruction in project sling by apache.

the class ConfigurationClassScannerPlugin method getClassesWithAnnotation.

/**
     * Get all classes that implement the given annotation via bnd Analyzer.
     * @param analyzer Analyzer
     * @param annotation Annotation
     * @return Class names
     */
private Collection<String> getClassesWithAnnotation(String annotationClassName, Analyzer analyzer) {
    SortedSet<String> classNames = new TreeSet<>();
    Collection<Clazz> clazzes = analyzer.getClassspace().values();
    Instruction instruction = new Instruction(annotationClassName);
    try {
        for (Clazz clazz : clazzes) {
            if (clazz.isAnnotation() && clazz.is(QUERY.ANNOTATED, instruction, analyzer)) {
                classNames.add(clazz.getClassName().getFQN());
            }
        }
    } catch (Exception ex) {
        reporter.exception(ex, "Error querying for classes with annotation: " + annotationClassName);
    }
    return classNames;
}
Also used : TreeSet(java.util.TreeSet) Clazz(aQute.bnd.osgi.Clazz) Instruction(aQute.bnd.osgi.Instruction)

Example 2 with Instruction

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

the class Profiles method _create.

public void _create(CreateOptions options) throws Exception {
    Builder b = new Builder();
    bnd.addClose(b);
    b.setBase(bnd.getBase());
    if (options.properties() != null) {
        for (String propertyFile : options.properties()) {
            File pf = bnd.getFile(propertyFile);
            b.addProperties(pf);
        }
    }
    if (options.bsn() != null)
        b.setProperty(Constants.BUNDLE_SYMBOLICNAME, options.bsn());
    if (options.version() != null)
        b.setProperty(Constants.BUNDLE_VERSION, options.version().toString());
    Instructions match = options.match();
    Parameters packages = new Parameters();
    Parameters capabilities = new Parameters();
    Collection<String> paths = new ArrayList<String>(new Parameters(b.getProperty("-paths"), bnd).keySet());
    if (paths.isEmpty())
        paths = options._arguments();
    logger.debug("input {}", paths);
    ResourceBuilder pb = new ResourceBuilder();
    for (String root : paths) {
        File f = bnd.getFile(root);
        if (!f.exists()) {
            error("could not find %s", f);
        } else {
            Glob g = options.extension();
            if (g == null)
                g = new Glob("*.jar");
            Collection<File> files = IO.tree(f, "*.jar");
            logger.debug("will profile {}", files);
            for (File file : files) {
                Domain domain = Domain.domain(file);
                if (domain == null) {
                    error("Not a bundle because no manifest %s", file);
                    continue;
                }
                String bsn = domain.getBundleSymbolicName().getKey();
                if (bsn == null) {
                    error("Not a bundle because no manifest %s", file);
                    continue;
                }
                if (match != null) {
                    Instruction instr = match.finder(bsn);
                    if (instr == null || instr.isNegated()) {
                        logger.debug("skipped {} because of non matching bsn {}", file, bsn);
                        continue;
                    }
                }
                Parameters eps = domain.getExportPackage();
                Parameters pcs = domain.getProvideCapability();
                logger.debug("parse {}:\ncaps: {}\npac: {}\n", file, pcs, eps);
                packages.mergeWith(eps, false);
                capabilities.mergeWith(pcs, false);
            }
        }
    }
    b.setProperty(Constants.PROVIDE_CAPABILITY, capabilities.toString());
    b.setProperty(Constants.EXPORT_PACKAGE, packages.toString());
    logger.debug("Found {} packages and {} capabilities", packages.size(), capabilities.size());
    Jar jar = b.build();
    File f = b.getOutputFile(options.output());
    logger.debug("Saving as {}", f);
    jar.write(f);
}
Also used : ResourceBuilder(aQute.bnd.osgi.resource.ResourceBuilder) Parameters(aQute.bnd.header.Parameters) ResourceBuilder(aQute.bnd.osgi.resource.ResourceBuilder) Builder(aQute.bnd.osgi.Builder) ArrayList(java.util.ArrayList) Instructions(aQute.bnd.osgi.Instructions) Instruction(aQute.bnd.osgi.Instruction) Glob(aQute.libg.glob.Glob) Jar(aQute.bnd.osgi.Jar) Domain(aQute.bnd.osgi.Domain) File(java.io.File)

Example 3 with Instruction

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

the class ProjectBuilder method getBaselineJar.

/**
	 * This method attempts to find the baseline jar for the current project. It
	 * reads the -baseline property and treats it as instructions. These
	 * instructions are matched against the bsns of the jars (think sub
	 * builders!). If they match, the sub builder is selected.
	 * <p>
	 * The instruction can then specify the following options:
	 * 
	 * <pre>
	 *  version :
	 * baseline version from repository file : a file path
	 * </pre>
	 * 
	 * If neither is specified, the current version is used to find the highest
	 * version (without qualifier) that is below the current version. If a
	 * version is specified, we take the highest version with the same base
	 * version.
	 * <p>
	 * Since baselining is expensive and easily generates errors you must enable
	 * it. The easiest solution is to {@code -baseline: *}. This will match all
	 * sub builders and will calculate the version.
	 * 
	 * @return a Jar or null
	 */
public Jar getBaselineJar() throws Exception {
    String bl = getProperty(Constants.BASELINE);
    if (bl == null || Constants.NONE.equals(bl))
        return null;
    Instructions baselines = new Instructions(getProperty(Constants.BASELINE));
    if (baselines.isEmpty())
        // no baselining
        return null;
    RepositoryPlugin repo = getBaselineRepo();
    if (repo == null)
        // errors reported already
        return null;
    String bsn = getBsn();
    Version version = new Version(getVersion());
    SortedSet<Version> versions = removeStagedAndFilter(repo.versions(bsn), repo, bsn);
    if (versions.isEmpty()) {
        // We have a repo
        Version v = Version.parseVersion(getVersion()).getWithoutQualifier();
        if (v.compareTo(Version.ONE) > 0) {
            warning("There is no baseline for %s in the baseline repo %s. The build is for version %s, which is higher than 1.0.0 which suggests that there should be a prior version.", getBsn(), repo, v);
        }
        return null;
    }
    for (Entry<Instruction, Attrs> e : baselines.entrySet()) {
        if (e.getKey().matches(bsn)) {
            Attrs attrs = e.getValue();
            Version target;
            if (attrs.containsKey("version")) {
                // Specified version!
                String v = attrs.get("version");
                if (!Verifier.isVersion(v)) {
                    error("Not a valid version in %s %s", Constants.BASELINE, v);
                    return null;
                }
                Version base = new Version(v);
                SortedSet<Version> later = versions.tailSet(base);
                if (later.isEmpty()) {
                    error("For baselineing %s-%s, specified version %s not found", bsn, version, base);
                    return null;
                }
                // First element is equal or next to the base we desire
                target = later.first();
            // Now, we could end up with a higher version than our
            // current
            // project
            } else if (attrs.containsKey("file")) {
                // Can be useful to specify a file
                // for example when copying a bundle with a public api
                File f = getProject().getFile(attrs.get("file"));
                if (f != null && f.isFile()) {
                    Jar jar = new Jar(f);
                    addClose(jar);
                    return jar;
                }
                error("Specified file for baseline but could not find it %s", f);
                return null;
            } else {
                target = versions.last();
            }
            if (target.getWithoutQualifier().compareTo(version.getWithoutQualifier()) > 0) {
                error("The baseline version %s is higher than the current version %s for %s in %s", target, version, bsn, repo);
                return null;
            }
            if (target.getWithoutQualifier().compareTo(version.getWithoutQualifier()) == 0) {
                if (isPedantic()) {
                    warning("Baselining against jar");
                }
            }
            File file = repo.get(bsn, target, attrs);
            if (file == null || !file.isFile()) {
                error("Decided on version %s-%s but cannot get file from repo %s", bsn, version, repo);
                return null;
            }
            Jar jar = new Jar(file);
            addClose(jar);
            return jar;
        }
    }
    // Ignore, nothing matched
    return null;
}
Also used : Version(aQute.bnd.version.Version) Attrs(aQute.bnd.header.Attrs) RepositoryPlugin(aQute.bnd.service.RepositoryPlugin) Instructions(aQute.bnd.osgi.Instructions) Jar(aQute.bnd.osgi.Jar) Instruction(aQute.bnd.osgi.Instruction) File(java.io.File)

Example 4 with Instruction

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

the class bnd method _select.

@Description("Helps finding information in a set of JARs by filtering on manifest data and printing out selected information.")
public void _select(selectOptions opts) throws Exception {
    PrintStream out = this.out;
    Filter filter = null;
    if (opts.where() != null) {
        String w = opts.where();
        if (!w.startsWith("("))
            w = "(" + w + ")";
        filter = new Filter(w);
    }
    Instructions instructions = new Instructions(opts.header());
    for (String s : opts._arguments()) {
        Jar jar = getJar(s);
        if (jar == null) {
            err.println("no file " + s);
            continue;
        }
        Domain domain = Domain.domain(jar.getManifest());
        Hashtable<String, Object> ht = new Hashtable<String, Object>();
        Iterator<String> i = domain.iterator();
        Set<String> realNames = new HashSet<String>();
        while (i.hasNext()) {
            String key = i.next();
            String value = domain.get(key).trim();
            ht.put(key.trim().toLowerCase(), value);
            realNames.add(key);
        }
        ht.put("resources", jar.getResources().keySet());
        realNames.add("resources");
        if (filter != null) {
            if (!filter.match(ht))
                continue;
        }
        Set<Instruction> unused = new HashSet<Instruction>();
        Collection<String> select = instructions.select(realNames, unused, true);
        for (String h : select) {
            if (opts.path()) {
                out.print(jar.getSource().getAbsolutePath() + ":");
            }
            if (opts.name()) {
                out.print(jar.getSource().getName() + ":");
            }
            if (opts.key()) {
                out.print(h + ":");
            }
            out.println(ht.get(h.toLowerCase()));
        }
        for (Instruction ins : unused) {
            String literal = ins.getLiteral();
            if (literal.equals("name"))
                out.println(jar.getSource().getName());
            else if (literal.equals("path"))
                out.println(jar.getSource().getAbsolutePath());
            else if (literal.equals("size") || literal.equals("length"))
                out.println(jar.getSource().length());
            else if (literal.equals("modified"))
                out.println(new Date(jar.getSource().lastModified()));
        }
    }
}
Also used : PrintStream(java.io.PrintStream) Hashtable(java.util.Hashtable) Instructions(aQute.bnd.osgi.Instructions) Instruction(aQute.bnd.osgi.Instruction) Date(java.util.Date) FilenameFilter(java.io.FilenameFilter) Filter(aQute.lib.filter.Filter) Jar(aQute.bnd.osgi.Jar) Domain(aQute.bnd.osgi.Domain) LinkedHashSet(java.util.LinkedHashSet) HashSet(java.util.HashSet) Description(aQute.lib.getopt.Description)

Example 5 with Instruction

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

the class MetatypeAnnotations method analyzeJar.

public boolean analyzeJar(Analyzer analyzer) throws Exception {
    this.minVersion = MetatypeVersion.VERSION_1_2;
    Parameters header = OSGiHeader.parseHeader(analyzer.getProperty(Constants.METATYPE_ANNOTATIONS, "*"));
    if (header.size() == 0)
        return false;
    Parameters optionsHeader = OSGiHeader.parseHeader(analyzer.getProperty(Constants.METATYPE_ANNOTATIONS_OPTIONS));
    EnumSet<Options> options = EnumSet.noneOf(Options.class);
    for (Map.Entry<String, Attrs> entry : optionsHeader.entrySet()) {
        try {
            Options.parseOption(entry, options, this);
        } catch (IllegalArgumentException e) {
            analyzer.error("Unrecognized %s value %s with attributes %s, expected values are %s", Constants.METATYPE_ANNOTATIONS_OPTIONS, entry.getKey(), entry.getValue(), EnumSet.allOf(Options.class));
        }
    }
    Map<TypeRef, OCDDef> classToOCDMap = new HashMap<TypeRef, OCDDef>();
    Set<String> ocdIds = new HashSet<String>();
    Set<String> pids = new HashSet<String>();
    Instructions instructions = new Instructions(header);
    XMLAttributeFinder finder = new XMLAttributeFinder(analyzer);
    List<Clazz> list = Create.list();
    for (Clazz c : analyzer.getClassspace().values()) {
        for (Instruction instruction : instructions.keySet()) {
            if (instruction.matches(c.getFQN())) {
                if (!instruction.isNegated()) {
                    list.add(c);
                    OCDDef definition = OCDReader.getOCDDef(c, analyzer, options, finder, minVersion);
                    if (definition != null) {
                        classToOCDMap.put(c.getClassName(), definition);
                    }
                }
                break;
            }
        }
    }
    // process Designate annotations after OCD annotations
    for (Clazz c : list) {
        DesignateReader.getDesignate(c, analyzer, classToOCDMap, finder);
    }
    for (Map.Entry<TypeRef, OCDDef> entry : classToOCDMap.entrySet()) {
        TypeRef c = entry.getKey();
        OCDDef definition = entry.getValue();
        definition.prepare(analyzer);
        if (!ocdIds.add(definition.id)) {
            analyzer.error("Duplicate OCD id %s from class %s; known ids %s", definition.id, c.getFQN(), ocdIds);
        }
        for (DesignateDef dDef : definition.designates) {
            if (dDef.pid != null && !pids.add(dDef.pid)) {
                analyzer.error("Duplicate pid %s from class %s", dDef.pid, c.getFQN());
            }
        }
        String name = "OSGI-INF/metatype/" + analyzer.validResourcePath(definition.id, "Invalid resource name") + ".xml";
        analyzer.getJar().putResource(name, new TagResource(definition.getTag()));
    }
    return false;
}
Also used : Parameters(aQute.bnd.header.Parameters) HashMap(java.util.HashMap) TagResource(aQute.bnd.component.TagResource) TypeRef(aQute.bnd.osgi.Descriptors.TypeRef) Attrs(aQute.bnd.header.Attrs) Instructions(aQute.bnd.osgi.Instructions) Instruction(aQute.bnd.osgi.Instruction) XMLAttributeFinder(aQute.bnd.xmlattribute.XMLAttributeFinder) Clazz(aQute.bnd.osgi.Clazz) HashMap(java.util.HashMap) Map(java.util.Map) HashSet(java.util.HashSet)

Aggregations

Instruction (aQute.bnd.osgi.Instruction)13 Instructions (aQute.bnd.osgi.Instructions)6 Attrs (aQute.bnd.header.Attrs)5 Parameters (aQute.bnd.header.Parameters)5 File (java.io.File)5 Clazz (aQute.bnd.osgi.Clazz)4 Version (aQute.bnd.version.Version)4 HashSet (java.util.HashSet)4 TreeSet (java.util.TreeSet)4 Jar (aQute.bnd.osgi.Jar)3 RepositoryPlugin (aQute.bnd.service.RepositoryPlugin)3 Description (aQute.lib.getopt.Description)3 ArrayList (java.util.ArrayList)3 Map (java.util.Map)3 Domain (aQute.bnd.osgi.Domain)2 XMLAttributeFinder (aQute.bnd.xmlattribute.XMLAttributeFinder)2 SortedList (aQute.lib.collections.SortedList)2 HashMap (java.util.HashMap)2 LinkedHashSet (java.util.LinkedHashSet)2 TagResource (aQute.bnd.component.TagResource)1