Search in sources :

Example 6 with Instructions

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

the class bnd method _xref.

/**
	 * Cross reference every class in the jar file to the files it references
	 */
@Description("Show a cross references for all classes in a set of jars.")
public void _xref(xrefOptions options) throws IOException, Exception {
    Analyzer analyzer = new Analyzer();
    final MultiMap<TypeRef, TypeRef> table = new MultiMap<TypeRef, TypeRef>();
    final MultiMap<PackageRef, PackageRef> packages = new MultiMap<PackageRef, PackageRef>();
    Set<TypeRef> set = Create.set();
    Instructions filter = new Instructions(options.match());
    for (String arg : options._arguments()) {
        try {
            File file = new File(arg);
            try (Jar jar = new Jar(file.getName(), file)) {
                for (Map.Entry<String, Resource> entry : jar.getResources().entrySet()) {
                    String key = entry.getKey();
                    Resource r = entry.getValue();
                    if (key.endsWith(".class")) {
                        TypeRef ref = analyzer.getTypeRefFromPath(key);
                        if (filter.matches(ref.toString())) {
                            set.add(ref);
                            try (InputStream in = r.openInputStream()) {
                                Clazz clazz = new Clazz(analyzer, key, r);
                                // TODO use the proper bcp instead
                                // of using the default layout
                                Set<TypeRef> s = clazz.parseClassFile();
                                for (Iterator<TypeRef> t = s.iterator(); t.hasNext(); ) {
                                    TypeRef tr = t.next();
                                    if (tr.isJava() || tr.isPrimitive())
                                        t.remove();
                                    else
                                        packages.add(ref.getPackageRef(), tr.getPackageRef());
                                }
                                table.addAll(ref, s);
                                set.addAll(s);
                            }
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    boolean to = options.to();
    boolean from = options.from();
    if (to == false && from == false)
        to = from = true;
    if (options.classes()) {
        if (to)
            printxref(table, ">");
        if (from)
            printxref(table.transpose(), "<");
    } else {
        if (to)
            printxref(packages, ">");
        if (from)
            printxref(packages.transpose(), "<");
    }
}
Also used : TypeRef(aQute.bnd.osgi.Descriptors.TypeRef) JarInputStream(java.util.jar.JarInputStream) InputStream(java.io.InputStream) FileResource(aQute.bnd.osgi.FileResource) Resource(aQute.bnd.osgi.Resource) Instructions(aQute.bnd.osgi.Instructions) Analyzer(aQute.bnd.osgi.Analyzer) InvocationTargetException(java.lang.reflect.InvocationTargetException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) IOException(java.io.IOException) XPathExpressionException(javax.xml.xpath.XPathExpressionException) ZipException(java.util.zip.ZipException) MultiMap(aQute.lib.collections.MultiMap) Jar(aQute.bnd.osgi.Jar) Clazz(aQute.bnd.osgi.Clazz) PackageRef(aQute.bnd.osgi.Descriptors.PackageRef) File(java.io.File) MultiMap(aQute.lib.collections.MultiMap) Map(java.util.Map) LinkedHashMap(java.util.LinkedHashMap) TreeMap(java.util.TreeMap) HashMap(java.util.HashMap) Description(aQute.lib.getopt.Description)

Example 7 with Instructions

use of aQute.bnd.osgi.Instructions 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 8 with Instructions

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

the class bnd method _settings.

@Description("Set bnd/jpm global variables")
public void _settings(settingOptions opts) throws Exception {
    try {
        Settings settings = this.settings;
        char[] password = this.password;
        if (opts.location() != null) {
            password = opts.password();
            File f = getFile(opts.location());
            settings = new Settings(f.getAbsolutePath());
            settings.load(password);
            logger.debug("getting settings from {}", f);
        }
        if (opts.clear()) {
            settings.clear();
            logger.debug("clear {}", settings.entrySet());
        }
        if (opts.generate()) {
            logger.debug("Generating new key pair");
            settings.generate(password);
        }
        logger.debug("settings {}", opts.clear());
        List<String> rest = opts._arguments();
        if (opts.publicKey()) {
            out.println(tos(!opts.base64(), settings.getPublicKey()));
        }
        if (opts.secretKey()) {
            out.println(tos(!opts.base64(), settings.getPrivateKey()));
        }
        if (opts.mac()) {
            for (String s : rest) {
                byte[] data = s.getBytes(UTF_8);
                byte[] signature = settings.sign(data);
                out.printf("%s\n", tos(!opts.base64(), signature));
            }
        }
        if (rest.isEmpty()) {
            list(null, settings);
        } else {
            boolean set = false;
            for (String s : rest) {
                s = s.trim();
                Matcher m = ASSIGNMENT.matcher(s);
                logger.debug("try {}", s);
                if (m.matches()) {
                    String key = m.group(1);
                    Instructions instr = new Instructions(key);
                    Collection<String> select = instr.select(settings.keySet(), true);
                    // check if there is a value a='b'
                    String value = m.group(4);
                    if (value == null || value.trim().length() == 0) {
                        // check '=' presence
                        if (m.group(2) == null) {
                            list(select, settings);
                        } else {
                            // we have 'a=', remove
                            for (String k : select) {
                                logger.debug("remove {}={}", k, settings.get(k));
                                settings.remove(k);
                                set = true;
                            }
                        }
                    } else {
                        logger.debug("assignment {}={}", key, value);
                        settings.put(key, value);
                        set = true;
                    }
                } else {
                    err.printf("Cannot assign %s\n", s);
                }
            }
            if (set) {
                logger.debug("saving");
                settings.save(password);
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}
Also used : Matcher(java.util.regex.Matcher) Instructions(aQute.bnd.osgi.Instructions) File(java.io.File) Settings(aQute.lib.settings.Settings) InvocationTargetException(java.lang.reflect.InvocationTargetException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) IOException(java.io.IOException) XPathExpressionException(javax.xml.xpath.XPathExpressionException) ZipException(java.util.zip.ZipException) Description(aQute.lib.getopt.Description)

Example 9 with Instructions

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

the class bnd method _grep.

@Description("Grep the manifest of bundles/jar files. ")
public void _grep(grepOptions opts) throws Exception {
    List<String> args = opts._arguments();
    String s = args.remove(0);
    Pattern pattern = Glob.toPattern(s);
    if (pattern == null) {
        messages.InvalidGlobPattern_(s);
        return;
    }
    if (args.isEmpty()) {
        args = new ExtList<String>(getBase().list(new FilenameFilter() {

            public boolean accept(File dir, String name) {
                return name.endsWith(".jar");
            }
        }));
    }
    Set<String> headers = opts.headers();
    if (headers == null)
        headers = new TreeSet<String>();
    if (opts.exports())
        headers.add(Constants.EXPORT_PACKAGE);
    if (opts.bsn())
        headers.add(Constants.BUNDLE_SYMBOLICNAME);
    if (opts.imports())
        headers.add(Constants.IMPORT_PACKAGE);
    Instructions instructions = new Instructions(headers);
    for (String fileName : args) {
        File file = getFile(fileName);
        if (!file.isFile()) {
            messages.NoSuchFile_(file);
            continue;
        }
        try (JarInputStream in = new JarInputStream(IO.stream(file))) {
            Manifest m = in.getManifest();
            for (Object header : m.getMainAttributes().keySet()) {
                Attributes.Name name = (Name) header;
                if (instructions.isEmpty() || instructions.matches(name.toString())) {
                    String h = m.getMainAttributes().getValue(name);
                    QuotedTokenizer qt = new QuotedTokenizer(h, ",;=");
                    for (String value : qt.getTokenSet()) {
                        Matcher matcher = pattern.matcher(value);
                        while (matcher.find()) {
                            int start = matcher.start() - 8;
                            if (start < 0)
                                start = 0;
                            int end = matcher.end() + 8;
                            if (end > value.length())
                                end = value.length();
                            out.printf("%40s : %20s ...%s[%s]%s...\n", fileName, name, value.substring(start, matcher.start()), value.substring(matcher.start(), matcher.end()), value.substring(matcher.end(), end));
                        }
                    }
                }
            }
        }
    }
}
Also used : Pattern(java.util.regex.Pattern) QuotedTokenizer(aQute.libg.qtokens.QuotedTokenizer) JarInputStream(java.util.jar.JarInputStream) Matcher(java.util.regex.Matcher) Attributes(java.util.jar.Attributes) Instructions(aQute.bnd.osgi.Instructions) Name(java.util.jar.Attributes.Name) Manifest(java.util.jar.Manifest) PomFromManifest(aQute.bnd.maven.PomFromManifest) Name(java.util.jar.Attributes.Name) FilenameFilter(java.io.FilenameFilter) TreeSet(java.util.TreeSet) File(java.io.File) Description(aQute.lib.getopt.Description)

Example 10 with Instructions

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

the class bnd method _view.

/**
	 * View files from JARs We parse the commandline and print each file on it.
	 * 
	 * @throws Exception
	 */
@Description("View a resource from a JAR file.")
public void _view(viewOptions options) throws Exception {
    Charset charset = UTF_8;
    if (options.charset() != null)
        charset = Charset.forName(options.charset());
    if (options._arguments().isEmpty()) {
        error("Need a jarfile as source");
        return;
    }
    List<String> args = options._arguments();
    File file = getFile(args.remove(0));
    if (!file.isFile()) {
        error("File does not exist %s", file);
        return;
    }
    try (Jar jar = new Jar(file)) {
        if (args.isEmpty())
            args.add("*");
        Instructions instructions = new Instructions(args);
        Collection<String> selected = instructions.select(jar.getResources().keySet(), true);
        for (String selection : selected) {
            Resource r = jar.getResource(selection);
            if (selection.endsWith(".MF")) {
                Manifest m = new Manifest(r.openInputStream());
                printManifest(m);
            } else if (selection.endsWith(".class")) {
                ClassDumper clsd = new ClassDumper(selection, r.openInputStream());
                clsd.dump(out);
            } else {
                InputStreamReader isr = new InputStreamReader(r.openInputStream(), charset);
                IO.copy(isr, out);
            }
        }
    }
}
Also used : InputStreamReader(java.io.InputStreamReader) FileResource(aQute.bnd.osgi.FileResource) Resource(aQute.bnd.osgi.Resource) Charset(java.nio.charset.Charset) Jar(aQute.bnd.osgi.Jar) Instructions(aQute.bnd.osgi.Instructions) Manifest(java.util.jar.Manifest) PomFromManifest(aQute.bnd.maven.PomFromManifest) ClassDumper(aQute.libg.classdump.ClassDumper) File(java.io.File) Description(aQute.lib.getopt.Description)

Aggregations

Instructions (aQute.bnd.osgi.Instructions)27 File (java.io.File)15 Jar (aQute.bnd.osgi.Jar)11 Description (aQute.lib.getopt.Description)10 Parameters (aQute.bnd.header.Parameters)9 Attrs (aQute.bnd.header.Attrs)6 Instruction (aQute.bnd.osgi.Instruction)6 FileResource (aQute.bnd.osgi.FileResource)5 ArrayList (java.util.ArrayList)5 Clazz (aQute.bnd.osgi.Clazz)4 Resource (aQute.bnd.osgi.Resource)4 Tree (aQute.bnd.service.diff.Tree)4 HashSet (java.util.HashSet)4 TypeRef (aQute.bnd.osgi.Descriptors.TypeRef)3 Version (aQute.bnd.version.Version)3 MultiMap (aQute.lib.collections.MultiMap)3 IOException (java.io.IOException)3 PrintWriter (java.io.PrintWriter)3 InvocationTargetException (java.lang.reflect.InvocationTargetException)3 Date (java.util.Date)3