bnd-1.50.0/0000755000175000017500000000000011656076535012252 5ustar drazzibdrazzibbnd-1.50.0/biz.aQute.launcher/0000755000175000017500000000000011656076535015714 5ustar drazzibdrazzibbnd-1.50.0/biz.aQute.launcher/build.xml0000644000175000017500000000017711656076535017542 0ustar drazzibdrazzib bnd-1.50.0/biz.aQute.launcher/bnd.bnd0000644000175000017500000000047611656076535017153 0ustar drazzibdrazzib-buildpath: biz.aQute.bndlib;version=project,\ aQute.libg;version=project,\ osgi.core;version=4.2.1,\ junit.osgi;version=3.8.2 # ee.minimum;version=1.2.1 Launcher-Plugin: aQute.launcher.plugin.ProjectLauncherImpl Private-Package: aQute.launcher.* Bundle-Version: 1.0.0 javac.source = 1.5 javac.target = jsr14bnd-1.50.0/biz.aQute.launcher/.classpath0000644000175000017500000000065611656076535017706 0ustar drazzibdrazzib bnd-1.50.0/biz.aQute.launcher/.project0000644000175000017500000000101711656076535017362 0ustar drazzibdrazzib biz.aQute.launcher org.eclipse.jdt.core.javabuilder bndtools.core.bndbuilder org.eclipse.jdt.core.javanature bndtools.core.bndnature bnd-1.50.0/biz.aQute.launcher/test/0000755000175000017500000000000011656076535016673 5ustar drazzibdrazzibbnd-1.50.0/biz.aQute.launcher/test/test/0000755000175000017500000000000011656076535017652 5ustar drazzibdrazzibbnd-1.50.0/biz.aQute.launcher/test/test/MiniFrameworkTest.java0000644000175000017500000000137411656076535024134 0ustar drazzibdrazzibpackage test; import java.io.*; import java.net.*; import java.util.*; import junit.framework.*; import org.osgi.framework.*; import aQute.launcher.minifw.*; public class MiniFrameworkTest extends TestCase { public void testSimple() throws Exception { Properties properties = new Properties(); MiniFramework framework = new MiniFramework(properties); URL url = new File("test/test/demo.jar").toURI().toURL(); url.openStream().close(); framework.init(); Bundle b = framework.installBundle("reference:" + url.toExternalForm()); assertNotNull(b); Bundle [] bundles = framework.getBundles(); assertNotNull(bundles); assertEquals( 2, bundles.length); Class c = b.loadClass("test.TestActivator"); assertNotNull(c); } } bnd-1.50.0/biz.aQute.launcher/src/0000755000175000017500000000000011656076535016503 5ustar drazzibdrazzibbnd-1.50.0/biz.aQute.launcher/src/aQute/0000755000175000017500000000000011656076535017562 5ustar drazzibdrazzibbnd-1.50.0/biz.aQute.launcher/src/aQute/launcher/0000755000175000017500000000000011656076535021363 5ustar drazzibdrazzibbnd-1.50.0/biz.aQute.launcher/src/aQute/launcher/minifw/0000755000175000017500000000000011656076535022654 5ustar drazzibdrazzibbnd-1.50.0/biz.aQute.launcher/src/aQute/launcher/minifw/MiniFramework.java0000644000175000017500000001535611656076535026303 0ustar drazzibdrazzibpackage aQute.launcher.minifw; import java.io.*; import java.net.*; import java.util.*; import org.osgi.framework.*; import org.osgi.framework.launch.*; public class MiniFramework implements Framework, Bundle, BundleContext { ClassLoader loader; Properties properties; Map bundles = new HashMap(); int ID = 1; int state = Bundle.INSTALLED; ClassLoader last; public MiniFramework(Map properties) { this.properties = new Properties(System.getProperties()); this.properties.putAll(properties); bundles.put(new Long(0), this); last = loader = getClass().getClassLoader(); } public void init() throws BundleException { state = Bundle.ACTIVE; } public FrameworkEvent waitForStop(long timeout) throws InterruptedException { long deadline = System.currentTimeMillis() + timeout; while (state != Bundle.UNINSTALLED) { if (timeout != 0) { long wait = deadline - System.currentTimeMillis(); if (wait <= 0) return new FrameworkEvent(FrameworkEvent.WAIT_TIMEDOUT, this, null); } else { ; } Thread.sleep(100); } return new FrameworkEvent(FrameworkEvent.STOPPED, this, null); } public BundleContext getBundleContext() { return this; } public long getBundleId() { return 0; } public URL getEntry(String path) { if (path.startsWith("/")) path = path.substring(1); return loader.getResource(path); } public Enumeration getEntryPaths(String path) { throw new UnsupportedOperationException(); } public Dictionary getHeaders() { return new Hashtable(); } public Dictionary getHeaders(String locale) { throw new UnsupportedOperationException(); } public long getLastModified() { return 0; } public String getLocation() { return "System Bundle"; } public URL getResource(String name) { return loader.getResource(name); } public Enumeration getResources(String name) throws IOException { return loader.getResources(name); } public int getState() { return Bundle.ACTIVE; } public String getSymbolicName() { return "system.bundle"; } public Version getVersion() { return new Version("1.0"); } public boolean hasPermission(Object permission) { return true; } public Class loadClass(String name) throws ClassNotFoundException { return loader.loadClass(name); } public void start() { } public void start(int options) { } public synchronized void stop() { state = Bundle.UNINSTALLED; notifyAll(); } public void stop(int options) throws BundleException { } public Bundle getBundle() { return this; } public Bundle getBundle(long id) { Long l = new Long(id); Bundle b = (Bundle) bundles.get(l); return b; } public Bundle[] getBundles() { Bundle[] bs = new Bundle[bundles.size()]; return (Bundle[]) bundles.values().toArray(bs); } public File getDataFile(String filename) { return null; } public String getProperty(String key) { return properties.getProperty(key); } public Bundle installBundle(String location) throws BundleException { if (location.startsWith("reference:")) location = location.substring("reference:".length()).trim(); if (location.startsWith("file:")) location = location.substring("file:".length()).trim(); while (location.startsWith("//")) location = location.substring(1); try { Context c = new Context(this, last, ++ID, location); bundles.put(new Long(c.id), c); last = c; return c; } catch (Exception e) { throw new BundleException("Failed to install", e); } } public Bundle installBundle(String location, InputStream in) throws BundleException { Context c; try { in.close(); try { URL url = new URL(location); } catch (MalformedURLException e) { throw new BundleException( "For the mini framework, the location must be a proper URL even though this is not required by the specification " + location, e); } c = new Context(this, last, ++ID, location); bundles.put(new Long(c.id), c); last = c; return c; } catch (Exception e) { throw new BundleException("Can't install " + location, e); } } public Enumeration findEntries(String path, String filePattern, boolean recurse) { throw new UnsupportedOperationException(); } public ServiceReference[] getRegisteredServices() { throw new UnsupportedOperationException(); } public ServiceReference[] getServicesInUse() { throw new UnsupportedOperationException(); } public Map getSignerCertificates(int signersType) { throw new UnsupportedOperationException(); } public void uninstall() throws BundleException { throw new UnsupportedOperationException(); } public void update() throws BundleException { throw new UnsupportedOperationException(); } public void update(InputStream in) throws BundleException { throw new UnsupportedOperationException(); } public void addBundleListener(BundleListener listener) { // no services so cannot do any harm } public void addFrameworkListener(FrameworkListener listener) { // no services so cannot do any harm } public void addServiceListener(ServiceListener listener) { // no services so cannot do any harm } public void addServiceListener(ServiceListener listener, String filter) { // no services so cannot do any harm } public Filter createFilter(String filter) throws InvalidSyntaxException { return FrameworkUtil.createFilter(filter); } public ServiceReference[] getAllServiceReferences(String clazz, String filter) throws InvalidSyntaxException { throw new UnsupportedOperationException(); } public Object getService(ServiceReference reference) { return null; } public ServiceReference getServiceReference(String clazz) { return null; } public ServiceReference[] getServiceReferences(String clazz, String filter) throws InvalidSyntaxException { return null; } public ServiceRegistration registerService(String[] clazzes, Object service, Dictionary properties) { throw new UnsupportedOperationException(); } public ServiceRegistration registerService(String clazz, Object service, Dictionary properties) { throw new UnsupportedOperationException(); } public void removeBundleListener(BundleListener listener) { // ok } public void removeFrameworkListener(FrameworkListener listener) { // ok } public void removeServiceListener(ServiceListener listener) { // ok } public boolean ungetService(ServiceReference reference) { throw new UnsupportedOperationException(); } public String toString() { return "Mini framework"; } class Loader extends ClassLoader { public Class findClass(String name) throws ClassNotFoundException { for (Iterator i = bundles.values().iterator(); i.hasNext();) { Bundle b = (Bundle) i; try { return b.loadClass(name); } catch (ClassNotFoundException e) { // Ignore, try next } } throw new ClassNotFoundException(name); } } } bnd-1.50.0/biz.aQute.launcher/src/aQute/launcher/minifw/Context.java0000644000175000017500000002226111656076535025146 0ustar drazzibdrazzibpackage aQute.launcher.minifw; import java.io.*; import java.net.*; import java.util.*; import java.util.jar.*; import java.util.zip.*; import org.osgi.framework.*; public class Context extends URLClassLoader implements Bundle, BundleContext, BundleReference { long id; MiniFramework fw; String location; int state = Bundle.INSTALLED; JarFile jar; Manifest manifest; TreeSet keys; private TreeSet paths; private File jarFile; class Dict extends Dictionary { public Enumeration elements() { return Collections.enumeration(manifest.getMainAttributes() .values()); } public Object get(Object key) { Object o = manifest.getMainAttributes().getValue((String) key); return o; } public boolean isEmpty() { return manifest.getMainAttributes().isEmpty(); } public Enumeration keys() { Vector v = new Vector(); for (Iterator i = manifest.getMainAttributes().keySet().iterator(); i .hasNext();) { Attributes.Name name = (Attributes.Name) i.next(); v.add(name.toString()); } return v.elements(); } public Object put(Object key, Object value) { throw new UnsupportedOperationException(); } public Object remove(Object key) { throw new UnsupportedOperationException(); } public int size() { return manifest.getMainAttributes().size(); } } public Context(MiniFramework fw, ClassLoader parent, int id, String location) throws Exception { super(new URL[] { new File(location).toURI().toURL() }, parent); this.fw = fw; this.id = id; this.location = location; jar = new JarFile(jarFile = new File(location)); // Enumeration entries = jar.entries(); // while ( entries.hasMoreElements()) // System.out.println(entries.nextElement().getName()); manifest = jar.getManifest(); jar.close(); } public BundleContext getBundleContext() { return this; } public long getBundleId() { return id; } public URL getEntry(String path) { if ( path.startsWith("/")) path = path.substring(1); return getResource(path); } public Enumeration getEntryPaths(String path) { throw new UnsupportedOperationException(); } public Dictionary getHeaders() { return new Dict(); } public Dictionary getHeaders(String locale) { return new Dict(); } public long getLastModified() { return jarFile.lastModified(); } public String getLocation() { return location; } public Enumeration findEntries(String path, String filePattern, boolean recurse) { try { if (path.startsWith("/")) path = path.substring(1); if (!path.endsWith("/")) path += "/"; Vector paths = new Vector(); for (Iterator i = getPaths().iterator(); i.hasNext();) { String entry = (String) i.next(); if (entry.startsWith(path)) { if (recurse || entry.indexOf('/', path.length()) < 0) { if (filePattern == null || matches(entry, filePattern)) { URL url = getResource(entry); if (url == null) { System.err .println("Cannot load resource that should be there: " + entry); } else paths.add(url); } } } } return paths.elements(); } catch (Exception e) { throw new RuntimeException(e); } } public static boolean matches(String path, String filePattern) { do { int part = filePattern.indexOf('*'); if (part < 0) { return path.indexOf(filePattern) >= 0; } else { String match = filePattern.substring(0, part); int m = path.indexOf(match); if (m < 0) return false; path = path.substring(m + match.length()); filePattern = filePattern.substring(part + 1); } } while (true); } private Collection getPaths() throws Exception { if (paths != null) return paths; paths = new TreeSet(); JarFile jar = new JarFile(new File(location)); try { for (Enumeration e = jar.entries(); e.hasMoreElements();) { ZipEntry entry = (JarEntry) e.nextElement(); paths.add(entry.getName()); } } finally { jar.close(); } return paths; } public ServiceReference[] getRegisteredServices() { return null; } public ServiceReference[] getServicesInUse() { return null; } public Map getSignerCertificates(int signersType) { throw new UnsupportedOperationException(); } public int getState() { return state; } public String getSymbolicName() { return ((String)getHeaders().get("Bundle-SymbolicName")).trim(); } public Version getVersion() { String v = ((String)getHeaders().get("Bundle-Version")).trim(); if ( v == null) return new Version("0"); else return new Version(v); } public boolean hasPermission(Object permission) { return true; } public void start() throws BundleException { state = Bundle.ACTIVE; } public void start(int options) throws BundleException { state = Bundle.ACTIVE; } public void stop() throws BundleException { state = Bundle.RESOLVED; } public void stop(int options) throws BundleException { state = Bundle.RESOLVED; } public void uninstall() throws BundleException { state = Bundle.UNINSTALLED; } public void update() throws BundleException { throw new UnsupportedOperationException(); } public void update(InputStream in) throws BundleException { throw new UnsupportedOperationException(); } public void addBundleListener(BundleListener listener) { throw new UnsupportedOperationException(); } public void addFrameworkListener(FrameworkListener listener) { throw new UnsupportedOperationException(); } public void addServiceListener(ServiceListener listener) { throw new UnsupportedOperationException(); } public void addServiceListener(ServiceListener listener, String filter) { throw new UnsupportedOperationException(); } public Filter createFilter(String filter) throws InvalidSyntaxException { throw new UnsupportedOperationException(); } public ServiceReference[] getAllServiceReferences(String clazz, String filter) throws InvalidSyntaxException { throw new UnsupportedOperationException(); } public Bundle getBundle() { return this; } public Bundle getBundle(long id) { return fw.getBundle(id); } public Bundle[] getBundles() { return fw.getBundles(); } public File getDataFile(String filename) { return null; } public String getProperty(String key) { return fw.getProperty(key); } public Object getService(ServiceReference reference) { throw new UnsupportedOperationException(); } public ServiceReference getServiceReference(String clazz) { return null; } public ServiceReference[] getServiceReferences(String clazz, String filter) throws InvalidSyntaxException { return null; } public Bundle installBundle(String location) throws BundleException { return fw.installBundle(location); } public Bundle installBundle(String location, InputStream input) throws BundleException { return fw.installBundle(location, input); } public ServiceRegistration registerService(String[] clazzes, Object service, Dictionary properties) { throw new UnsupportedOperationException(); } public ServiceRegistration registerService(String clazz, Object service, Dictionary properties) { throw new UnsupportedOperationException(); } public void removeBundleListener(BundleListener listener) { throw new UnsupportedOperationException(); } public void removeFrameworkListener(FrameworkListener listener) { throw new UnsupportedOperationException(); } public void removeServiceListener(ServiceListener listener) { throw new UnsupportedOperationException(); } public boolean ungetService(ServiceReference reference) { throw new UnsupportedOperationException(); } public String toString() { return id + " " + location; } } bnd-1.50.0/biz.aQute.launcher/src/aQute/launcher/plugin/0000755000175000017500000000000011656076535022661 5ustar drazzibdrazzibbnd-1.50.0/biz.aQute.launcher/src/aQute/launcher/plugin/ProjectLauncherImpl.java0000644000175000017500000001026211656076535027437 0ustar drazzibdrazzibpackage aQute.launcher.plugin; import java.io.*; import java.text.MessageFormat; import java.util.*; import java.util.jar.*; import aQute.bnd.build.*; import aQute.bnd.service.RepositoryPlugin.Strategy; import aQute.launcher.constants.*; import aQute.lib.io.*; import aQute.lib.osgi.*; import aQute.libg.generics.*; import static aQute.lib.osgi.Constants.*; public class ProjectLauncherImpl extends ProjectLauncher { final private Project project; final private File propertiesFile; boolean prepared; public ProjectLauncherImpl(Project project) throws Exception { super(project); project.trace("created a aQute launcher plugin"); this.project = project; propertiesFile = File.createTempFile("launch", ".properties", project.getTarget()); project.trace(MessageFormat.format("launcher plugin using temp launch file {0}", propertiesFile.getAbsolutePath())); addRunVM("-D" + LauncherConstants.LAUNCHER_PROPERTIES + "=" + propertiesFile.getAbsolutePath()); if (project.getRunProperties().get("noframework") != null) { setRunFramework(NONE); project.warning("The noframework property in -runproperties is replaced by a project setting: '-runframework: none'"); } super.addDefault(Constants.DEFAULT_LAUNCHER_BSN); } public String getMainTypeName() { return "aQute.launcher.Launcher"; } public void update() throws Exception { updateFromProject(); writeProperties(); } public int launch() throws Exception { prepare(); return super.launch(); } public void prepare() throws Exception { if (prepared) return; prepared = true; writeProperties(); } void writeProperties() throws Exception { LauncherConstants lc = getConstants(getRunBundles()); OutputStream out = new FileOutputStream(propertiesFile); try { lc.getProperties().store(out, "Launching " + project); } finally { out.close(); } } /** * @return * @throws Exception * @throws FileNotFoundException * @throws IOException */ private LauncherConstants getConstants(Collection runbundles) throws Exception, FileNotFoundException, IOException { project.trace("preparing the aQute launcher plugin"); LauncherConstants lc = new LauncherConstants(); lc.runProperties = getRunProperties(); lc.storageDir = getStorageDir(); lc.keep = isKeep(); lc.runbundles.addAll(getRunBundles()); lc.trace = getTrace(); lc.timeout = getTimeout(); lc.services = super.getRunFramework() == SERVICES ? true : false; lc.activators.addAll(getActivators()); if (!getSystemPackages().isEmpty()) { lc.systemPackages = Processor.printClauses(getSystemPackages()); } return lc; } /** * Create a standalone executable * @throws Exception * @throws IOException * @throws FileNotFoundException */ public Jar executable() throws Exception { Jar jar = new Jar(project.getName()); Collection runbundles = copyBundles(jar, getRunBundles()); LauncherConstants lc = getConstants(runbundles); final Properties p = lc.getProperties(); p.setProperty(RUNBUNDLES, Processor.join(runbundles,", \\\n ") ); jar.putResource("descriptor.properties", new WriteResource() { @Override public void write(OutputStream outStream) throws IOException, Exception { p.store(outStream, "comment"); } @Override public long lastModified() { return 0L; } }); List paths = Create.list(); paths.addAll( getRunpath()); paths.add( project.getBundle("biz.aQute.launcher", null, Strategy.HIGHEST, null).getFile().getAbsolutePath()); for ( String path : paths) { File f = IO.getFile(project.getBase(), path); Jar roll = new Jar(f); jar.addAll(roll); } Manifest m = new Manifest(); m.getMainAttributes().putValue("Main-Class", "aQute.launcher.Launcher"); jar.setManifest(m); return jar; } /** * @param jar */ private Collection copyBundles(Jar jar, Collection runbundles) { List list = Create.list(); for (String s : runbundles) { File f = IO.getFile(new File("").getAbsoluteFile(), s); if (!f.isFile()) { project.error("In exec, cannot find runbundle %s for project %s", f, project); } else { String path = "jar/" + f.getName(); list.add(path); } } return list; } } bnd-1.50.0/biz.aQute.launcher/src/aQute/launcher/Launcher.java0000644000175000017500000005443011656076535023775 0ustar drazzibdrazzibpackage aQute.launcher; import static aQute.launcher.constants.LauncherConstants.*; import java.io.*; import java.lang.reflect.*; import java.net.*; import java.security.*; import java.util.*; import java.util.Map.*; import org.osgi.framework.*; import org.osgi.framework.launch.*; import org.osgi.service.packageadmin.*; import org.osgi.service.permissionadmin.*; import aQute.launcher.constants.*; import aQute.launcher.minifw.*; /** * This is the primary bnd launcher. It implements a launcher that runs on Java * 1.4. */ public class Launcher implements ServiceListener { private PrintStream out; private LauncherConstants parms; private Framework systemBundle; private final Properties properties; private boolean security; private SimplePermissionPolicy policy; private Runnable mainThread; private PackageAdmin padmin; private static File propertiesFile; private final Timer timer = new Timer(); private final List embedded = new ArrayList(); private TimerTask watchdog = null; private final Map errors = new HashMap(); private final Map installedBundles = new LinkedHashMap(); public static void main(String[] args) { try { String path = System.getProperty(LauncherConstants.LAUNCHER_PROPERTIES); assert path != null; propertiesFile = new File(path).getAbsoluteFile(); propertiesFile.deleteOnExit(); FileInputStream in = new FileInputStream(propertiesFile); Properties properties = new Properties(); try { properties.load(in); } finally { in.close(); } Launcher target = new Launcher(properties); target.run(args); } catch (Throwable t) { // Last resort ... errors should be handled lower t.printStackTrace(System.err); } } public Launcher(Properties properties) throws Exception { this.properties = properties; System.getProperties().putAll(properties); this.parms = new LauncherConstants(properties); out = System.err; trace("inited runbundles=%s activators=%s timeout=%s", parms.runbundles, parms.activators, parms.timeout); watchdog = new TimerTask() { long begin = propertiesFile.lastModified(); public void run() { if (begin < propertiesFile.lastModified()) { try { FileInputStream in = new FileInputStream(propertiesFile); Properties properties = new Properties(); try { properties.load(in); } finally { in.close(); } parms = new LauncherConstants(properties); update(); } catch (Exception e) { error("Error in updating the framework from the properties: %s", e); } begin = propertiesFile.lastModified(); } } }; timer.scheduleAtFixedRate(watchdog, 5000, 1000); } private void run(String args[]) throws Throwable { try { int status = activate(); if (status != 0) { report(out); System.exit(status); } trace("framework=" + systemBundle); // Register the command line with ourselves as the // service. if (parms.services) { // Does not work for our dummy framework Hashtable argprops = new Hashtable(); argprops.put(LauncherConstants.LAUNCHER_ARGUMENTS, args); argprops.put(LauncherConstants.LAUNCHER_READY, "true"); systemBundle.getBundleContext().registerService(Launcher.class.getName(), this, argprops); trace("registered launcher with arguments for syncing"); } // Wait until a Runnable is registered with main.thread=true. // not that this will never happen when we're running on the mini fw // but the test case normally exits. synchronized (this) { while (mainThread == null) { trace("will wait for a registered Runnable"); wait(); } } trace("Will run %s as main thread", mainThread); mainThread.run(); } catch (Throwable e) { error("Unexpected error in the run body: %s", e); throw e; } finally { systemBundle.stop(); trace("stopped system bundle due to leaving run body"); } } private List split(String value, String separator) { List list = new ArrayList(); if (value == null) return list; StringTokenizer st = new StringTokenizer(value, separator); while (st.hasMoreTokens()) list.add(st.nextToken()); return list; } public int activate() throws Exception { Policy.setPolicy(new AllPolicy()); systemBundle = createFramework(); if (systemBundle == null) return LauncherConstants.ERROR; doTimeoutHandler(); doSecurity(); // Initialize this framework so it becomes STARTING systemBundle.start(); trace("system bundle started ok"); BundleContext systemContext = systemBundle.getBundleContext(); ServiceReference ref = systemContext.getServiceReference(PackageAdmin.class.getName()); if (ref != null) { padmin = (PackageAdmin) systemContext.getService(ref); } else trace("could not get package admin"); systemContext.addServiceListener(this, "(&(objectclass=java.lang.Runnable)(main.thread=true))"); update(); if (parms.trace) { report(out); } // Start embedded activators trace("start embedded activators"); if (parms.activators != null) { ClassLoader loader = getClass().getClassLoader(); for (Object token : parms.activators) { try { Class clazz = loader.loadClass((String) token); BundleActivator activator = (BundleActivator) clazz.newInstance(); embedded.add(activator); trace("adding activator %s", activator); } catch (Exception e) { throw new IllegalArgumentException("Embedded Bundle Activator incorrect: " + token + ", " + e); } } } int result = LauncherConstants.OK; for (BundleActivator activator : embedded) try { trace("starting activator %s", activator); activator.start(systemContext); } catch (Exception e) { error("Starting activator %s : %s", activator, e); result = LauncherConstants.ERROR; } return result; } /** * @param systemContext * @throws MalformedURLException * @throws FileNotFoundException * @throws IOException */ private void update() throws Exception { trace("Updating framework with %s", parms.runbundles); // Turn the bundle location paths into files List desired = new ArrayList(); for (Object o : parms.runbundles) { File file = new File((String) o).getAbsoluteFile(); if (!file.exists()) error("Bundle files does not exist: " + file); else desired.add(file); } // deleted = old - new List tobedeleted = new ArrayList(installedBundles.keySet()); tobedeleted.removeAll(desired); // updated = old /\ new List tobeupdated = new ArrayList(installedBundles.keySet()); tobeupdated.retainAll(desired); // install = new - old List tobeinstalled = new ArrayList(desired); tobeinstalled.removeAll(installedBundles.keySet()); List tobestarted = new ArrayList(); for (File f : tobedeleted) try { trace("uninstalling %s", f); installedBundles.get(f).uninstall(); installedBundles.remove(f); } catch (Exception e) { error("Failed to uninstall bundle %s, exception %s", f, e); } for (File f : tobeinstalled) try { trace("installing %s", f); Bundle b = install(f); installedBundles.put(f, b); tobestarted.add(b); } catch (Exception e) { error("Failed to uninstall bundle %s, exception %s", f, e); } for (File f : tobeupdated) try { Bundle b = installedBundles.get(f); if (b.getLastModified() < f.lastModified()) { trace("updating %s", f); if ( b.getState() == Bundle.ACTIVE) { tobestarted.add(b); b.stop(); } b.update(); } else trace("bundle is still current according to timestamp %s", f); } catch (Exception e) { error("Failed to update bundle %s, exception %s", f, e); } if (padmin != null) padmin.refreshPackages(null); trace("bundles administered %s", installedBundles.keySet()); // From now on, the bundles are on their own. They have // by default AllPermission, but if they install bundles // they will not automatically get AllPermission anymore if (security) policy.setDefaultPermissions(null); // Get the resolved status if (padmin != null && padmin.resolveBundles(null) == false) { error("could not resolve the bundles"); // return LauncherConstants.RESOLVE_ERROR; } // Now start all the installed bundles in the same order // (unless they're a fragment) trace("Will start bundles: %s" ,tobestarted); for (Bundle b : tobestarted) { try { trace("starting %s", b.getSymbolicName()); if (!isFragment(b)) b.start(Bundle.START_ACTIVATION_POLICY); trace("started %s", b.getSymbolicName()); } catch (BundleException e) { error("Failed to start bundle %s-%s, exception %s", b.getSymbolicName(), b .getVersion(), e); } } } Bundle install(File f) throws Exception { BundleContext context = systemBundle.getBundleContext(); try { trace("will install %s with reference", f.getAbsolutePath()); String reference = "reference:" + f.toURI().toURL().toExternalForm(); Bundle b = context.installBundle(reference); if (b.getLastModified() < f.lastModified()) { b.update(); } return b; } catch (BundleException e) { trace("failed reference, will try to install %s with input stream", f.getAbsolutePath()); String reference = f.toURI().toURL().toExternalForm(); InputStream in = new FileInputStream(f); try { return context.installBundle(reference, in); } finally { in.close(); } } } private void doTimeoutHandler() { // Ensure we properly close in a separate thread so that // we can leverage the main thread, which is required for macs Thread wait = new Thread("FrameworkWaiter") { public void run() { try { FrameworkEvent result = systemBundle.waitForStop(parms.timeout); trace( "framework event " + result + " " + result.getType()); Thread.sleep(1000); switch (result.getType()) { case FrameworkEvent.STOPPED: System.exit(LauncherConstants.OK); break; case FrameworkEvent.WAIT_TIMEDOUT: System.exit(LauncherConstants.TIMEDOUT); break; case FrameworkEvent.ERROR: System.exit(ERROR); break; case FrameworkEvent.WARNING: System.exit(WARNING); break; case FrameworkEvent.STOPPED_BOOTCLASSPATH_MODIFIED: case FrameworkEvent.STOPPED_UPDATE: System.exit(UPDATE_NEEDED); break; } } catch (InterruptedException e) { System.exit(CANCELED); } finally { System.err.println("System exiting due to timeout of " + parms.timeout); } } }; wait.start(); } private void doSecurity() { try { PermissionInfo allPermissions[] = new PermissionInfo[] { new PermissionInfo( AllPermission.class.getName(), null, null) }; policy = new SimplePermissionPolicy(this, systemBundle.getBundleContext()); // All bundles installed from the script are getting AllPermission // for now. policy.setDefaultPermissions(allPermissions); security = true; } catch (Throwable t) { // This can throw a linkage error when the framework // does not carry the PermissionAdmin class security = false; } } private boolean isFragment(Bundle b) { return padmin != null && padmin.getBundleType(b) == PackageAdmin.BUNDLE_TYPE_FRAGMENT; } public void deactivate() throws Exception { if (systemBundle != null) { systemBundle.stop(); systemBundle.waitForStop(parms.timeout); } } public void addSystemPackage(String packageName) { parms.systemPackages = concat(parms.systemPackages, packageName); } private String concat(String a, String b) { if (a == null) return b; else if (b == null) return a; return a + "," + b; } private Framework createFramework() throws Exception { Properties p = new Properties(); p.putAll(properties); File workingdir = new File("tmp").getAbsoluteFile(); if (parms.storageDir != null) workingdir = parms.storageDir; trace("using working dir: %s", parms.storageDir); if (!parms.keep) { trace("deleting working dir %s because not kept", workingdir); delete(workingdir); p.setProperty(Constants.FRAMEWORK_STORAGE_CLEAN, "true"); } workingdir.mkdirs(); if (!workingdir.isDirectory()) throw new IllegalArgumentException("Cannot create a working dir: " + workingdir); p.setProperty(Constants.FRAMEWORK_STORAGE, workingdir.getAbsolutePath()); if (parms.systemPackages != null) { p.setProperty(Constants.FRAMEWORK_SYSTEMPACKAGES_EXTRA, parms.systemPackages); trace("system packages used: %s", parms.systemPackages); } Framework systemBundle; if (parms.services) { trace("using META-INF/services"); // 3) framework = null, lookup in META-INF/services ClassLoader loader = getClass().getClassLoader(); // 3) Lookup in META-INF/services List implementations = getMetaInfServices(loader, FrameworkFactory.class .getName()); if (implementations.size() == 0) error("Found no fw implementation"); if (implementations.size() > 1) error("Found more than one framework implementations: %s", implementations); String implementation = (String) implementations.get(0); Class clazz = loader.loadClass(implementation); FrameworkFactory factory = (FrameworkFactory) clazz.newInstance(); trace("Framework factory %s", factory); systemBundle = factory.newFramework(p); trace("framework instance %s", systemBundle); } else { trace("using embedded mini framework because we were told not to use META-INF/services"); // we have to use our own dummy framework systemBundle = new MiniFramework(p); } systemBundle.init(); trace("inited system bundle %s", systemBundle); return systemBundle; } /** * Try to get the stupid service interface ... * * @param loader * @param string * @return * @throws IOException */ private List getMetaInfServices(ClassLoader loader, String factory) throws IOException { if (loader == null) loader = getClass().getClassLoader(); Enumeration e = loader.getResources("META-INF/services/" + factory); List factories = new ArrayList(); while (e.hasMoreElements()) { URL url = (URL) e.nextElement(); trace("found META-INF/services in %s", url); InputStream in = url.openStream(); try { BufferedReader rdr = new BufferedReader(new InputStreamReader(in, "UTF-8")); String line; while ((line = rdr.readLine()) != null) { trace(line); line = line.trim(); if (!line.startsWith("#") && line.length() > 0) { factories.add(line); } } } finally { in.close(); } } return factories; } public void addBundle(File resource) { parms.runbundles.add(resource.getAbsolutePath()); } private void delete(File f) { String path = f.getAbsolutePath(); char first = path.charAt(0); if (path.equals("/") || (first >= 'A' && first <= 'Z' && path.substring(1).equals(":\\"))) throw new IllegalArgumentException( "You can not make the root the storage area because it will be deleted"); if (f.isDirectory()) { File fs[] = f.listFiles(); for (int i = 0; i < fs.length; i++) delete(fs[i]); } f.delete(); } public void report(PrintStream out) { try { out.println("------------------------------- REPORT --------------------------"); out.println(); row(out, "Framework", systemBundle == null ? "<>" : systemBundle.getClass()); row(out, "Framework type", parms.services ? "META-INF/services" : "mini framework"); row(out, "Storage", parms.storageDir); row(out, "Keep", parms.keep); row(out, "Security", security); list(out, fill("Run bundles", 40), parms.runbundles); list(out, fill("Classpath", 40), split(System.getProperty("java.class.path"), File.pathSeparator)); list(out, fill("System Packages", 40), split(parms.systemPackages, ",")); row(out, "Properties"); for (Entry entry : properties.entrySet()) { String key = (String) entry.getKey(); String value = (String) entry.getValue(); row(out, key, value); } if (systemBundle != null) { BundleContext context = systemBundle.getBundleContext(); if (context != null) { Bundle bundles[] = context.getBundles(); out.println(); out.println("Id State Modified Location"); for (int i = 0; i < bundles.length; i++) { String loc = bundles[i].getLocation(); loc = loc.replaceAll("\\w+:", ""); File f = new File(loc); out.print(fill(Long.toString(bundles[i].getBundleId()), 6)); out.print(fill(toState(bundles[i].getState()), 6)); if (f.exists()) out.print(fill(toDate(f.lastModified()), 14)); else out.print(fill("<>", 14)); if (errors.containsKey(bundles[i])) { out.print(fill(loc, 50)); out.print(errors.get(bundles[i]).getMessage()); } else out.print(bundles[i].getLocation()); out.println(); } } } } catch (Throwable t) { error("Sorry, can't print framework: %s", t); } } private void row(PrintStream out, Object... parms) { boolean fill = true; for (Object p : parms) { if (fill) out.print(fill(p.toString(), 40)); else out.print(p.toString()); fill = false; } out.println(); } String toDate(long t) { Calendar c = Calendar.getInstance(); c.setTimeInMillis(t); return fill(c.get(Calendar.YEAR), 4) + fill(c.get(Calendar.MONTH), 2) + fill(c.get(Calendar.DAY_OF_MONTH), 2) + fill(c.get(Calendar.HOUR_OF_DAY), 2) + fill(c.get(Calendar.MINUTE), 2); } private String fill(int n, int width) { return fill(Integer.toString(n), width, '0', -1); } private String fill(String s, int width) { return fill(s, width, ' ', -1); } private String fill(String s, int width, char filler, int dir) { StringBuffer sb = new StringBuffer(); if (s.length() > width) { int half = (width - 1) / 2; return s.substring(0, half) + ".." + s.substring(s.length() - half); } width -= s.length(); int before = (dir == 0) ? width / 2 : (dir < 0) ? 0 : width; int after = width - before; while (before-- > 0) sb.append(filler); sb.append(s); while (after-- > 0) sb.append(filler); return sb.toString(); } private String toState(int state) { switch (state) { case Bundle.INSTALLED: return "INSTL"; case Bundle.RESOLVED: return "RSLVD"; case Bundle.STARTING: return "STRTD"; case Bundle.STOPPING: return "STPPD"; case Bundle.ACTIVE: return "ACTIV"; case Bundle.UNINSTALLED: return "UNNST"; } return "? " + state; } private void list(PrintStream out, String del, List l) { for (Object o : l) { String s = o.toString(); out.print(del); out.println(s); del = fill(" ", 40); } } public int translateToError(BundleException e) { switch (e.getType()) { case BundleException.ACTIVATOR_ERROR: return LauncherConstants.ACTIVATOR_ERROR; case BundleException.DUPLICATE_BUNDLE_ERROR: return LauncherConstants.DUPLICATE_BUNDLE; case BundleException.RESOLVE_ERROR: return LauncherConstants.RESOLVE_ERROR; case BundleException.INVALID_OPERATION: case BundleException.MANIFEST_ERROR: case BundleException.NATIVECODE_ERROR: case BundleException.STATECHANGE_ERROR: case BundleException.UNSUPPORTED_OPERATION: case BundleException.UNSPECIFIED: default: return ERROR; } } public String translateToMessage(BundleException e) { switch (e.getType()) { case BundleException.ACTIVATOR_ERROR: Throwable t = e.getCause(); StackTraceElement[] stackTrace = t.getStackTrace(); if (stackTrace == null || stackTrace.length == 0) return "activator error " + t.getMessage(); StackTraceElement top = stackTrace[0]; return "activator error " + t.getMessage() + " from: " + top.getClassName() + ":" + top.getMethodName() + "#" + top.getLineNumber(); case BundleException.DUPLICATE_BUNDLE_ERROR: case BundleException.RESOLVE_ERROR: case BundleException.INVALID_OPERATION: case BundleException.MANIFEST_ERROR: case BundleException.NATIVECODE_ERROR: case BundleException.STATECHANGE_ERROR: case BundleException.UNSUPPORTED_OPERATION: case BundleException.UNSPECIFIED: default: return e.getMessage(); } } static PermissionCollection all = new AllPermissionCollection(); class AllPolicy extends Policy { public PermissionCollection getPermissions(CodeSource codesource) { trace("Granting AllPermission to %s", codesource.getLocation()); return all; } public void refresh() { trace("Policy refresh"); } } static class AllPermissionCollection extends PermissionCollection { private static final long serialVersionUID = 1L; private static Vector list = new Vector(); static { list.add(new AllPermission()); } { setReadOnly(); } public void add(Permission permission) { } public Enumeration elements() { return list.elements(); } public boolean implies(Permission permission) { return true; } } public synchronized void serviceChanged(ServiceEvent event) { if (event.getType() == ServiceEvent.REGISTERED) { mainThread = (Runnable) systemBundle.getBundleContext().getService( event.getServiceReference()); notifyAll(); } } public void trace(String msg, Object... objects) { if (parms.trace) { message("# ", msg, objects); } } private void message(String prefix, String string, Object[] objects) { Throwable e = null; StringBuffer sb = new StringBuffer(); int n = 0; sb.append(prefix); for (int i = 0; i < string.length(); i++) { char c = string.charAt(i); if (c == '%') { c = string.charAt(++i); switch (c) { case 's': if (n < objects.length) { Object o = objects[n++]; if (o instanceof Throwable) { e = (Throwable) o; if (o instanceof BundleException) { sb.append(translateToMessage((BundleException) o)); } else if (o instanceof InvocationTargetException) { Throwable t = (InvocationTargetException) o; sb.append(t.getMessage()); e = t; } else sb.append(e.getMessage()); } else { sb.append(o); } } else sb.append(""); break; default: sb.append(c); } } else { sb.append(c); } } out.println(sb); if (e != null && parms.trace) e.printStackTrace(out); out.flush(); } public void error(String msg, Object... objects) { message("! ", msg, objects); } } bnd-1.50.0/biz.aQute.launcher/src/aQute/launcher/SimplePermissionPolicy.java0000644000175000017500000001322311656076535026711 0ustar drazzibdrazzibpackage aQute.launcher; import java.io.*; import java.net.*; import java.util.*; import org.osgi.framework.*; import org.osgi.service.permissionadmin.*; /** * Implements a permissionpolicy. It will tried to read a resource from the * bundle. This resource should have the following format: * *
 * 
 * 
 *    '(' permission-class [ '"' name-parameter '"' [ '"' action [ ',' action ] ... '"' ] ] ')'
 *   Or
 *    '#' *
 * 
 * 
 * 
* * Each valid line is translated into a PermissionInfo object and these objects * together form the permissions for a specific bundle. The class will also * attempt to read a file called "default.perm" from the current bundle that * will have the same format. This is used for the default permissions. *

* If there is no permission admin service, this class does nothing relevant. */ public class SimplePermissionPolicy implements SynchronousBundleListener { static final String DEFAULT_PERMISSION_RESOURCE = "default.perm"; BundleContext context; List bundles; PermissionInfo[] defaultPermissions; final Launcher launcher; /** * Create a new permission policy. This will set the default permissions and * the permissions for this bundle (if the resource is present). */ SimplePermissionPolicy(Launcher launcher, BundleContext context) throws Exception { this.launcher = launcher; this.context = context; bundles = new ArrayList(); context.addBundleListener(this); PermissionAdmin permissionAdmin = getPermissionAdmin(); if (permissionAdmin == null) /* no permission admin service */{ launcher.trace("no permission admin available => ! security"); return; } // Set the default permissions. InputStream in = getClass().getResourceAsStream(DEFAULT_PERMISSION_RESOURCE); if (in != null) { PermissionInfo[] info; try { info = parse(in); } finally { in.close(); } permissionAdmin.setDefaultPermissions(info); launcher.trace("Found default permission resource %s", DEFAULT_PERMISSION_RESOURCE); } else { launcher.trace("No default permission resource %s", DEFAULT_PERMISSION_RESOURCE); } // // Set this bundles permissions. // Bundle self = context.getBundle(); setPermissions(self); } /** * Sets the permissions of a bundle from a resource, if exists. */ public void setPermissions(Bundle bundle) { PermissionAdmin permissionAdmin = getPermissionAdmin(); if (permissionAdmin == null) /* no permission admin service */{ return; } PermissionInfo[] info = getPermissions(bundle); if (info == null) { launcher.trace("Using default permissions for %s", bundle.getLocation()); info = defaultPermissions; } else launcher.trace("For permissions inside bundle %s", bundle.getLocation()); if (info != null && info.length > 0) { bundles.add(bundle); permissionAdmin.setPermissions(bundle.getLocation(), info); } else launcher.trace("No permissions for %s", bundle.getLocation()); } /** * Get the resource and parse it into PermissionInfo objects. */ public PermissionInfo[] getPermissions(Bundle bundle) { URL url = bundle.getEntry("/OSGI-INF/permissions.perm"); if (url == null) url = bundle.getEntry("/OSGI-INF/permissions.perm".toUpperCase()); PermissionInfo[] info = null; if (url != null) try { InputStream in = url.openStream(); info = parse(in); } catch (IOException e) { System.out.println("Unable to read permission info for bundle " + bundle.getLocation() + " " + e); } return info; } /** * Parse a permission info file. */ public PermissionInfo[] parse(InputStream in) throws IOException { PermissionInfo[] info = null; if (in != null) { List permissions = new ArrayList(); try { BufferedReader reader = new BufferedReader(new InputStreamReader(in, "UTF8")); String line; while ((line = reader.readLine()) != null) { line = line.trim(); if ((line.length() == 0) || line.startsWith("#") || line.startsWith("//")) /* comments */ continue; try { permissions.add(new PermissionInfo(line)); } catch (IllegalArgumentException iae) { /* incorrectly encoded permission */ System.out.println("Permission incorrectly encoded: " + line + " " + iae); } } } finally { in.close(); } int size = permissions.size(); if (size > 0) { info = new PermissionInfo[size]; info = permissions.toArray(info); } } return info; } /** * Clear the permissions for a bundle. */ public void clearPermissions(Bundle bundle) { PermissionAdmin permissionAdmin = getPermissionAdmin(); if (permissionAdmin == null) /* no permission admin service */ return; if (bundles.remove(bundle)) { permissionAdmin.setPermissions(bundle.getLocation(), null); } } private PermissionAdmin getPermissionAdmin() { ServiceReference ref = context.getServiceReference(PermissionAdmin.class.getName()); if (ref == null) return null; return (PermissionAdmin) context.getService(ref); } /** * Event when a bundle has changed so we need to inspect if it is installed, * and if so we need to set the permissions or remove it when it is * uninstalled. */ public void bundleChanged(BundleEvent event) { Bundle bundle = event.getBundle(); if (bundle.getBundleId() == 0) /* ignore the system bundle */ return; int type = event.getType(); switch (type) { case BundleEvent.INSTALLED: case BundleEvent.UPDATED: setPermissions(bundle); break; case BundleEvent.UNINSTALLED: clearPermissions(bundle); break; } } public void setDefaultPermissions(PermissionInfo defaultPermissions[]) { this.defaultPermissions = defaultPermissions; } } bnd-1.50.0/biz.aQute.launcher/src/aQute/launcher/constants/0000755000175000017500000000000011656076535023377 5ustar drazzibdrazzibbnd-1.50.0/biz.aQute.launcher/src/aQute/launcher/constants/LauncherConstants.java0000644000175000017500000001015711656076535027704 0ustar drazzibdrazzibpackage aQute.launcher.constants; import java.io.*; import java.util.*; public class LauncherConstants { public final static String LAUNCHER_PROPERTIES = "launcher.properties"; public final static String LAUNCHER_ARGUMENTS = "launcher.arguments"; public final static String LAUNCHER_READY = "launcher.ready"; // MUST BE ALIGNED WITH ProjectLauncher! Donot want to create coupling // so cannot refer. public final static int OK = 0; public final static int ERROR = -2; public final static int WARNING = -1; public final static int TIMEDOUT = -3; public final static int UPDATE_NEEDED = -4; public final static int CANCELED = -5; public final static int DUPLICATE_BUNDLE = -6; public final static int RESOLVE_ERROR = -7; public final static int ACTIVATOR_ERROR = -8; // Start custom errors from here public final static int CUSTOM_LAUNCHER = -128; // Local names final static String LAUNCH_SERVICES = "launch.services"; final static String LAUNCH_STORAGE_DIR = "launch.storage.dir"; final static String LAUNCH_KEEP = "launch.keep"; final static String LAUNCH_RUNBUNDLES = "launch.bundles"; final static String LAUNCH_SYSTEMPACKAGES = "launch.system.packages"; final static String LAUNCH_TRACE = "launch.trace"; final static String LAUNCH_TIMEOUT = "launch.timeout"; final static String LAUNCH_ACTIVATORS = "launch.activators"; /** * The command line arguments of the launcher. Launcher are not supposed to * eat any arguments, they should use -D VM arguments so that applications * can leverage the command line. The launcher must register itself as a * service under its impl. class with this property set to a String[]. */ public boolean services; public File storageDir = new File(""); public boolean keep; public final List runbundles = new ArrayList(); public String systemPackages; public boolean trace; public long timeout; public final List activators = new ArrayList(); public Map runProperties = new HashMap(); /** * Translate a constants to properties. * * @return */ public Properties getProperties() { Properties p = new Properties(); p.setProperty(LAUNCH_SERVICES, services + ""); p.setProperty(LAUNCH_STORAGE_DIR, storageDir.getAbsolutePath()); p.setProperty(LAUNCH_KEEP, keep + ""); p.setProperty(LAUNCH_RUNBUNDLES, join(runbundles, ",")); if (systemPackages != null) p.setProperty(LAUNCH_SYSTEMPACKAGES, systemPackages + ""); p.setProperty(LAUNCH_TRACE, trace + ""); p.setProperty(LAUNCH_TIMEOUT, timeout + ""); p.setProperty(LAUNCH_ACTIVATORS, join(activators, ",")); for (Map.Entry entry : runProperties.entrySet()) { if (entry.getValue() == null) p.remove(entry.getKey()); else p.put(entry.getKey(), entry.getValue()); } return p; } /** * Empty constructor for the plugin */ public LauncherConstants() { } /** * Create a constants from properties. * * @param p */ public LauncherConstants(Properties p) { services = Boolean.valueOf(p.getProperty(LAUNCH_SERVICES)); storageDir = new File(p.getProperty(LAUNCH_STORAGE_DIR)); keep = Boolean.valueOf(p.getProperty(LAUNCH_KEEP)); runbundles.addAll(split(p.getProperty(LAUNCH_RUNBUNDLES), ",")); systemPackages = p.getProperty(LAUNCH_SYSTEMPACKAGES); trace = Boolean.valueOf(p.getProperty(LAUNCH_TRACE)); timeout = Long.parseLong(p.getProperty(LAUNCH_TIMEOUT)); activators.addAll(split(p.getProperty(LAUNCH_ACTIVATORS), " ,")); Map map = (Map) p; runProperties.putAll(map); } private Collection split(String property, String string) { List result = new ArrayList(); StringTokenizer st = new StringTokenizer(property, string); while (st.hasMoreTokens()) { result.add(st.nextToken()); } return result; } private static String join(List runbundles2, String string) { StringBuffer sb = new StringBuffer(); String del = ""; for (Object r : runbundles2) { sb.append(del); sb.append(r); del = string; } return sb.toString(); } } bnd-1.50.0/biz.aQute.launcher/README0000644000175000017500000000012111656076535016566 0ustar drazzibdrazzibThe launcher project is a launcher plugin that extends the ProjectLauncher.java bnd-1.50.0/biz.aQute.launcher/.settings/0000755000175000017500000000000011656076535017632 5ustar drazzibdrazzibbnd-1.50.0/biz.aQute.launcher/.settings/org.eclipse.jdt.core.prefs0000644000175000017500000000116011656076535024612 0ustar drazzibdrazzib#Mon May 24 10:59:53 CEST 2010 eclipse.preferences.version=1 org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled org.eclipse.jdt.core.compiler.codegen.targetPlatform=jsr14 org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve org.eclipse.jdt.core.compiler.compliance=1.4 org.eclipse.jdt.core.compiler.debug.lineNumber=generate org.eclipse.jdt.core.compiler.debug.localVariable=generate org.eclipse.jdt.core.compiler.debug.sourceFile=generate org.eclipse.jdt.core.compiler.problem.assertIdentifier=warning org.eclipse.jdt.core.compiler.problem.enumIdentifier=warning org.eclipse.jdt.core.compiler.source=1.5 bnd-1.50.0/biz.aQute.launcher/.settings/org.eclipse.core.resources.prefs0000644000175000017500000000012511656076535026043 0ustar drazzibdrazzib#Mon Sep 19 11:00:09 EDT 2005 eclipse.preferences.version=1 encoding/=UTF-8 bnd-1.50.0/biz.aQute.launcher/.settings/org.eclipse.core.runtime.prefs0000644000175000017500000000011611656076535025514 0ustar drazzibdrazzib#Tue Dec 14 12:22:25 EST 2010 eclipse.preferences.version=1 line.separator=\n bnd-1.50.0/biz.aQute.bnd/0000755000175000017500000000000011656076535014656 5ustar drazzibdrazzibbnd-1.50.0/biz.aQute.bnd/META-INF/0000755000175000017500000000000011656076535016016 5ustar drazzibdrazzibbnd-1.50.0/biz.aQute.bnd/META-INF/MANIFEST.MF0000644000175000017500000000224311656076535017451 0ustar drazzibdrazzibManifest-Version: 1 Bundle-ManifestVersion: 2 Bundle-Version: 0.0.0 Bundle-Name: bnd Bundle-SymbolicName: biz.aQute.bnd; singleton:=true Bundle-ClassPath: .,tmp/biz.aQute.bnd.jar Bundle-Activator: aQute.bnd.plugin.Activator Require-Bundle: org.eclipse.ui.ide;bundle-version="[3.3.0, 4.0.0)", org.eclipse.jface.text;bundle-version="[3.3.0, 4.0.0)", org.eclipse.ui.workbench.texteditor;bundle-version="[3.3.0, 4.0.0)", org.eclipse.ui.editors;bundle-version="[3.3.0, 4.0.0)", org.eclipse.ui;bundle-version="[3.3.0, 4.0.0)", org.eclipse.debug.ui;bundle-version="[3.3.0, 4.0.0)", org.eclipse.jdt.core;bundle-version="[3.3.0, 4.0.0)", org.eclipse.jdt.ui;bundle-version="[3.3.0, 4.0.0)", org.eclipse.core.runtime;bundle-version="[3.2.0, 4.0.0)", org.eclipse.jdt.launching;bundle-version="[3.2.0, 4.0.0)", org.eclipse.jdt.debug.ui;bundle-version="[3.2.0, 4.0.0)", org.eclipse.jdt.junit;bundle-version="[3.2.0, 4.0.0)", org.junit, org.eclipse.osgi.services, org.apache.ant, org.eclipse.ui.console Bundle-RequiredExecutionEnvironment: J2SE-1.5 Bundle-Description: A utility and plugin to wrap, build, print, or otherwise manipulate bundles Bundle-ActivationPolicy: lazy bnd-1.50.0/biz.aQute.bnd/plugin.xml0000755000175000017500000002076311656076535016711 0ustar drazzibdrazzib bnd-1.50.0/biz.aQute.bnd/LICENSE0000755000175000017500000002613611656076535015676 0ustar drazzibdrazzib Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. bnd-1.50.0/biz.aQute.bnd/biz.aQute.bnd.bnd0000644000175000017500000000102211656076535017742 0ustar drazzibdrazzib-sources: true -include: ~META-INF/MANIFEST.MF Include-Resource: plugin.xml, icons=icons, LICENSE, embedded-repo.jar Private-Package: aQute.bnd.*, aQute.lib.* #, org.osgi.service.component.annotations Conditional-Package: aQute.libg.* Export-Package: aQute.bnd.service.*, org.osgi.service.bindex Import-Package: !org.eclipse.*,org.apache.tools.ant;resolution:=optional,org.osgi.service.bindex,* Bundle-ClassPath: . Main-Class: aQute.bnd.main.bnd Bundle-Version: ${^Bundle-Version} bnd-1.50.0/biz.aQute.bnd/build.xml0000644000175000017500000000017711656076535016504 0ustar drazzibdrazzib bnd-1.50.0/biz.aQute.bnd/local0000755000175000017500000000014411656076535015675 0ustar drazzibdrazzib#!/bin/sh java -cp ../biz.aQute.bndlib/bin:../aQute.libg/bin:bin aQute.bnd.main.bnd -exceptions $1 bnd-1.50.0/biz.aQute.bnd/icons/0000755000175000017500000000000011656076535015771 5ustar drazzibdrazzibbnd-1.50.0/biz.aQute.bnd/icons/host.gif0000644000175000017500000000020111656076535017426 0ustar drazzibdrazzibGIF89a³ÿ_?C|¿?·ÿ?¼¿?}?_?Cÿÿÿÿÿÿ,@6ÐÈI+=%ƒBH¶Y†…ÖD”hZC °î žA«x®§lÛ²•ë5 RX„gP³ Ánš‹;bnd-1.50.0/biz.aQute.bnd/icons/installed.gif0000644000175000017500000000026311656076535020440 0ustar drazzibdrazzibGIF89a³ÿÿÿÿÿŸŸÿÿßß¿¿¿¿ŸŸŸ€€€___ÿÿÿ!ù ,@`PÉI«(¡ÃC(GA CÐn HAÛˆa’{|¡Á¨”2/WÌT¬Œ†ƒIæëí¨Ö,uH€0a Ep"Ãà‘ÀŽ~Âuù©5‘ÙˆvmÚCe6=XY‚;bnd-1.50.0/biz.aQute.bnd/icons/inuse.gif0000644000175000017500000000054011656076535017602 0ustar drazzibdrazzibGIF89aÕÿÿÿÿÿÿÿÿÿß?ýýüüÿûú÷÷úññõððñêéààçßß¿ßߟÝÝÜÜæÕÖÖÿÀÊ¿¿¿¾¾¿¸·²±«ª¸  ¤Ÿ¿¿ŸŸŸ””““‰‰˜‡‡•€€€~~†utkkoggccgaak___\[LLMGF@@?_Ÿ==<<;;99=993332,// €ÿÿÿ!ù8,@z@œpH,â¦äƒY žU@¥>J©HtÐ0nÛÀèÌ6Rbu 8|hS€ä5R@·B$àÆ¬,PiG7+6ˆkqlUŒk2!‚yT0E"*wO‚zU Nœy&ab6('xG`·d %p–FBA;A;bnd-1.50.0/biz.aQute.bnd/icons/importing-bundle.gif0000644000175000017500000000034611656076535021742 0ustar drazzibdrazzibGIF89aÄÿÿÿÿÿÿÿß?ÿÞ{ÿ½9ßß¿ßߟޜ9ÆÆÆ¿¿¿½½œ½½{½{9  ¤Ÿ¿¿ŸŸŸ€€€{Z9___Z99?_Ÿ99Z€,@k Žd)J(Ô40Ä1!¤½G“2>…‹á"°& šI¤`D*Æ¡;œ1cv\¾V¶7º$‹zÉ>¶E‹È7È-ó˜.+}Gþ]#b|#CDFW $ B•FJoo!;bnd-1.50.0/biz.aQute.bnd/icons/resolved.gif0000644000175000017500000000020411656076535020277 0ustar drazzibdrazzibGIF89a¢ßß¿ÿÿÿ¿¿¿ŸŸŸ€€€___ÀÀÀÿÿÿ!ù,@IhºÜLP$¥ 89ޱe†"AêÙ@Ñ_³ET\¸hïÔ½ ‡á)LN cT«‚”ô, Ëfc°ã ¸Ÿ(î%;bnd-1.50.0/biz.aQute.bnd/icons/unknown.gif0000644000175000017500000000011711656076535020156 0ustar drazzibdrazzibGIF89a¢ÿÿÿ¿¿¿___ÿÿÿ!ù,ºA$€™‹l%_1( 8%;bnd-1.50.0/biz.aQute.bnd/icons/registered.gif0000644000175000017500000000053511656076535020620 0ustar drazzibdrazzibGIF89aÕÿÿÿÿÿÿÿÿÿß?ýýüüÿøø÷÷úððñêéééïèééààçßß¿ßߟÝÝÜÜæÖÖÄÄпÀÊ¿¿¿¾¾¿¸·²±  ¬  ¤Ÿ¿¿ŸŸŸ””““‰‰˜‡‡•††€€€llvkkoggccgaak___\[OOSLLMEEAA @@?_Ÿ<<;;99=9900%// €ÿÿÿ!ù8,@z@œp(œŽ¡LÆ…CŒXtÊ"âØ,vÓ¸9nÛU+I¡‚*Q«=nð3{øÈ8oŠÆeë13 SRjClY &4VŒWnYs‡F_`bl&^Ÿ˜1$ “8 )+ƒ„VY "/T±‡4…E¨¢DA;bnd-1.50.0/biz.aQute.bnd/icons/active.gif0000644000175000017500000000162211656076535017734 0ustar drazzibdrazzibGIF89a÷ÿÿÿÿÆÆÆZ99{Z9½{9Þœ9ÿ½9ÿÞ{½½œ½½{99Z,@wH°àÀX˜pa"hX`ÀB€€€€DÜÈ‘ÀlDh @“- x)¥K‹/3’ܹSO Àx âFC[ZŒ©r HE)õ£ÏH.}Ù”`‚s&àâÏŸ;bnd-1.50.0/biz.aQute.bnd/icons/export-package.gif0000644000175000017500000000171411656076535021375 0ustar drazzibdrazzibGIF89a÷ÿÿÿÿÿÿfÿÌfÿÌ3ÌÌÌÌ̙̙3Ìf3™ÌÌ™™™ff3f333f™33fˆ»»»ªªªˆˆˆUUUÿÿÌÿÿ™ÿÿ3ÿÿÿÌÿÿÌÌÿÌ™ÿÌÿ™ÿÿ™Ìÿ™™ÿ™fÿ™3ÿ™ÿfÿÿfÌÿf™ÿffÿf3ÿfÿ3ÿÿ3Ìÿ3™ÿ3fÿ33ÿ3ÿÿÿÌÿ™ÿfÿ3ÿÌÿÿÌÿÌÌÿ™ÌÿfÌÿ3ÌÿÌÌÿÌÌfÌÌ3ÌÌÌ™ÿÌ™ÌÌ™™Ì™fÌ™ÌfÿÌfÌÌf™ÌffÌfÌ3ÿÌ3ÌÌ3™Ì3fÌ33Ì3ÌÿÌÌÌ™ÌfÌ3Ì™ÿÿ™ÿÌ™ÿ™™ÿf™ÿ3™ÿ™Ìÿ™Ì™™Ìf™Ì3™Ì™™ÿ™™Ì™™f™™3™™™fÿ™fÌ™f™™ff™f3™f™3ÿ™3Ì™3™™3f™33™3™ÿ™Ì™™™f™3™fÿÿfÿÌfÿ™fÿffÿ3fÿfÌÿfÌÌfÌ™fÌffÌ3fÌf™ÿf™Ìf™™f™ff™3f™ffÿffÌff™ffffff3ÿf3Ìf3™f3ff3fÿfÌf™fff3f3ÿÿ3ÿÌ3ÿ™3ÿf3ÿ33ÿ3Ìÿ3ÌÌ3Ì™3Ìf3Ì33Ì3™ÿ3™Ì3™™3™f3™33™3fÿ3fÌ3ff3f33f33ÿ33Ì33™333333ÿ3Ì3™3f333ÿÿÿÌÿ™ÿfÿ3ÿÌÿÌÌÌ™ÌfÌ3Ì™ÿ™Ì™™™f™3™fÿfÌf™fff3f3ÿ3Ì3™3f333ÿÌ™f3îÝ»ªˆwUD"îÝ»ªˆwUD"îÝ»ªwUD"îîîÝÝÝwwwDDD"""ÿÿü!ùÿ,@©8PÂ" $``A? hôkàÐá„þ T AÃh$Ø7¡À ö3p€åJ1-û ÔHP F &è¬À€‚   9á’nühÀÀ‚ M1f¬©’êT«,Ð3¢W™ZMNPO @ƒ(ð ¤ ) $&V³ƒöóØTæÕ¹ÂXxðL›ú)6·R¿RiÞ%ø/ ;bnd-1.50.0/biz.aQute.bnd/icons/bundle.gif0000644000175000017500000000162211656076535017732 0ustar drazzibdrazzibGIF89a÷ÿÿÿÿÆÆÆZ99{Z9½{9Þœ9ÿ½9ÿÞ{½½œ½½{99Z,@wH°àÀX˜pa"hX`ÀB€€€€DÜÈ‘ÀlDh @“- x)¥K‹/3’ܹSO Àx âFC[ZŒ©r HE)õ£ÏH.}Ù”`‚s&àâÏŸ;bnd-1.50.0/biz.aQute.bnd/icons/fragment.gif0000644000175000017500000000024411656076535020263 0ustar drazzibdrazzibGIF89a³_?C|¿?·ÿ?¼¿?}?_?Cÿÿÿÿÿÿ!ù,QÉI«­æRÃ{¿^xI˜Å˜@9¤Rç< ‚Ñ ÂTB¯Éi@(¬^†AQ 5o¸`UÉ v…ð5+‘/´YR­æÚšÉz;bnd-1.50.0/biz.aQute.bnd/icons/module.gif0000644000175000017500000000024411656076535017745 0ustar drazzibdrazzibGIF89a³_?C|¿?·ÿ?¼¿?}?_?Cÿÿÿÿÿÿ!ù,QÉI«­æRÃ{¿^xI˜Å˜@9¤Rç< ‚Ñ ÂTB¯Éi@(¬^†AQ 5o¸`UÉ v…ð5+‘/´YR­æÚšÉz;bnd-1.50.0/biz.aQute.bnd/icons/run.gif0000644000175000017500000000206611656076535017270 0ustar drazzibdrazzibGIF89aÄÿÿÿÿûøÇûÕúøòè¼ìÞ´ëܳëÛ³êÛ²æÓ¬ßÇ£Ù¼šÖ·–Õ·—Õ·–Õ¶—Õ¶–Ó±’˦‰ÉÉýÇž‚Æž‚¿’w¿‘w¾’v¸†l·†l­u]žpX_??,@b ŽdInA@$Â00ÖVhÁp.³&P ΆÁëùtBÆ ·ƒ¹”ÌFF¢-$¹ØÎÈåvF‚-Pà“"‰Av¾(©Ãá´\xç;bJ/1r3Zj%a|]!;À¦ÿÿÿÿЦî<”ÒøààîLï!î<î< ïT'‘| î<7)‘|Ðï3‘|Ðï—+î<¨îh£( •Î ;œÌ"SL†É@€4‡ÒY"I8Db'òÀdhŬ£Éa‘˜MèÑ]³Õr2<§EGÈ„—Z0RWYABDU;#@Dwh’“!;bnd-1.50.0/biz.aQute.bnd/icons/property.gif0000644000175000017500000000013511656076535020343 0ustar drazzibdrazzibGIF89a¢ÀÀÀŸŸŸ€€€___ÿÿÿ!ù,"XºÜþ0ÊÙ† Ep¥Þ\ôÀ[@ˆ :i.%¬XmßT;bnd-1.50.0/biz.aQute.bnd/icons/mini-logo.gif0000644000175000017500000000162211656076535020353 0ustar drazzibdrazzibGIF89a÷ÿÿÿÿÆÆÆZ99{Z9½{9Þœ9ÿ½9ÿÞ{½½œ½½{99Z,@wH°àÀX˜pa"hX`ÀB€€€€DÜÈ‘ÀlDh @“- x)¥K‹/3’ܹSO Àx âFC[ZŒ©r HE)õ£ÏH.}Ù”`‚s&àâÏŸ;bnd-1.50.0/biz.aQute.bnd/icons/logo16x16.gif0000644000175000017500000000055011656076535020126 0ustar drazzibdrazzibGIF89aÕeRqjWuxjŠv“„x“‰|˜š¨ž”«¢™®¦²ª¢µ¯¦¹±¨º·¯Àº³ÃÃ½ÊÆÁÍËÆÓÍÈÔÒÎØÕÑÛÙÕÞÚØßÞÓÊÞÜæáßèäáçæÝÔçåêèåëéâÜêèíîîóðïòòñôõêÛø÷øúæÄúîÙûêËûìÓûðÜüèÆüôãüöêýúóýýý!ù,…@—pè:­ˆÈá1Åjµ’D«‰:BK®Öª™Êb‘¬å¶Ë„vWh.4;Ú\.”“î÷À !: #&&#. C-(…]B!Q(’D  B(''”$."¦'#I" &§# }k.)*FÃCÅÇHA;bnd-1.50.0/biz.aQute.bnd/icons/test.gif0000644000175000017500000000051711656076535017442 0ustar drazzibdrazzibGIF89a³ÿÿÿÿûøÇòçºëܳäΩÀÀÀÕ·—Æž‚¿’w·†l­u]£  žpXyO@_??!ù,@H°ÈI«| d°¶Ö¥ƒÁ„¡X"³²•â²Omßxï7쳎Ÿd4`/ É€h¤ ¦CåX;! `»árC¢„ ¡Hú‚Ba;Âl:Ÿ€§Ôi¬ú,Ö@ x¦D-ñ¨èÄÕj³Þ-Tl¤2͵àC¶b³Y!;!ù",l@‘pH,‡¡c±0ùl>“‚²ð6€ÀGº¬$Á"²-N‡¤xX<“âñÈ|@ŽJçó!†6€ ‚‚€ICU V}D  uP] j|\DTN¢SMOQJ~®°±®A;bnd-1.50.0/biz.aQute.bnd/bnd.bnd0000644000175000017500000000201411656076535016103 0ustar drazzibdrazzib-dependson: biz.aQute.junit, biz.aQute.launcher, demo Bundle-Version: 1.48.0 Bundle-License: http://www.opensource.org/licenses/apache2.0.php; \ description="${Bundle-Copyright}"; \ link=LICENSE -sub: *.bnd -buildpath: biz.aQute.bndlib;version=project,\ aQute.libg;version=project,\ com.springsource.junit,\ org.eclipse.core.runtime,\ org.eclipse.core.resources,\ org.eclipse.core.commands,\ org.eclipse.debug.ui,\ org.eclipse.debug.core,\ org.eclipse.jdt.core,\ org.eclipse.jdt.debug.ui,\ org.eclipse.jdt.junit,\ org.eclipse.jdt.launching,\ org.eclipse.jdt.ui,\ org.eclipse.jface,\ org.eclipse.jface.text,\ org.eclipse.text,\ org.eclipse.ui,\ org.eclipse.ui.workbench,\ org.eclipse.ui.editors,\ org.eclipse.ui.ide,\ org.eclipse.ui.workbench.texteditor,\ org.eclipse.swt.carbon.macosx,\ org.eclipse.core.jobs,\ org.eclipse.equinox.common,\ org.eclipse.equinox.registry,\ org.apache.tools.ant,\ osgi.cmpn,\ osgi.core;version=4.1,\ junit.osgi,\ org.osgi.impl.bundle.bindex bnd-1.50.0/biz.aQute.bnd/.classpath0000644000175000017500000000100411656076535016634 0ustar drazzibdrazzib bnd-1.50.0/biz.aQute.bnd/.project0000644000175000017500000000120611656076535016324 0ustar drazzibdrazzib biz.aQute.bnd org.eclipse.jdt.core.javabuilder org.eclipse.pde.ManifestBuilder org.eclipse.pde.SchemaBuilder org.eclipse.jdt.core.javanature org.eclipse.pde.PluginNature bnd-1.50.0/biz.aQute.bnd/bnd/0000755000175000017500000000000011656076535015421 5ustar drazzibdrazzibbnd-1.50.0/biz.aQute.bnd/bnd/embedded-repo.bnd0000644000175000017500000000031611656076535020602 0ustar drazzibdrazzib-resourceonly: true Include-Resource: \ biz.aQute.launcher/biz.aQute.launcher-latest.jar=${repo;biz.aQute.launcher;snapshot}, \ biz.aQute.junit/biz.aQute.junit-latest.jar=${repo;biz.aQute.junit;snapshot} bnd-1.50.0/biz.aQute.bnd/build.properties0000644000175000017500000000013011656076535020065 0ustar drazzibdrazzibsource.. = src/ bin.includes = plugin.xml,\ META-INF/,\ . bnd-1.50.0/biz.aQute.bnd/annotation.bnd0000755000175000017500000000034411656076535017521 0ustar drazzibdrazzibBundle-Name: bnd Annotations Library Bundle-Description: Contains only the annotations for bnd. Bundle-DocURL: http://www.aQute.biz/Code/Bnd Export-Package: aQute.bnd.annotation.*, aQute.bnd.test bnd-1.50.0/biz.aQute.bnd/test/0000755000175000017500000000000011656076535015635 5ustar drazzibdrazzibbnd-1.50.0/biz.aQute.bnd/test/ws/0000755000175000017500000000000011656076535016266 5ustar drazzibdrazzibbnd-1.50.0/biz.aQute.bnd/test/ws/p4-sub/0000755000175000017500000000000011656076535017400 5ustar drazzibdrazzibbnd-1.50.0/biz.aQute.bnd/test/ws/p4-sub/generated/0000755000175000017500000000000011656076535021336 5ustar drazzibdrazzibbnd-1.50.0/biz.aQute.bnd/src/0000755000175000017500000000000011656076535015445 5ustar drazzibdrazzibbnd-1.50.0/biz.aQute.bnd/src/biz/0000755000175000017500000000000011656076535016231 5ustar drazzibdrazzibbnd-1.50.0/biz.aQute.bnd/src/biz/aqute/0000755000175000017500000000000011656076535017350 5ustar drazzibdrazzibbnd-1.50.0/biz.aQute.bnd/src/biz/aqute/bnd/0000755000175000017500000000000011656076535020113 5ustar drazzibdrazzibbnd-1.50.0/biz.aQute.bnd/src/biz/aqute/bnd/eclipse/0000755000175000017500000000000011656076535021537 5ustar drazzibdrazzibbnd-1.50.0/biz.aQute.bnd/src/biz/aqute/bnd/eclipse/popup/0000755000175000017500000000000011656076535022702 5ustar drazzibdrazzibbnd-1.50.0/biz.aQute.bnd/src/biz/aqute/bnd/eclipse/popup/Refresh.java0000644000175000017500000000166111656076535025147 0ustar drazzibdrazzibpackage biz.aqute.bnd.eclipse.popup; import org.eclipse.jface.action.IAction; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.viewers.ISelection; import org.eclipse.swt.widgets.Shell; import org.eclipse.ui.IObjectActionDelegate; import org.eclipse.ui.IWorkbenchPart; public class Refresh implements IObjectActionDelegate { /** * Constructor for Action1. */ public Refresh() { super(); } /** * @see IObjectActionDelegate#setActivePart(IAction, IWorkbenchPart) */ public void setActivePart(IAction action, IWorkbenchPart targetPart) { } /** * @see IActionDelegate#run(IAction) */ public void run(IAction action) { Shell shell = new Shell(); MessageDialog.openInformation( shell, "aQute Bundle Tool", "New Action was executed."); } /** * @see IActionDelegate#selectionChanged(IAction, ISelection) */ public void selectionChanged(IAction action, ISelection selection) { } } bnd-1.50.0/biz.aQute.bnd/src/swing2swt/0000755000175000017500000000000011656076535017414 5ustar drazzibdrazzibbnd-1.50.0/biz.aQute.bnd/src/swing2swt/layout/0000755000175000017500000000000011656076535020731 5ustar drazzibdrazzibbnd-1.50.0/biz.aQute.bnd/src/swing2swt/layout/AWTLayout.java0000644000175000017500000000470311656076535023431 0ustar drazzibdrazzib/* ----------------------------------------------------------------------------- (c) Copyright IBM Corp. 2003 All rights reserved. The sample program(s) is/are owned by International Business Machines Corporation or one of its subsidiaries ("IBM") and is/are copyrighted and licensed, not sold. You may copy, modify, and distribute this/these sample program(s) in any form without payment to IBM, for any purpose including developing, using, marketing or distributing programs that include or are derivative works of the sample program(s). The sample program(s) is/are provided to you on an "AS IS" basis, without warranty of any kind. IBM HEREBY EXPRESSLY DISCLAIMS ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. Some jurisdictions do not allow for the exclusion or limitation of implied warranties, so the above limitations or exclusions may not apply to you. IBM shall not be liable for any damages you suffer as a result of using, modifying or distributing the sample program(s) or its/their derivatives. Each copy of any portion of this/these sample program(s) or any derivative work, must include the above copyright notice and disclaimer of warranty. ----------------------------------------------------------------------------- */ package swing2swt.layout; import java.awt.Dimension; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Layout; /** * Superclass for all the AWT layouts ported to SWT. * @author Yannick Saillet */ public abstract class AWTLayout extends Layout { /** * Key under which an eventual preferred size (set with setPreferredSize) * is stored as a user data in the SWT control. */ public final static String KEY_PREFERRED_SIZE = "preferredSize"; /** * Gets the preferred size of a component. * If a preferred size has been set with setPreferredSize, returns it, * otherwise returns the component computed preferred size. */ protected Point getPreferredSize( Control control, int wHint, int hHint, boolean changed) { // check if a preferred size was set on the control with // SWTComponent.setPreferredSize(Dimension) Dimension d = (Dimension)control.getData(KEY_PREFERRED_SIZE); if (d != null) return new Point(d.width, d.height); return control.computeSize(wHint, hHint, changed); } } bnd-1.50.0/biz.aQute.bnd/src/swing2swt/layout/GridLayout.java0000644000175000017500000001152211656076535023660 0ustar drazzibdrazzib/* ----------------------------------------------------------------------------- (c) Copyright IBM Corp. 2003 All rights reserved. The sample program(s) is/are owned by International Business Machines Corporation or one of its subsidiaries ("IBM") and is/are copyrighted and licensed, not sold. You may copy, modify, and distribute this/these sample program(s) in any form without payment to IBM, for any purpose including developing, using, marketing or distributing programs that include or are derivative works of the sample program(s). The sample program(s) is/are provided to you on an "AS IS" basis, without warranty of any kind. IBM HEREBY EXPRESSLY DISCLAIMS ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. Some jurisdictions do not allow for the exclusion or limitation of implied warranties, so the above limitations or exclusions may not apply to you. IBM shall not be liable for any damages you suffer as a result of using, modifying or distributing the sample program(s) or its/their derivatives. Each copy of any portion of this/these sample program(s) or any derivative work, must include the above copyright notice and disclaimer of warranty. ----------------------------------------------------------------------------- */ package swing2swt.layout; import org.eclipse.swt.SWT; import org.eclipse.swt.graphics.*; import org.eclipse.swt.widgets.*; /** * Port of AWT GridLayout to SWT. * @author Yannick Saillet */ public class GridLayout extends AWTLayout { private int rows, columns, hgap, vgap; public GridLayout() { this(1, 0); } public GridLayout(int rows, int columns) { this(rows, columns, 0, 0); } public GridLayout(int rows, int columns, int hgap, int vgap) { if (rows == 0 && columns == 0) throw new IllegalArgumentException("rows and cols cannot both be zero"); if (rows > 0 && columns > 0) columns = 0; this.rows = rows; this.columns = columns; this.hgap = hgap; this.vgap = vgap; } public int getColumns() { return columns; } public int getHgap() { return hgap; } public int getRows() { return rows; } public int getVgap() { return vgap; } public void setColumns(int cols) { if (rows == 0 && columns == 0) throw new IllegalArgumentException("rows and cols cannot both be zero"); this.columns = cols; } public void setHgap(int hgap) { this.hgap = hgap; } public void setRows(int rows) { if (rows == 0 && columns == 0) throw new IllegalArgumentException("rows and cols cannot both be zero"); this.rows = rows; } public void setVgap(int vgap) { this.vgap = vgap; } //---------- protected Point computeSize( Composite composite, int wHint, int hHint, boolean flushCache) { Control[] children = composite.getChildren(); int nbOfVisibleChildren = 0; for (int i = 0; i < children.length; i++) { //if (children[i].isVisible()) nbOfVisibleChildren++; } if (nbOfVisibleChildren == 0) return new Point(0, 0); int r = rows; int c = columns; if (r == 0) r = nbOfVisibleChildren / c + ((nbOfVisibleChildren % c) == 0 ? 0 : 1); else if (c == 0) c = nbOfVisibleChildren / r + ((nbOfVisibleChildren % r) == 0 ? 0 : 1); int width = 0; int height = 0; for (int i = 0; i < children.length; i++) { //if (!children[i].isVisible()) //continue; Point size = getPreferredSize(children[i], SWT.DEFAULT, SWT.DEFAULT, flushCache); if (size.x > width) width = size.x; if (size.y > height) height = size.y; } return new Point(c * width + (c - 1) * hgap, r * height + (r - 1) * vgap); } protected void layout(Composite composite, boolean flushCache) { Rectangle clientArea = composite.getClientArea(); Control[] children = composite.getChildren(); int nbOfVisibleChildren = 0; for (int i = 0; i < children.length; i++) { //if (children[i].isVisible()) nbOfVisibleChildren++; } if (nbOfVisibleChildren == 0) return ; int r = rows; int c = columns; if (r == 0) r = nbOfVisibleChildren / c + ((nbOfVisibleChildren % c) == 0 ? 0 : 1); else if (c == 0) c = nbOfVisibleChildren / r + ((nbOfVisibleChildren % r) == 0 ? 0 : 1); int width = (clientArea.width - (c - 1) * hgap) / c; int height = (clientArea.height - (r - 1) * vgap) / r; int x = clientArea.x; int y = clientArea.y; for (int i = 0; i < children.length; i++) { //if (!children[i].isVisible()) //continue; children[i].setBounds(x, y, width, height); if (((i + 1) % c) == 0) // if new line { x = clientArea.x; y += height + vgap; } else x += width + hgap; } } } bnd-1.50.0/biz.aQute.bnd/src/test/0000755000175000017500000000000011656076535016424 5ustar drazzibdrazzibbnd-1.50.0/biz.aQute.bnd/src/test/TestBuild.java0000644000175000017500000000032511656076535021166 0ustar drazzibdrazzibpackage test; import aQute.bnd.main.*; import junit.framework.*; public class TestBuild extends TestCase { public void testX() {} // public void testBndBuild() { // bnd.main(new String[] {"build"}); // } } bnd-1.50.0/biz.aQute.bnd/src/aQute/0000755000175000017500000000000011656076535016524 5ustar drazzibdrazzibbnd-1.50.0/biz.aQute.bnd/src/aQute/bnd/0000755000175000017500000000000011656076535017267 5ustar drazzibdrazzibbnd-1.50.0/biz.aQute.bnd/src/aQute/bnd/junit/0000755000175000017500000000000011656076535020420 5ustar drazzibdrazzibbnd-1.50.0/biz.aQute.bnd/src/aQute/bnd/junit/OSGiJUnitLaunchShortcut.java0000644000175000017500000000050311656076535025723 0ustar drazzibdrazzibpackage aQute.bnd.junit; public class OSGiJUnitLaunchShortcut extends org.eclipse.jdt.junit.launcher.JUnitLaunchShortcut { public OSGiJUnitLaunchShortcut() { //System.out.println("Constructore Launch Shortcut"); } protected String getLaunchConfigurationTypeId() { return "aQute.bnd.junit.launchconfig"; } } bnd-1.50.0/biz.aQute.bnd/src/aQute/bnd/junit/OSGiJUnitTabGroup.java0000644000175000017500000000141211656076535024500 0ustar drazzibdrazzibpackage aQute.bnd.junit; import org.eclipse.debug.ui.*; import org.eclipse.debug.ui.sourcelookup.*; import org.eclipse.jdt.debug.ui.launchConfigurations.*; import org.eclipse.jdt.junit.launcher.*; public class OSGiJUnitTabGroup extends org.eclipse.jdt.internal.junit.launcher.JUnitTabGroup { public void createTabs(ILaunchConfigurationDialog dialog, String mode) { ILaunchConfigurationTab[] tabs= new ILaunchConfigurationTab[] { new JUnitLaunchConfigurationTab(), new OSGiArgumentsTab(), new JavaArgumentsTab(), new JavaClasspathTab(), new JavaJRETab(), new SourceLookupTab(), new EnvironmentTab(), new CommonTab() }; setTabs(tabs); } } bnd-1.50.0/biz.aQute.bnd/src/aQute/bnd/junit/OSGiJUnitLauncherConfigurationDelegate.java0000644000175000017500000001054511656076535030710 0ustar drazzibdrazzibpackage aQute.bnd.junit; import java.io.*; import java.util.*; import org.eclipse.core.runtime.*; import org.eclipse.debug.core.*; import org.eclipse.jdt.core.*; import org.eclipse.jdt.junit.launcher.*; import aQute.bnd.build.*; import aQute.bnd.plugin.*; import aQute.bnd.service.*; import aQute.lib.osgi.*; @SuppressWarnings("unchecked") public class OSGiJUnitLauncherConfigurationDelegate extends JUnitLaunchConfigurationDelegate { private ProjectTester tester; private ProjectTester getTester(ILaunchConfiguration configuration) throws CoreException { try { if (tester == null) { IJavaProject javaProject = getJavaProject(configuration); Project project = Activator.getDefault().getCentral().getModel(javaProject); project.clear(); tester = project.getProjectTester(); if (tester == null) { throw new IllegalArgumentException("Launching " + project + ". Cannot determine launcher configuration from -runpath: " + project.getProperty(Constants.RUNPATH)); } } return tester; } catch (Exception e) { throw new CoreException(new Status(IStatus.ERROR, Activator.PLUGIN_ID, "Failed to obtain launcher", e)); } } public String verifyMainTypeName(ILaunchConfiguration configuration) throws CoreException { return getTester(configuration).getProjectLauncher().getMainTypeName(); } // protected IMember[] evaluateTests(ILaunchConfiguration configuration, // IProgressMonitor monitor) throws CoreException { // System.out.println("Evaluate Tests"); // return super.evaluateTests(configuration, monitor); // } protected void collectExecutionArguments(ILaunchConfiguration configuration, List/* String */vmArguments, List/* String */programArguments) throws CoreException { try { super.collectExecutionArguments(configuration, vmArguments, programArguments); ProjectTester tester = getTester(configuration); ProjectLauncher launcher = tester.getProjectLauncher(); int port = -1; // Pretty ugly :-( for (int i = 0; i < programArguments.size(); i++) { if (programArguments.get(i).equals("-port")) { port = Integer.parseInt((String) programArguments.get(++i)); } else if (programArguments.get(i).equals("-testNameFile")) { File testNameFile = tester.getProject().getFile( (String) programArguments.get(++i)); processFile(tester, testNameFile); } else if (programArguments.get(i).equals("-test")) { tester.addTest((String)programArguments.get(++i)); }else if (programArguments.get(i).equals("-classNames")) { tester.addTest((String)programArguments.get(++i)); } } if (tester instanceof EclipseJUnitTester) { EclipseJUnitTester etester = (EclipseJUnitTester) tester; etester.setPort(port); } programArguments.addAll(launcher.getArguments()); vmArguments.addAll(launcher.getRunVM()); if (configuration.getAttribute(OSGiArgumentsTab.ATTR_KEEP, false)) programArguments.add("-keep"); if (tester.getProject().isOk()) { tester.prepare(); return; } String args = vmArguments + " " + programArguments + " " + Arrays.toString(getClasspath(configuration)); Activator.getDefault().report(true, false, tester.getProject(), "Launching " + tester.getProject(), args); } catch (Exception e) { throw new CoreException(new Status(IStatus.ERROR, Activator.PLUGIN_ID, "Building arguments for remote VM", e)); } throw new CoreException(new Status(IStatus.ERROR, Activator.PLUGIN_ID, "Building arguments for remote VM")); } private void processFile(ProjectTester tester, File file) throws IOException { FileReader rdr = new FileReader(file); BufferedReader brdr = new BufferedReader(rdr); String line = brdr.readLine(); while (line != null) { tester.addTest(line.trim()); line = brdr.readLine(); } rdr.close(); } /** * Calculate the classpath. We include our own runtime.jar which includes * the test framework and we include the first of the test frameworks * specified. */ public String[] getClasspath(ILaunchConfiguration configuration) throws CoreException { return getTester(configuration).getProjectLauncher().getClasspath().toArray(new String[0]); } public void launch(ILaunchConfiguration configuration, String mode, ILaunch launch, IProgressMonitor monitor) throws CoreException { try { super.launch(configuration, mode, launch, monitor); } finally { tester = null; } } } bnd-1.50.0/biz.aQute.bnd/src/aQute/bnd/junit/OSGiArgumentsTab.java0000644000175000017500000001071711656076535024407 0ustar drazzibdrazzibpackage aQute.bnd.junit; import org.eclipse.core.resources.*; import org.eclipse.core.runtime.*; import org.eclipse.debug.core.*; import org.eclipse.debug.ui.*; import org.eclipse.jdt.core.*; import org.eclipse.jdt.launching.*; import org.eclipse.swt.*; import org.eclipse.swt.layout.*; import org.eclipse.swt.widgets.*; import aQute.bnd.plugin.*; public class OSGiArgumentsTab extends AbstractLaunchConfigurationTab { public static final String ATTR_KEEP = Activator.PLUGIN_ID + ".CLEARCACHE"; //$NON-NLS-1$ public static final String ATTR_REPORT = Activator.PLUGIN_ID + ".REPORT"; //$NON-NLS-1$ Button wReport; private Button wKeep; public void createControl(Composite parent) { Composite comp = new Composite(parent, SWT.NONE); comp.setLayout(new FormLayout()); setControl(comp); wKeep = new Button(comp, SWT.CHECK); final FormData fd_wClearCache = new FormData(); fd_wClearCache.bottom = new FormAttachment(wKeep, 25, SWT.BOTTOM); fd_wClearCache.top = new FormAttachment(wKeep, 5, SWT.BOTTOM); fd_wClearCache.right = new FormAttachment(wKeep, 189, SWT.LEFT); fd_wClearCache.left = new FormAttachment(wKeep, 0, SWT.LEFT); wKeep.setLayoutData(fd_wClearCache); wKeep.setText("Keep"); wReport = new Button(comp, SWT.CHECK); final FormData fd_verboseButton = new FormData(); fd_verboseButton.top = new FormAttachment(wReport, 5, SWT.BOTTOM); fd_verboseButton.left = new FormAttachment(wReport, 0, SWT.LEFT); wReport.setLayoutData(fd_verboseButton); wReport.setText("Report"); validatePage(); } private void validatePage() { setErrorMessage(null); setMessage(null); } public String getName() { return "OSGi"; } public void initializeFrom(ILaunchConfiguration configuration) { try { boolean keep = configuration.getAttribute(ATTR_KEEP, false); wKeep.setSelection(keep); boolean report = configuration.getAttribute(ATTR_REPORT, false); wReport.setSelection(report); } catch (Exception ce) { ce.printStackTrace(); } } public void performApply(ILaunchConfigurationWorkingCopy configuration) { configuration.setAttribute(ATTR_REPORT, wReport.getSelection()); configuration .setAttribute(ATTR_KEEP, wKeep.getSelection()); } public void setDefaults(ILaunchConfigurationWorkingCopy configuration) { // TODO Auto-generated method stub } /** * Returns the Java project specified by the given launch configuration, or * null if none. * * @param configuration * launch configuration * @return the Java project specified by the given launch configuration, or * null if none * @exception CoreException * if unable to retrieve the attribute */ public IJavaProject getJavaProject(ILaunchConfiguration configuration) throws CoreException { String projectName = getJavaProjectName(configuration); if (projectName != null) { projectName = projectName.trim(); if (projectName.length() > 0) { IProject project = ResourcesPlugin.getWorkspace().getRoot() .getProject(projectName); IJavaProject javaProject = JavaCore.create(project); if (javaProject != null && javaProject.exists()) { return javaProject; } } } return null; } /** * Returns the Java project name specified by the given launch * configuration, or null if none. * * @param configuration * launch configuration * @return the Java project name specified by the given launch * configuration, or null if none * @exception CoreException * if unable to retrieve the attribute */ public String getJavaProjectName(ILaunchConfiguration configuration) throws CoreException { return configuration.getAttribute( IJavaLaunchConfigurationConstants.ATTR_PROJECT_NAME, (String) null); } } bnd-1.50.0/biz.aQute.bnd/src/aQute/bnd/libsync/0000755000175000017500000000000011656076535020732 5ustar drazzibdrazzibbnd-1.50.0/biz.aQute.bnd/src/aQute/bnd/libsync/LibSync.java0000644000175000017500000000506311656076535023144 0ustar drazzibdrazzibpackage aQute.bnd.libsync; import java.io.*; import java.net.*; import java.util.*; import aQute.lib.osgi.*; public class LibSync extends Processor { URL url; public LibSync() { } public LibSync(Processor parent) { super(parent); } public void submit(Jar jar) throws Exception { String host = getProperty("libsync.repo", "http://libsync.com/repo"); try { URL url = new URL(host); Verifier v = new Verifier(jar); v.setPedantic(true); v.verify(); getInfo(v); if (isOk() && v.getWarnings().isEmpty()) { send0(jar, url); } } catch (MalformedURLException e) { error("The libsync.repo property does not contain a proper URL %s, exception: %s", host, e); } catch (Exception e) { error("Submission of %s to %s failed even after retrying", host, jar.getName()); } } Jar send0(Jar jar, URL url) throws Exception { int retries = Integer.parseInt(getProperty("libsync.retries", "3")); for (int i = 0; i < retries - 1; i++) { try { return send1(jar, url); } catch (Exception e) { warning("Submission failed %s, will retry (%d times defined in libsync.retries)", e, retries); Thread.sleep(i * 1000); } } return send1(jar, url); } Jar send1(Jar jar, URL url) throws Exception { HttpURLConnection urlc = (HttpURLConnection) url.openConnection(); urlc.setDoOutput(true); urlc.setDoInput(true); trace("Connecting to: %s", url); urlc.setRequestMethod("POST"); urlc.setRequestProperty("Content-Type", "application/binary"); urlc.connect(); OutputStream out = urlc.getOutputStream(); try { jar.write(out); } finally { out.close(); } trace("Submitted: %s to %s", jar.getName(), url); InputStream in = urlc.getInputStream(); try { Jar result = new Jar(url.toExternalForm(), in); addClose(result); trace("Received: %s", result.getName()); Resource errors = result.getResource("META-INF/errors"); Resource warnings = result.getResource("META-INF/warnings"); if (errors != null) parse(errors.openInputStream(), url.getFile(), getErrors()); if (warnings != null) parse(warnings.openInputStream(), url.getFile(), getWarnings()); return result; } finally { in.close(); } } private void parse(InputStream in, String prefix, List to) throws Exception { try { InputStreamReader r = new InputStreamReader(in, Constants.DEFAULT_CHARSET); BufferedReader br = new BufferedReader(r); String line = br.readLine(); while (line != null) { to.add(prefix + line); line = br.readLine(); } } finally { in.close(); } } } bnd-1.50.0/biz.aQute.bnd/src/aQute/bnd/main/0000755000175000017500000000000011656076535020213 5ustar drazzibdrazzibbnd-1.50.0/biz.aQute.bnd/src/aQute/bnd/main/bnd.java0000755000175000017500000017202011656076535021626 0ustar drazzibdrazzibpackage aQute.bnd.main; import java.io.*; import java.net.*; import java.util.*; import java.util.jar.*; import java.util.prefs.*; import java.util.regex.*; import java.util.zip.*; import javax.xml.parsers.*; import javax.xml.transform.*; import javax.xml.transform.dom.*; import javax.xml.transform.stream.*; import javax.xml.xpath.*; import org.w3c.dom.*; import aQute.bnd.build.*; import aQute.bnd.concurrent.*; import aQute.bnd.libsync.*; import aQute.bnd.maven.*; import aQute.bnd.service.*; import aQute.bnd.service.action.*; import aQute.bnd.settings.*; import aQute.lib.deployer.*; import aQute.lib.io.*; import aQute.lib.jardiff.*; import aQute.lib.osgi.*; import aQute.lib.osgi.eclipse.*; import aQute.lib.tag.*; import aQute.libg.generics.*; import aQute.libg.version.*; /** * Utility to make bundles. * * TODO Add Javadoc comment for this type. * * @version $Revision: 1.14 $ */ public class bnd extends Processor { Settings settings = new Settings(); PrintStream out = System.out; static boolean exceptions = false; static boolean failok = false; private Project project; public static void main(String args[]) { bnd main = new bnd(); try { main.run(args); if (bnd.failok) return; System.exit(main.getErrors().size()); } catch (Exception e) { System.err.println("Software error occurred " + e); if (exceptions) e.printStackTrace(); } System.exit(-1); } void run(String[] args) throws Exception { int i = 0; try { for (; i < args.length; i++) { if ("-failok".equals(args[i])) { failok = true; } else if ("-exceptions".equals(args[i])) { exceptions = true; } else if ("-trace".equals(args[i])) { setTrace(true); } else if ("-pedantic".equals(args[i])) { setPedantic(true); } else if (args[i].indexOf('=') > 0) { String parts[] = args[i].split("\\s*(?!\\\\)=\\s*"); if (parts.length == 2) setProperty(parts[0], parts[1]); else error("invalid property def: %s", args[i]); } else if ("-base".equals(args[i])) { setBase(new File(args[++i]).getAbsoluteFile()); if (!getBase().isDirectory()) { out.println("-base must be a valid directory"); } else if (args[i].startsWith("-")) error("Invalid option: ", args[i]); } else break; } project = getProject(); if (project != null) { setParent(project); project.setPedantic(isPedantic()); project.setTrace(isTrace()); } trace("project = %s", project); if (i >= args.length) { if (project != null && project.isValid()) { trace("default build of current project"); project.build(); } else doHelp(); } else { if (!doProject(project, args, i)) { if (!doCommand(args, i)) { doFiles(args, i); } } } } catch (Throwable t) { if (exceptions) t.printStackTrace(); error("exception %s", t, t); } int n = 1; switch (getErrors().size()) { case 0: // System.err.println("No errors"); break; case 1: System.err.println("One error"); break; default: System.err.println(getErrors().size() + " errors"); } for (String msg : getErrors()) { System.err.println(n++ + " : " + msg); } n = 1; switch (getWarnings().size()) { case 0: // System.err.println("No warnings"); break; case 1: System.err.println("One warning"); break; default: System.err.println(getWarnings().size() + " warnings"); } for (String msg : getWarnings()) { System.err.println(n++ + " : " + msg); } if (getErrors().size() != 0) { System.err.flush(); System.out.flush(); Thread.sleep(1000); System.exit(getErrors().size()); } } boolean doProject(Project project, String[] args, int i) throws Exception { if (project != null) { trace("project command %s", args[i]); Action a = project.getActions().get(args[i]); if (a != null) { a.execute(project, args[i++]); getInfo(project); return true; } } return false; } boolean doCommand(String args[], int i) throws Exception { String cmd = args[i]; trace("command %s", cmd); if ("wrap".equals(args[i])) { doWrap(args, ++i); } else if ("maven".equals(args[i])) { MavenCommand maven = new MavenCommand(this); maven.setTrace(isTrace()); maven.setPedantic(isPedantic()); maven.run(args, ++i); getInfo(maven); } else if ("global".equals(args[i])) { global(args, ++i); } else if ("exec".equals(args[i])) { doRun(args[++i]); } else if ("print".equals(args[i])) { doPrint(args, ++i); } else if ("lib".equals(args[i])) { doLib(args, ++i); } else if ("graph".equals(args[i])) { doDot(args, ++i); } else if ("create-repo".equals(args[i])) { createRepo(args, ++i); } else if ("release".equals(args[i])) { doRelease(args, ++i); } else if ("debug".equals(args[i])) { debug(args, ++i); } else if ("bump".equals(args[i])) { bump(args, ++i); } else if ("deliverables".equals(args[i])) { deliverables(args, ++i); } else if ("view".equals(args[i])) { doView(args, ++i); } else if ("buildx".equals(args[i])) { doBuild(args, ++i); } else if ("extract".equals(args[i])) { doExtract(args, ++i); } else if ("patch".equals(args[i])) { patch(args, ++i); } else if ("runtests".equals(args[i])) { runtests(args, ++i); } else if ("xref".equals(args[i])) { doXref(args, ++i); } else if ("eclipse".equals(args[i])) { doEclipse(args, ++i); } else if ("repo".equals(args[i])) { repo(args, ++i); } else if ("diff".equals(args[i])) { doDiff(args, ++i); } else if ("help".equals(args[i])) { doHelp(args, ++i); } else if ("macro".equals(args[i])) { doMacro(args, ++i); } else if ("multibuild".equals(args[i])) { doMulti(args, ++i); } else if ("merge".equals(args[i])) { doMerge(args, ++i); } else { trace("command %s not found", cmd); return false; } trace("command %s executed", cmd); return true; } private void doMulti(String[] args, int i) throws Exception { // Project p = getProject(); // Workspace workspace; // // if (p != null) // workspace = p.getWorkspace(); // else // workspace = Workspace.getWorkspace(getBase()); // // trace("Starting multibuild"); // MultiBuilder multiBuilder = new MultiBuilder(workspace); // multiBuilder.startBuild(); // // trace("Syncing multibuild"); // multiBuilder.syncBuild(); // trace("Synced"); // if ( p != null) { // trace("Build %s", (Object) p.build()); // } } boolean doFiles(String args[], int i) throws Exception { while (i < args.length) { String path = args[i]; if (path.endsWith(Constants.DEFAULT_BND_EXTENSION)) doBuild(getFile(path), new File[0], new File[0], null, "", new File(path).getParentFile(), 0, new HashSet()); else if (path.endsWith(Constants.DEFAULT_JAR_EXTENSION) || path.endsWith(Constants.DEFAULT_BAR_EXTENSION)) doPrint(path, -1); else if (path.endsWith(Constants.DEFAULT_BNDRUN_EXTENSION)) doRun(path); else error("Unknown file %s", path); i++; } return true; } private void doRun(String path) throws Exception { File file = getFile(path); if (!file.isFile()) throw new FileNotFoundException(path); File projectDir = file.getParentFile(); File workspaceDir = projectDir.getParentFile(); if (workspaceDir == null) { workspaceDir = new File(System.getProperty("user.home") + File.separator + ".bnd"); } Workspace ws = Workspace.getWorkspace(workspaceDir); File bndbnd = new File(projectDir, Project.BNDFILE); Project project; if (bndbnd.isFile()) { project = new Project(ws, projectDir, bndbnd); project.doIncludeFile(file, true, project.getProperties()); } else project = new Project(ws, projectDir, file); project.setTrace(isTrace()); project.setPedantic(isPedantic()); try { project.run(); } catch (Exception e) { error("Failed to run %s: %s", project, e); } getInfo(project); } private void bump(String[] args, int i) throws Exception { if (getProject() == null) { error("No project found, use -base

bump"); return; } String mask = null; if (args.length > i) { mask = args[i]; if (mask.equalsIgnoreCase("major")) mask = "+00"; else if (mask.equalsIgnoreCase("minor")) mask = "=+0"; else if (mask.equalsIgnoreCase("micro")) mask = "==+"; else if (!mask.matches("(+=0){1,3}")) { error("Invalid mask for version bump %s, is (minor|major|micro|), see $version for mask", mask); return; } } if (mask == null) getProject().bump(); else getProject().bump(mask); out.println(getProject().getProperty(BUNDLE_VERSION, "No version found")); } /** * Take the current project, calculate its dependencies from the repo and * create a mini-repo from it that can easily be unzipped. * * @param args * @param i * @throws Exception */ private void createRepo(String[] args, int i) throws Exception { Project project = getProject(); if (project == null) { error("not in a proper bnd project ... " + getBase()); return; } File out = getFile(project.getName() + ".repo.jar"); List skip = Create.list(); while (i < args.length) { if (args[i].equals("-o")) { i++; if (i < args.length) out = getFile(args[i]); else error("No arg for -out"); } else if (args[i].equals("-skip")) { i++; if (i < args.length) { Instruction instr = Instruction.getPattern(args[i]); skip.add(instr); } else error("No arg for -skip"); } else error("invalid arg for create-repo %s", args[i]); i++; } Jar output = new Jar(project.getName()); output.setDoNotTouchManifest(); addClose(output); getInfo(project); if (isOk()) { for (Container c : project.getBuildpath()) { addContainer(skip, output, c); } for (Container c : project.getRunbundles()) { addContainer(skip, output, c); } if (isOk()) { try { output.write(out); } catch (Exception e) { error("Could not write mini repo %s", e); } } } } private void addContainer(Collection skip, Jar output, Container c) throws Exception { trace("add container " + c); String prefix = "cnf/repo/"; switch (c.getType()) { case ERROR: error("Dependencies include %s", c.getError()); return; case REPO: case EXTERNAL: { String name = getName(skip, prefix, c, ".jar"); if (name != null) output.putResource(name, new FileResource(c.getFile())); trace("storing %s in %s", c, name); break; } case PROJECT: trace("not storing project " + c); break; case LIBRARY: { String name = getName(skip, prefix, c, ".lib"); if (name != null) { output.putResource(name, new FileResource(c.getFile())); trace("store library %s", name); for (Container child : c.getMembers()) { trace("store member %s", child); addContainer(skip, output, child); } } } } } String getName(Collection skip, String prefix, Container c, String extension) throws Exception { Manifest m = c.getManifest(); try { if (m == null) { error("No manifest found for %s", c); return null; } String bsn = m.getMainAttributes().getValue(BUNDLE_SYMBOLICNAME); if (bsn == null) { error("No bsn in manifest: %s", c); return null; } for (Instruction instr : skip) { if (instr.matches(bsn)) { if (instr.isNegated()) // - * - = +! break; else return null; // skip it } } int n = bsn.indexOf(';'); if (n > 0) { bsn = bsn.substring(0, n).trim(); } String version = m.getMainAttributes().getValue(BUNDLE_VERSION); if (version == null) version = "0"; Version v = new Version(version); version = v.getMajor() + "." + v.getMinor() + "." + v.getMicro(); if (c.getFile() != null && c.getFile().getName().endsWith("-latest.jar")) version = "latest"; return prefix + bsn + "/" + bsn + "-" + version + extension; } catch (Exception e) { error("Could not store repo file %s", c); } return null; } private void deliverables(String[] args, int i) throws Exception { Project project = getProject(); long start = System.currentTimeMillis(); Collection projects = project.getWorkspace().getAllProjects(); List containers = new ArrayList(); for (Project p : projects) { containers.addAll(p.getDeliverables()); } long duration = System.currentTimeMillis() - start; System.out.println("Took " + duration + " ms"); for (Container c : containers) { Version v = new Version(c.getVersion()); System.out.printf("%-40s %d.%d.%d %s\n", c.getBundleSymbolicName(), v.getMajor(), v.getMinor(), v.getMicro(), c.getFile()); } } private int doMacro(String[] args, int i) throws Exception { String result; for (; i < args.length; i++) { String cmd = args[i]; cmd = cmd.replaceAll("@\\{([^}])\\}", "\\${$1}"); cmd = cmd.replaceAll(":", ";"); cmd = cmd.replaceAll("[^$](.*)", "\\${$0}"); result = getReplacer().process(cmd); if (result != null && result.length() != 0) { Collection parts = split(result); for (String s : parts) { out.println(s); } } else out.println("No result for " + cmd); } return i; } private void doRelease(String[] args, int i) throws Exception { Project project = getProject(); project.release(false); getInfo(project); } /** * Cross reference every class in the jar file to the files it references * * @param args * @param i */ private void doXref(String[] args, int i) { for (; i < args.length; i++) { try { File file = new File(args[i]); Jar jar = new Jar(file.getName(), file); try { for (Map.Entry entry : jar.getResources().entrySet()) { String key = entry.getKey(); Resource r = entry.getValue(); if (key.endsWith(".class")) { InputStream in = r.openInputStream(); Clazz clazz = new Clazz(key, r); out.print(key); Set xref = clazz.parseClassFile(); in.close(); for (String element : xref) { out.print("\t"); out.print(element); } out.println(); } } } finally { jar.close(); } } catch (Exception e) { e.printStackTrace(); } } } private void doEclipse(String[] args, int i) throws Exception { File dir = new File("").getAbsoluteFile(); if (args.length == i) doEclipse(dir); else { for (; i < args.length; i++) { doEclipse(new File(dir, args[i])); } } } private void doEclipse(File file) throws Exception { if (!file.isDirectory()) error("Eclipse requires a path to a directory: " + file.getAbsolutePath()); else { File cp = new File(file, ".classpath"); if (!cp.exists()) { error("Cannot find .classpath in project directory: " + file.getAbsolutePath()); } else { EclipseClasspath eclipse = new EclipseClasspath(this, file.getParentFile(), file); out.println("Classpath " + eclipse.getClasspath()); out.println("Dependents " + eclipse.getDependents()); out.println("Sourcepath " + eclipse.getSourcepath()); out.println("Output " + eclipse.getOutput()); out.println(); } } } final static int BUILD_SOURCES = 1; final static int BUILD_POM = 2; final static int BUILD_FORCE = 4; private void doBuild(String[] args, int i) throws Exception { File classpath[] = new File[0]; File workspace = null; File sourcepath[] = new File[0]; File output = null; String eclipse = ""; int options = 0; for (; i < args.length; i++) { if ("-workspace".startsWith(args[i])) { workspace = new File(args[++i]); } else if ("-classpath".startsWith(args[i])) { classpath = getClasspath(args[++i]); } else if ("-sourcepath".startsWith(args[i])) { String arg = args[++i]; String spaces[] = arg.split("\\s*,\\s*"); sourcepath = new File[spaces.length]; for (int j = 0; j < spaces.length; j++) { File f = new File(spaces[j]); if (!f.exists()) error("No such sourcepath entry: " + f.getAbsolutePath()); sourcepath[j] = f; } } else if ("-eclipse".startsWith(args[i])) { eclipse = args[++i]; } else if ("-noeclipse".startsWith(args[i])) { eclipse = null; } else if ("-output".startsWith(args[i])) { output = new File(args[++i]); } else if ("-sources".startsWith(args[i])) { options |= BUILD_SOURCES; } else if ("-pom".startsWith(args[i])) { options |= BUILD_POM; } else if ("-force".startsWith(args[i])) { options |= BUILD_FORCE; } else { if (args[i].startsWith("-")) error("Invalid option for bnd: " + args[i]); else { File properties = new File(args[i]); if (!properties.exists()) error("Cannot find bnd file: " + args[i]); else { if (workspace == null) workspace = properties.getParentFile(); doBuild(properties, classpath, sourcepath, output, eclipse, workspace, options, new HashSet()); } output = null; } } } } private File[] getClasspath(String string) { String spaces[] = string.split("\\s*,\\s*"); File classpath[] = new File[spaces.length]; for (int j = 0; j < spaces.length; j++) { File f = new File(spaces[j]); if (!f.exists()) error("No such classpath entry: " + f.getAbsolutePath()); classpath[j] = f; } return classpath; } private void doBuild(File properties, File classpath[], File sourcepath[], File output, String eclipse, File workspace, int options, Set building) throws Exception { properties = properties.getAbsoluteFile(); if (building.contains(properties)) { error("Circular dependency in pre build " + properties); return; } building.add(properties); Builder builder = new Builder(); try { builder.setPedantic(isPedantic()); builder.setProperties(properties); if (output == null) { String out = builder.getProperty("-output"); if (out != null) { output = getFile(properties.getParentFile(), out); if (!output.getName().endsWith(".jar")) output.mkdirs(); } else output = properties.getAbsoluteFile().getParentFile(); } String prebuild = builder.getProperty("-prebuild"); if (prebuild != null) prebuild(prebuild, properties.getParentFile(), classpath, sourcepath, output, eclipse, workspace, options, building); doEclipse(builder, properties, classpath, sourcepath, eclipse, workspace); if ((options & BUILD_SOURCES) != 0) builder.getProperties().setProperty("-sources", "true"); if (failok) builder.setProperty(Analyzer.FAIL_OK, "true"); Jar jar = builder.build(); getInfo(builder); if (getErrors().size() > 0 && !failok) return; String name = builder.getBsn() + DEFAULT_JAR_EXTENSION; if (output.isDirectory()) output = new File(output, name); output.getParentFile().mkdirs(); if ((options & BUILD_POM) != 0) { Resource r = new PomFromManifest(jar.getManifest()); jar.putResource("pom.xml", r); String path = output.getName().replaceAll("\\.jar$", ".pom"); if (path.equals(output.getName())) path = output.getName() + ".pom"; File pom = new File(output.getParentFile(), path); OutputStream out = new FileOutputStream(pom); try { r.write(out); } finally { out.close(); } } jar.setName(output.getName()); String msg = ""; if (!output.exists() || output.lastModified() <= jar.lastModified() || (options & BUILD_FORCE) != 0) { jar.write(output); } else { msg = "(not modified)"; } statistics(jar, output, msg); } finally { builder.close(); } } private void prebuild(String prebuild, File base, File[] classpath, File[] sourcepath, File output, String eclipse2, File workspace, int options, Set building) throws Exception { // Force the output a directory if (output.isFile()) output = output.getParentFile(); Collection parts = Processor.split(prebuild); for (String part : parts) { File f = new File(part); if (!f.exists()) f = new File(base, part); if (!f.exists()) { error("Trying to build a non-existent file: " + parts); continue; } try { doBuild(f, classpath, sourcepath, output, eclipse2, workspace, options, building); } catch (Exception e) { error("Trying to build: " + part + " " + e); } } } private void statistics(Jar jar, File output, String msg) { out.println(jar.getName() + " " + jar.getResources().size() + " " + output.length() + msg); } /** * @param properties * @param classpath * @param eclipse * @return * @throws IOException */ void doEclipse(Builder builder, File properties, File[] classpath, File sourcepath[], String eclipse, File workspace) throws IOException { if (eclipse != null) { File project = new File(workspace, eclipse).getAbsoluteFile(); if (project.exists() && project.isDirectory()) { try { EclipseClasspath path = new EclipseClasspath(this, project.getParentFile(), project); List newClasspath = Create.copy(Arrays.asList(classpath)); newClasspath.addAll(path.getClasspath()); classpath = (File[]) newClasspath.toArray(classpath); List newSourcepath = Create.copy(Arrays.asList(sourcepath)); newSourcepath.addAll(path.getSourcepath()); sourcepath = (File[]) newSourcepath.toArray(sourcepath); } catch (Exception e) { if (eclipse.length() > 0) error("Eclipse specified (" + eclipse + ") but getting error processing: " + e); } } else { if (eclipse.length() > 0) error("Eclipse specified (" + eclipse + ") but no project directory found"); } } builder.setClasspath(classpath); builder.setSourcepath(sourcepath); } private void doHelp() { doHelp(new String[0], 0); } private void doHelp(String[] args, int i) { if (args.length <= i) { out.println("bnd -failok? -exceptions? ( wrap | print | build | eclipse | xref | view )?"); out.println("See http://www.aQute.biz/Code/Bnd"); } else { while (args.length > i) { if ("wrap".equals(args[i])) { out.println("bnd wrap (-output )? (-properties )? "); } else if ("print".equals(args[i])) { out.println("bnd wrap -verify? -manifest? -list? -eclipse "); } else if ("build".equals(args[i])) { out.println("bnd build (-output )? (-classpath )? (-sourcepath )? "); out.println(" -eclipse? -noeclipse? -sources? "); } else if ("eclipse".equals(args[i])) { out.println("bnd eclipse"); } else if ("view".equals(args[i])) { out.println("bnd view +"); } i++; } } } final static int VERIFY = 1; final static int MANIFEST = 2; final static int LIST = 4; final static int ECLIPSE = 8; final static int IMPEXP = 16; final static int USES = 32; final static int USEDBY = 64; final static int COMPONENT = 128; final static int METATYPE = 256; static final int HEX = 0; private void doPrint(String[] args, int i) throws Exception { int options = 0; for (; i < args.length; i++) { if ("-verify".startsWith(args[i])) options |= VERIFY; else if ("-manifest".startsWith(args[i])) options |= MANIFEST; else if ("-list".startsWith(args[i])) options |= LIST; else if ("-eclipse".startsWith(args[i])) options |= ECLIPSE; else if ("-impexp".startsWith(args[i])) options |= IMPEXP; else if ("-uses".startsWith(args[i])) options |= USES; else if ("-usedby".startsWith(args[i])) options |= USEDBY; else if ("-component".startsWith(args[i])) options |= COMPONENT; else if ("-metatype".startsWith(args[i])) options |= METATYPE; else if ("-all".startsWith(args[i])) options = -1; else { if (args[i].startsWith("-")) error("Invalid option for print: " + args[i]); else doPrint(args[i], options); } } } public void doPrint(String string, int options) throws Exception { File file = new File(string); if (!file.exists()) error("File to print not found: " + string); else { if (options == 0) options = VERIFY | MANIFEST | IMPEXP | USES; doPrint(file, options); } } private void doPrint(File file, int options) throws ZipException, IOException, Exception { Jar jar = new Jar(file.getName(), file); try { if ((options & VERIFY) != 0) { Verifier verifier = new Verifier(jar); verifier.setPedantic(isPedantic()); verifier.verify(); getInfo(verifier); } if ((options & MANIFEST) != 0) { Manifest manifest = jar.getManifest(); if (manifest == null) warning("JAR has no manifest " + file); else { out.println("[MANIFEST " + jar.getName() + "]"); SortedSet sorted = new TreeSet(); for (Object element : manifest.getMainAttributes().keySet()) { sorted.add(element.toString()); } for (String key : sorted) { Object value = manifest.getMainAttributes().getValue(key); format("%-40s %-40s\r\n", new Object[] { key, value }); } } out.println(); } if ((options & IMPEXP) != 0) { out.println("[IMPEXP]"); Manifest m = jar.getManifest(); if (m != null) { Map> imports = parseHeader(m.getMainAttributes() .getValue(Analyzer.IMPORT_PACKAGE)); Map> exports = parseHeader(m.getMainAttributes() .getValue(Analyzer.EXPORT_PACKAGE)); for (String p : exports.keySet()) { if (imports.containsKey(p)) { Map attrs = imports.get(p); if (attrs.containsKey(Constants.VERSION_ATTRIBUTE)) { exports.get(p).put("imported-as", attrs.get(VERSION_ATTRIBUTE)); } } } print("Import-Package", new TreeMap>(imports)); print("Export-Package", new TreeMap>(exports)); } else warning("File has no manifest"); } if ((options & (USES | USEDBY)) != 0) { out.println(); Analyzer analyzer = new Analyzer(); analyzer.setPedantic(isPedantic()); analyzer.setJar(jar); analyzer.analyze(); if ((options & USES) != 0) { out.println("[USES]"); printMapOfSets(new TreeMap>(analyzer.getUses())); out.println(); } if ((options & USEDBY) != 0) { out.println("[USEDBY]"); printMapOfSets(invertMapOfCollection(analyzer.getUses())); } } if ((options & COMPONENT) != 0) { printComponents(out, jar); } if ((options & METATYPE) != 0) { printMetatype(out, jar); } if ((options & LIST) != 0) { out.println("[LIST]"); for (Map.Entry> entry : jar.getDirectories() .entrySet()) { String name = entry.getKey(); Map contents = entry.getValue(); out.println(name); if (contents != null) { for (String element : contents.keySet()) { int n = element.lastIndexOf('/'); if (n > 0) element = element.substring(n + 1); out.print(" "); out.print(element); String path = element; if (name.length() != 0) path = name + "/" + element; Resource r = contents.get(path); if (r != null) { String extra = r.getExtra(); if (extra != null) { out.print(" extra='" + escapeUnicode(extra) + "'"); } } out.println(); } } else { out.println(name + " "); } } out.println(); } } finally { jar.close(); } } private final char nibble(int i) { return "0123456789ABCDEF".charAt(i & 0xF); } private final String escapeUnicode(String s) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); if (c >= ' ' && c <= '~' && c != '\\') sb.append(c); else { sb.append("\\u"); sb.append(nibble(c >> 12)); sb.append(nibble(c >> 8)); sb.append(nibble(c >> 4)); sb.append(nibble(c)); } } return sb.toString(); } /** * Print the components in this JAR. * * @param jar */ private void printComponents(PrintStream out, Jar jar) throws Exception { out.println("[COMPONENTS]"); Manifest manifest = jar.getManifest(); if (manifest == null) { out.println("No manifest"); return; } String componentHeader = manifest.getMainAttributes().getValue(Constants.SERVICE_COMPONENT); Map> clauses = parseHeader(componentHeader); for (String path : clauses.keySet()) { out.println(path); Resource r = jar.getResource(path); if (r != null) { InputStreamReader ir = new InputStreamReader(r.openInputStream(), Constants.DEFAULT_CHARSET); OutputStreamWriter or = new OutputStreamWriter(out, Constants.DEFAULT_CHARSET); try { copy(ir, or); } finally { or.flush(); ir.close(); } } else { out.println(" - no resource"); warning("No Resource found for service component: " + path); } } out.println(); } /** * Print the metatypes in this JAR. * * @param jar */ private void printMetatype(PrintStream out, Jar jar) throws Exception { out.println("[METATYPE]"); Manifest manifest = jar.getManifest(); if (manifest == null) { out.println("No manifest"); return; } Map map = jar.getDirectories().get("OSGI-INF/metatype"); if (map != null) { for (Map.Entry entry : map.entrySet()) { out.println(entry.getKey()); IO.copy(entry.getValue().openInputStream(), out); out.println(); } out.println(); } } Map> invertMapOfCollection(Map> map) { Map> result = new TreeMap>(); for (Map.Entry> entry : map.entrySet()) { String name = entry.getKey(); if (name.startsWith("java.") && !name.equals("java.sql")) continue; Collection used = entry.getValue(); for (String n : used) { if (n.startsWith("java.") && !n.equals("java.sql")) continue; Set set = result.get(n); if (set == null) { set = new TreeSet(); result.put(n, set); } set.add(name); } } return result; } void printMapOfSets(Map> map) { for (Map.Entry> entry : map.entrySet()) { String name = entry.getKey(); Set used = new TreeSet(entry.getValue()); for (Iterator k = used.iterator(); k.hasNext();) { String n = (String) k.next(); if (n.startsWith("java.") && !n.equals("java.sql")) k.remove(); } String list = vertical(40, used); format("%-40s %s", new Object[] { name, list }); } } String vertical(int padding, Set used) { StringBuffer sb = new StringBuffer(); String del = ""; for (Iterator u = used.iterator(); u.hasNext();) { String name = (String) u.next(); sb.append(del); sb.append(name); sb.append("\r\n"); del = pad(padding); } if (sb.length() == 0) sb.append("\r\n"); return sb.toString(); } String pad(int i) { StringBuffer sb = new StringBuffer(); while (i-- > 0) sb.append(' '); return sb.toString(); } /** * View files from JARs * * We parse the commandline and print each file on it. * * @param args * @param i * @throws Exception */ private void doView(String[] args, int i) throws Exception { int options = 0; String charset = "UTF-8"; File output = null; for (; i < args.length; i++) { if ("-charset".startsWith(args[i])) charset = args[++i]; else if ("-output".startsWith(args[i])) { output = new File(args[++i]); } else break; } if (i >= args.length) { error("Insufficient arguments for view, no JAR"); return; } String jar = args[i++]; if (i >= args.length) { error("No Files to view"); return; } doView(jar, args, i, charset, options, output); } private void doView(String jar, String[] args, int i, String charset, int options, File output) { File path = new File(jar).getAbsoluteFile(); File dir = path.getParentFile(); if (dir == null) { dir = new File(""); } if (!dir.exists()) { error("No such file: " + dir.getAbsolutePath()); return; } String name = path.getName(); if (name == null) name = "META-INF/MANIFEST.MF"; Instruction instruction = Instruction.getPattern(path.getName()); File[] children = dir.listFiles(); for (int j = 0; j < children.length; j++) { String base = children[j].getName(); // out.println("Considering: " + // children[j].getAbsolutePath() + " " + // instruction.getPattern()); if (instruction.matches(base) ^ instruction.isNegated()) { for (; i < args.length; i++) { doView(children[j], args[i], charset, options, output); } } } } private void doView(File file, String resource, String charset, int options, File output) { // out.println("doView:" + file.getAbsolutePath() ); try { Instruction instruction = Instruction.getPattern(resource); FileInputStream fin = new FileInputStream(file); ZipInputStream in = new ZipInputStream(fin); ZipEntry entry = in.getNextEntry(); while (entry != null) { // out.println("view " + file + ": " // + instruction.getPattern() + ": " + entry.getName() // + ": " + output + ": " // + instruction.matches(entry.getName())); if (instruction.matches(entry.getName()) ^ instruction.isNegated()) doView(entry.getName(), in, charset, options, output); in.closeEntry(); entry = in.getNextEntry(); } in.close(); fin.close(); } catch (Exception e) { out.println("Can not process: " + file.getAbsolutePath()); e.printStackTrace(); } } private void doView(String name, ZipInputStream in, String charset, int options, File output) throws Exception { int n = name.lastIndexOf('/'); name = name.substring(n + 1); InputStreamReader rds = new InputStreamReader(in, charset); OutputStreamWriter wrt = new OutputStreamWriter(out, Constants.DEFAULT_CHARSET); if (output != null) if (output.isDirectory()) wrt = new FileWriter(new File(output, name)); else wrt = new FileWriter(output); copy(rds, wrt); // rds.close(); also closes the stream which closes our zip it // seems if (output != null) wrt.close(); else wrt.flush(); } private void copy(Reader rds, Writer wrt) throws IOException { char buffer[] = new char[1024]; int size = rds.read(buffer); while (size > 0) { wrt.write(buffer, 0, size); size = rds.read(buffer); } } private void print(String msg, Map> ports) { if (ports.isEmpty()) return; out.println(msg); for (Map.Entry> entry : ports.entrySet()) { String key = entry.getKey(); Map clause = Create.copy(entry.getValue()); clause.remove("uses:"); format(" %-38s %s\r\n", key.trim(), clause.isEmpty() ? "" : clause.toString()); } } private void format(String string, Object... objects) { if (objects == null || objects.length == 0) return; StringBuffer sb = new StringBuffer(); int index = 0; for (int i = 0; i < string.length(); i++) { char c = string.charAt(i); switch (c) { case '%': String s = objects[index++] + ""; int width = 0; int justify = -1; i++; c = string.charAt(i++); switch (c) { case '-': justify = -1; break; case '+': justify = 1; break; case '|': justify = 0; break; default: --i; } c = string.charAt(i++); while (c >= '0' && c <= '9') { width *= 10; width += c - '0'; c = string.charAt(i++); } if (c != 's') { throw new IllegalArgumentException("Invalid sprintf format: " + string); } if (s.length() > width) sb.append(s); else { switch (justify) { case -1: sb.append(s); for (int j = 0; j < width - s.length(); j++) sb.append(" "); break; case 1: for (int j = 0; j < width - s.length(); j++) sb.append(" "); sb.append(s); break; case 0: int spaces = (width - s.length()) / 2; for (int j = 0; j < spaces; j++) sb.append(" "); sb.append(s); for (int j = 0; j < width - s.length() - spaces; j++) sb.append(" "); break; } } break; default: sb.append(c); } } out.print(sb); } private void doWrap(String[] args, int i) throws Exception { int options = 0; File properties = null; File output = null; File classpath[] = null; for (; i < args.length; i++) { if ("-output".startsWith(args[i])) output = new File(args[++i]); else if ("-properties".startsWith(args[i])) properties = new File(args[++i]); else if ("-classpath".startsWith(args[i])) { classpath = getClasspath(args[++i]); } else { File bundle = new File(args[i]); doWrap(properties, bundle, output, classpath, options, null); } } } public boolean doWrap(File properties, File bundle, File output, File classpath[], int options, Map additional) throws Exception { if (!bundle.exists()) { error("No such file: " + bundle.getAbsolutePath()); return false; } else { Analyzer analyzer = new Analyzer(); try { analyzer.setPedantic(isPedantic()); analyzer.setJar(bundle); Jar dot = analyzer.getJar(); if (properties != null) { analyzer.setProperties(properties); } if (additional != null) analyzer.putAll(additional, false); if (analyzer.getProperty(Analyzer.IMPORT_PACKAGE) == null) analyzer.setProperty(Analyzer.IMPORT_PACKAGE, "*;resolution:=optional"); if (analyzer.getProperty(Analyzer.BUNDLE_SYMBOLICNAME) == null) { Pattern p = Pattern.compile("(" + Verifier.SYMBOLICNAME.pattern() + ")(-[0-9])?.*\\.jar"); String base = bundle.getName(); Matcher m = p.matcher(base); base = "Untitled"; if (m.matches()) { base = m.group(1); } else { error("Can not calculate name of output bundle, rename jar or use -properties"); } analyzer.setProperty(Analyzer.BUNDLE_SYMBOLICNAME, base); } if (analyzer.getProperty(Analyzer.EXPORT_PACKAGE) == null) { String export = analyzer.calculateExportsFromContents(dot); analyzer.setProperty(Analyzer.EXPORT_PACKAGE, export); } if (classpath != null) analyzer.setClasspath(classpath); analyzer.mergeManifest(dot.getManifest()); // // Cleanup the version .. // String version = analyzer.getProperty(Analyzer.BUNDLE_VERSION); if (version != null) { version = Builder.cleanupVersion(version); analyzer.setProperty(Analyzer.BUNDLE_VERSION, version); } if (output == null) if (properties != null) output = properties.getAbsoluteFile().getParentFile(); else output = bundle.getAbsoluteFile().getParentFile(); String path = bundle.getName(); if (path.endsWith(DEFAULT_JAR_EXTENSION)) path = path.substring(0, path.length() - DEFAULT_JAR_EXTENSION.length()) + DEFAULT_BAR_EXTENSION; else path = bundle.getName() + DEFAULT_BAR_EXTENSION; if (output.isDirectory()) output = new File(output, path); analyzer.calcManifest(); Jar jar = analyzer.getJar(); getInfo(analyzer); statistics(jar, output, ""); File f = File.createTempFile("tmpbnd", ".jar"); f.deleteOnExit(); try { jar.write(f); jar.close(); if (!f.renameTo(output)) { copy(f, output); } } finally { f.delete(); } return getErrors().size() == 0; } finally { analyzer.close(); } } } void doDiff(String args[], int first) throws Exception { File base = new File(""); boolean strict = false; Jar targets[] = new Jar[2]; int n = 0; for (int i = first; i < args.length; i++) { if ("-d".equals(args[i])) base = getFile(base, args[++i]); else if ("-strict".equals(args[i])) strict = "true".equalsIgnoreCase(args[++i]); else if (args[i].startsWith("-")) error("Unknown option for diff: " + args[i]); else { if (n >= 2) System.err.println("Must have 2 files ... not more"); else { File f = getFile(base, args[i]); if (!f.isFile()) System.err.println("Not a file: " + f); else { try { Jar jar = new Jar(f); targets[n++] = jar; } catch (Exception e) { System.err.println("Not a JAR: " + f); } } } } } if (n != 2) { System.err.println("Must have 2 files ..."); return; } Diff diff = new Diff(); Map map = diff.diff(targets[0], targets[1], strict); diff.print(System.out, map, 0); for (Jar jar : targets) { jar.close(); } diff.close(); } void copy(File a, File b) { try { InputStream in = new FileInputStream(a); OutputStream out = new FileOutputStream(b); byte[] buffer = new byte[8196]; int size = in.read(buffer); while (size > 0) { out.write(buffer, 0, size); size = in.read(buffer); } in.close(); out.close(); } catch (IOException e) { error("While copying the output: %s -> %s", e, a, b); } } public void setOut(PrintStream out) { this.out = out; } public Project getProject() throws Exception { if (project != null) return project; try { project = Workspace.getProject(getBase()); if (project == null) return null; if (!project.isValid()) return null; return project; } catch (IllegalArgumentException e) { return null; } } /** * Printout all the variables. * * @param args * @param i * @throws Exception */ public void debug(String args[], int i) throws Exception { Project project = getProject(); System.out.println("Project: " + project); Properties p = project.getFlattenedProperties(); for (Object k : p.keySet()) { String key = (String) k; String s = p.getProperty(key); Collection l = null; if (s.indexOf(',') > 0) l = split(s); else if (s.indexOf(':') > 0) l = split(s, "\\s*:\\s*"); if (l != null) { String del = key; for (String ss : l) { System.out.printf("%-40s %s\n", del, ss); del = ""; } } else System.out.printf("%-40s %s\n", key, s); } } /** * Manage the repo. * *
	 *  repo
	 *      list
	 *      put <file|url>
	 *      get <bsn> (<version>)?
	 *      fetch <file|url>
	 * 
*/ public void repo(String args[], int i) throws Exception { String bsn = null; String version = null; List repos = new ArrayList(); RepositoryPlugin writable = null; Project p = Workspace.getProject(getBase()); if (p != null) { repos.addAll(p.getWorkspace().getRepositories()); for (Iterator rp = repos.iterator(); rp.hasNext();) { RepositoryPlugin rpp = rp.next(); if (rpp.canWrite()) { writable = rpp; break; } } } for (; i < args.length; i++) { if ("repos".equals(args[i])) { int n = 0; for (RepositoryPlugin repo : repos) { out.printf("%3d. %s\n", n++, repo); } } else if ("list".equals(args[i])) { String mask = null; if (i < args.length - 1) { mask = args[++i]; } repoList(repos, mask); } else if ("-repo".equals(args[i])) { String location = args[++i]; if (location.equals("maven")) { System.out.println("Maven"); MavenRepository maven = new MavenRepository(); maven.setProperties(new HashMap()); maven.setReporter(this); repos = Arrays.asList((RepositoryPlugin) maven); } else { FileRepo repo = new FileRepo(); repo.setReporter(this); repo.setLocation(location); repos = Arrays.asList((RepositoryPlugin) repo); writable = repo; } } else if ("-bsn".equals(args[i])) { bsn = args[++i]; } else if ("-version".equals(args[i])) { version = args[++i]; } else if ("spring".equals(args[i])) { if (bsn == null || version == null) { error("-bsn and -version must be set before spring command is used"); } else { String url = String .format("http://www.springsource.com/repository/app/bundle/version/download?name=%s&version=%s&type=binary", bsn, version); repoPut(writable, p, url, bsn, version); } } else if ("put".equals(args[i])) while (++i < args.length) { repoPut(writable, p, args[i], bsn, version); } else if ("get".equals(args[i])) repoGet(repos, args[++i]); else repoFetch(repos, args[++i]); } } private void repoGet(List writable, String string) { } private void repoPut(RepositoryPlugin writable, Project project, String file, String bsn, String version) throws Exception { Jar jar = null; int n = file.indexOf(':'); if (n > 1 && n < 10) { jar = project.getValidJar(new URL(file)); } else { File f = getFile(file); if (f.isFile()) { jar = project.getValidJar(f); } } if (jar != null) { Manifest manifest = jar.getManifest(); if (bsn != null) manifest.getMainAttributes().putValue(Constants.BUNDLE_SYMBOLICNAME, bsn); if (version != null) manifest.getMainAttributes().putValue(Constants.BUNDLE_VERSION, version); writable.put(jar); } else error("There is no such file or url: " + file); } private void repoFetch(List repos, String string) { File f = getFile(string); if (f.isFile()) { } else { // try { // URL url = new URL(string); // } catch (MalformedURLException mue) { // // } } } void repoList(List repos, String mask) throws Exception { trace("list repo " + repos + " " + mask); Set bsns = new TreeSet(); for (RepositoryPlugin repo : repos) { bsns.addAll(repo.list(mask)); } for (String bsn : bsns) { Set versions = new TreeSet(); for (RepositoryPlugin repo : repos) { List result = repo.versions(bsn); if (result != null) versions.addAll(result); } out.printf("%-40s %s\n", bsn, versions); } } /** * Patch */ void patch(String args[], int i) throws Exception { for (; i < args.length; i++) { if ("create".equals(args[i]) && i + 3 < args.length) { createPatch(args[++i], args[++i], args[++i]); } else if ("apply".equals(args[i]) && i + 3 < args.length) { applyPatch(args[++i], args[++i], args[++i]); } else if ("help".equals(args[i])) { out.println("patch (create | patch )"); } else out.println("Patch does not recognize command? " + Arrays.toString(args)); } } void createPatch(String old, String newer, String patch) throws Exception { Jar a = new Jar(new File(old)); Manifest am = a.getManifest(); Jar b = new Jar(new File(newer)); Manifest bm = b.getManifest(); Set delete = newSet(); for (String path : a.getResources().keySet()) { Resource br = b.getResource(path); if (br == null) { trace("DELETE %s", path); delete.add(path); } else { Resource ar = a.getResource(path); if (isEqual(ar, br)) { trace("UNCHANGED %s", path); b.remove(path); } else trace("UPDATE %s", path); } } bm.getMainAttributes().putValue("Patch-Delete", join(delete, ", ")); bm.getMainAttributes().putValue("Patch-Version", am.getMainAttributes().getValue("Bundle-Version")); b.write(new File(patch)); a.close(); a.close(); } private boolean isEqual(Resource ar, Resource br) throws Exception { InputStream ain = ar.openInputStream(); try { InputStream bin = br.openInputStream(); try { while (true) { int an = ain.read(); int bn = bin.read(); if (an == bn) { if (an == -1) return true; } else return false; } } finally { bin.close(); } } finally { ain.close(); } } void applyPatch(String old, String patch, String newer) throws Exception { Jar a = new Jar(new File(old)); Jar b = new Jar(new File(patch)); Manifest bm = b.getManifest(); String patchDelete = bm.getMainAttributes().getValue("Patch-Delete"); String patchVersion = bm.getMainAttributes().getValue("Patch-Version"); if (patchVersion == null) { error("To patch, you must provide a patch bundle.\nThe given " + patch + " bundle does not contain the Patch-Version header"); return; } Collection delete = split(patchDelete); Set paths = new HashSet(a.getResources().keySet()); paths.removeAll(delete); for (String path : paths) { Resource br = b.getResource(path); if (br == null) b.putResource(path, a.getResource(path)); } bm.getMainAttributes().putValue("Bundle-Version", patchVersion); b.write(new File(newer)); a.close(); b.close(); } /** * Run the tests from a prepared bnd file. * * @param args * @param i * @throws Exception */ public void runtests(String args[], int i) throws Exception { int errors = 0; File cwd = new File("").getAbsoluteFile(); Workspace ws = new Workspace(cwd); File reportDir = getFile("reports"); IO.delete(reportDir); reportDir.mkdirs(); Tag summary = new Tag("summary"); summary.addAttribute("date", new Date()); summary.addAttribute("ws", ws.getBase()); try { boolean hadOne = false; for (; i < args.length; i++) { if (args[i].startsWith("-reportdir")) { reportDir = getFile(args[++i]).getAbsoluteFile(); if (!reportDir.isDirectory()) error("reportdir must be a directory " + reportDir); } else if (args[i].startsWith("-title")) { summary.addAttribute("title", args[++i]); } else if (args[i].startsWith("-dir")) { cwd = getFile(args[++i]).getAbsoluteFile(); } else if (args[i].startsWith("-workspace")) { File tmp = getFile(args[++i]).getAbsoluteFile(); ws = Workspace.getWorkspace(tmp); } else { File f = getFile(args[i]); errors += runtTest(f, ws, reportDir, summary); hadOne = true; } } if (!hadOne) { // See if we had any, if so, just use all files in // the current directory File[] files = cwd.listFiles(); for (File f : files) { if (f.getName().endsWith(".bnd")) { errors += runtTest(f, ws, reportDir, summary); } } } } catch (Throwable e) { e.printStackTrace(); error("FAILURE IN RUNTESTS", e); errors++; } if (errors > 0) summary.addAttribute("errors", errors); for (String error : getErrors()) { Tag e = new Tag("error"); e.addContent(error); } for (String warning : getWarnings()) { Tag e = new Tag("warning"); e.addContent(warning); } File r = getFile(reportDir + "/summary.xml"); FileOutputStream out = new FileOutputStream(r); PrintWriter pw = new PrintWriter(new OutputStreamWriter(out, Constants.DEFAULT_CHARSET)); try { summary.print(0, pw); } finally { pw.close(); out.close(); } if (errors != 0) error("Errors found %s", errors); } private int runtTest(File testFile, Workspace ws, File reportDir, Tag summary) throws Exception { File tmpDir = new File(reportDir, "tmp"); tmpDir.mkdirs(); tmpDir.deleteOnExit(); Tag test = new Tag(summary, "test"); test.addAttribute("path", testFile.getAbsolutePath()); if (!testFile.isFile()) { error("No bnd file: %s", testFile); test.addAttribute("exception", "No bnd file found"); throw new FileNotFoundException("No bnd file found for " + testFile.getAbsolutePath()); } Project project = new Project(ws, testFile.getAbsoluteFile().getParentFile(), testFile.getAbsoluteFile()); project.setTrace(isTrace()); project.setProperty(NOBUNDLES, "true"); ProjectTester tester = project.getProjectTester(); getInfo(project, project.toString() + ": "); if (!isOk()) throw new IllegalStateException("Errors found while creating the bnd test project " + testFile.getAbsolutePath()); tester.setContinuous(false); tester.setReportDir(tmpDir); test.addAttribute("title", project.toString()); long start = System.currentTimeMillis(); try { int errors = tester.test(); Collection reports = tester.getReports(); for (File report : reports) { Tag bundle = new Tag(test, "bundle"); File dest = new File(reportDir, report.getName()); report.renameTo(dest); bundle.addAttribute("file", dest.getAbsolutePath()); doPerReport(bundle, dest); } switch (errors) { case ProjectLauncher.OK: return 0; case ProjectLauncher.CANCELED: test.addAttribute("failed", "canceled"); return 1; case ProjectLauncher.DUPLICATE_BUNDLE: test.addAttribute("failed", "duplicate bundle"); return 1; case ProjectLauncher.ERROR: test.addAttribute("failed", "unknown reason"); return 1; case ProjectLauncher.RESOLVE_ERROR: test.addAttribute("failed", "resolve error"); return 1; case ProjectLauncher.TIMEDOUT: test.addAttribute("failed", "timed out"); return 1; case ProjectLauncher.WARNING: test.addAttribute("warning", "true"); return 1; case ProjectLauncher.ACTIVATOR_ERROR: test.addAttribute("failed", "activator error"); return 1; default: if (errors > 0) { test.addAttribute("errors", errors); return errors; } else { test.addAttribute("failed", "unknown reason"); return 1; } } } catch (Exception e) { test.addAttribute("failed", e); throw e; } finally { long duration = System.currentTimeMillis() - start; test.addAttribute("duration", (duration + 500) / 1000); getInfo(project, project.toString() + ": "); } } /** * Calculate the coverage if there is coverage info in the test file. */ private void doPerReport(Tag report, File file) throws Exception { try { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true); // never forget this! DocumentBuilder builder = factory.newDocumentBuilder(); Document doc = builder.parse(file); XPathFactory xpathFactory = XPathFactory.newInstance(); XPath xpath = xpathFactory.newXPath(); doCoverage(report, doc, xpath); doHtmlReport(report, file, doc, xpath); } catch (Exception e) { report.addAttribute("coverage-failed", e.getMessage()); } } private void doCoverage(Tag report, Document doc, XPath xpath) throws XPathExpressionException { int bad = Integer.parseInt(xpath.evaluate("count(//method[count(ref)<2])", doc)); int all = Integer.parseInt(xpath.evaluate("count(//method)", doc)); report.addAttribute("coverage-bad", bad); report.addAttribute("coverage-all", all); } private void doHtmlReport(Tag report, File file, Document doc, XPath xpath) throws Exception { String path = file.getAbsolutePath(); if (path.endsWith(".xml")) path = path.substring(0, path.length() - 4); path += ".html"; File html = new File(path); trace("Creating html report: %s", html); TransformerFactory fact = TransformerFactory.newInstance(); InputStream in = getClass().getResourceAsStream("testreport.xsl"); if (in == null) { warning("Resource not found: test-report.xsl, no html report"); } else { FileWriter out = new FileWriter(html); try { Transformer transformer = fact.newTransformer(new StreamSource(in)); transformer.transform(new DOMSource(doc), new StreamResult(out)); trace("Transformed"); } finally { in.close(); out.close(); } } } /** * Extract a file from the JAR */ public void doExtract(String args[], int i) throws Exception { if (i >= args.length) { error("No arguments for extract"); return; } File f = getFile(args[i++]); if (!f.isFile()) { error("No JAR file to extract from: %s", f); return; } if (i == args.length) { System.out.println("FILES:"); doPrint(f, LIST); return; } Jar j = new Jar(f); try { Writer output = new OutputStreamWriter(out, Constants.DEFAULT_CHARSET); while (i < args.length) { String path = args[i++]; Resource r = j.getResource(path); if (r == null) error("No such resource: %s in %s", path, f); else { InputStream in = r.openInputStream(); try { InputStreamReader rds = new InputStreamReader(in, Constants.DEFAULT_CHARSET); copy(rds, output); output.flush(); } finally { in.close(); } } } } finally { j.close(); } } void doDot(String args[], int i) throws Exception { File out = getFile("graph.gv"); Builder b = new Builder(); for (; i < args.length; i++) { if ("-o".equals(args[i])) out = getFile(args[++i]); else if (args[i].startsWith("-")) error("Unknown option for dot: %s", args[i]); else b.addClasspath(getFile(args[i])); } b.setProperty(EXPORT_PACKAGE, "*"); b.setPedantic(isPedantic()); b.build(); FileWriter os = new FileWriter(out); PrintWriter pw = new PrintWriter(os); try { pw.println("digraph bnd {"); pw.println(" size=\"6,6\";"); pw.println("node [color=lightblue2, style=filled,shape=box];"); for (Map.Entry> uses : b.getUses().entrySet()) { for (String p : uses.getValue()) { if (!p.startsWith("java.")) pw.printf("\"%s\" -> \"%s\";\n", uses.getKey(), p); } } pw.println("}"); } finally { pw.close(); } } private void traverse(List files, File f) { if (f.isFile()) { if (f.getName().endsWith(".jar")) files.add(f); } else if (f.isDirectory()) { File[] subs = f.listFiles(); for (File sub : subs) { traverse(files, sub); } } } public void global(String args[], int i) throws BackingStoreException { Settings settings = new Settings(); if (args.length == i) { for (String key : settings.getKeys()) System.out.printf("%-30s %s\n", key, settings.globalGet(key, "<>")); } else { while (i < args.length) { boolean remove = false; if ("-remove".equals(args[i])) { remove = true; i++; } if (i + 1 == args.length) { if (remove) settings.globalRemove(args[i]); else System.out.printf("%-30s %s\n", args[i], settings.globalGet(args[i], "<>")); i++; } else { settings.globalSet(args[i], args[i + 1]); i += 2; } } } } /** * Merge a bundle with its source. * * @throws Exception */ public void doMerge(String args[], int i) throws Exception { File out = null; // String prefix = ""; // boolean maven; List sourcePath = new ArrayList(); while (i < args.length - 1) { String arg = args[i++]; if (arg.equals("-o")) { out = getFile(arg); } else if (arg.equals("-maven")) { // maven = true; } else { File source = getFile(arg); if (source.exists()) { Jar jar = new Jar(source); addClose(jar); sourcePath.add(jar); } else { error("Sourec file/dir does not exist"); } } } if (i >= args.length) { error("No binary file specified"); return; } File binary = getFile(args[i]); Jar output = new Jar(binary); try { Analyzer analyzer = new Analyzer(); analyzer.setJar(output); analyzer.analyze(); outer: for (Clazz clazz : analyzer.getClassspace().values()) { String sourcename = clazz.getSourceFile(); String path = clazz.getPath(); int n = path.lastIndexOf('/'); if (n >= 0) { path = path.substring(0, n + 1); } else path = ""; String cname = path + sourcename; for (Jar source : sourcePath) { Resource r = source.getResource(cname); if (r != null) { output.putResource("OSGI-OPT/src/" + cname, r); continue outer; } } error("Source not found %s", cname); } if (out == null) { File backup = new File(binary.getAbsolutePath() + ".bak"); binary.renameTo(backup); out = binary; } output.write(out); } finally { output.close(); for (Jar jar : sourcePath) jar.close(); } } /** * Create lib file on a directory. * * @throws Exception * * @throws Exception */ public void doLib(String args[], int i) throws Exception { File out = null; List files = new ArrayList(); while (i < args.length) { String arg = args[i++]; if ("-o".equals(arg)) { out = getFile(args[i++]); } else if (arg.startsWith("-")) { error("Unknown option: %s", arg); } else files.add(getFile(arg)); } if (files.isEmpty()) { error("No files specified for lib"); return; } if (out == null) { out = getFile(files.get(0).getName() + ".lib"); } System.out.println("Using " + out); Writer w = new FileWriter(out); try { for (File file : files) { System.out.println("And using " + file); if (file.isDirectory()) doLib(file, w); else if (file.isFile()) doSingleFileLib(file, w); else if (!file.equals(out)) error("Not a file %s", file); } } finally { w.close(); } } public void doLib(File dir, Appendable out) throws Exception { for (File file : dir.listFiles()) { doSingleFileLib(file, out); } } /** * @param out * @param file * @throws IOException * @throws Exception */ void doSingleFileLib(File file, Appendable out) throws IOException, Exception { Jar jar = new Jar(file); String bsn = jar.getBsn(); System.out.println(bsn); String version = jar.getVersion(); jar.close(); if (bsn == null) { error("No valid bsn for %s", file); bsn = "not set"; } if (version == null) version = "0"; Version v = new Version(version); v = new Version(v.getMajor(), v.getMinor(), v.getMicro()); out.append(bsn); out.append(";version=" + v + "\n"); // '[" + v + "," + v + "]'\n"); } /** * @return * @throws IOException * @throws MalformedURLException */ protected Jar getJarFromFileOrURL(String spec) throws IOException, MalformedURLException { Jar jar; File jarFile = getFile(spec); if (jarFile.exists()) { jar = new Jar(jarFile); } else { URL url = new URL(spec); InputStream in = url.openStream(); try { jar = new Jar(url.getFile(), in); } finally { in.close(); } } addClose(jar); return jar; } } bnd-1.50.0/biz.aQute.bnd/src/aQute/bnd/main/packageinfo0000755000175000017500000000001411656076535022403 0ustar drazzibdrazzibversion 0.9 bnd-1.50.0/biz.aQute.bnd/src/aQute/bnd/main/maven-settings.xsl0000644000175000017500000000047711656076535023717 0ustar drazzibdrazzib bnd-1.50.0/biz.aQute.bnd/src/aQute/bnd/main/component.xslt0000644000175000017500000000413711656076535023136 0ustar drazzibdrazzib Name Enabled Factory Immediate Configuration Policy Activate Modified Deactivate Implementation Properties Service (servicefactory=) Reference Interface Cardinality Policy Target Bind method Unbind method bnd-1.50.0/biz.aQute.bnd/src/aQute/bnd/main/testreport.xsl0000644000175000017500000001656211656076535023170 0ustar drazzibdrazzib Test

Summary

The following table provides a summary of the test information.

Property Key Property Value
Target
Framework
Testrun
Bundles

Testcases

The following table shows the results of each test. A red icon indicates that the test failed or had an error. A green icon indicates success. Any errors or failure messages will be displayed as a list beneath the test name. To see the exception, click on the info icon on the right.

Test Failures Error Info
ok warning error

Coverage

The following table provides a sumary of the coverage based on static analysis. A red icon indicates the method is never referred. An orange icon indicates there is only one method referring to the method and a green icon indicates there are 2 or more references. The references are shown by clicking on the info icon. This table is based on static analysis so it is not possible to see how often the method is called and with what parameters.

ok error
bnd-1.50.0/biz.aQute.bnd/src/aQute/bnd/plugin/0000755000175000017500000000000011656076535020565 5ustar drazzibdrazzibbnd-1.50.0/biz.aQute.bnd/src/aQute/bnd/plugin/editors/0000755000175000017500000000000011656076535022236 5ustar drazzibdrazzibbnd-1.50.0/biz.aQute.bnd/src/aQute/bnd/plugin/editors/BndCompletionProcessor.java0000644000175000017500000000263711656076535027546 0ustar drazzibdrazzibpackage aQute.bnd.plugin.editors; import org.eclipse.jface.text.*; import org.eclipse.jface.text.contentassist.*; import aQute.bnd.help.*; public class BndCompletionProcessor implements IContentAssistProcessor { public ICompletionProposal[] computeCompletionProposals(ITextViewer viewer, int offset) { ICompletionProposal[] result= new ICompletionProposal[Syntax.HELP.size()]; int i=0; for ( Syntax s : Syntax.HELP.values()) { IContextInformation info= new ContextInformation( s.getHeader(), s.getHeader()); result[i++]= new CompletionProposal(s.getHeader()+": ", offset-1, 1, s.getHeader().length()+2, null, s.getHeader(), info, s.getLead()); //$NON-NLS-1$ } return result; } public IContextInformation[] computeContextInformation(ITextViewer viewer, int offset) { // TODO Auto-generated method stub return null; } public char[] getCompletionProposalAutoActivationCharacters() { return new char[] {'-'}; } public char[] getContextInformationAutoActivationCharacters() { return new char[] {'-'}; } public IContextInformationValidator getContextInformationValidator() { // TODO Auto-generated method stub return null; } public String getErrorMessage() { // TODO Auto-generated method stub return null; } } bnd-1.50.0/biz.aQute.bnd/src/aQute/bnd/plugin/editors/MacroRule.java0000644000175000017500000000266011656076535024776 0ustar drazzibdrazzibpackage aQute.bnd.plugin.editors; import org.eclipse.jface.text.rules.*; import aQute.lib.osgi.*; public class MacroRule implements IRule { private StringBuffer buffer = new StringBuffer(); private IToken token; public MacroRule(IToken token) { this.token = token; } public IToken evaluate(ICharacterScanner scanner) { int c = scanner.read(); if (c == '$') { buffer.setLength(0); buffer.append('$'); if ( scan(scanner, buffer) ) return token; } scanner.unread(); return Token.UNDEFINED; } boolean scan( ICharacterScanner scanner, StringBuffer buffer ) { int c = scanner.read(); if (c == ICharacterScanner.EOF) return false; int terminator = Macro.getTerminator((char) c); if (terminator == 0) return false; while(true) { c = scanner.read(); buffer.append((char)c); if ( c == terminator ) return true; else if ( c == '$') { if ( !scan(scanner, buffer) ) return false; } else if ( c == '\\') { c = scanner.read(); if ( c == ICharacterScanner.EOF) return false; buffer.append((char)c); } } } } bnd-1.50.0/biz.aQute.bnd/src/aQute/bnd/plugin/editors/BndSourceViewerConfiguration.java0000755000175000017500000001075311656076535030710 0ustar drazzibdrazzibpackage aQute.bnd.plugin.editors; import java.util.*; import org.eclipse.jface.text.*; import org.eclipse.jface.text.contentassist.*; import org.eclipse.jface.text.presentation.*; import org.eclipse.jface.text.rules.*; import org.eclipse.jface.text.source.*; import org.eclipse.swt.*; import org.eclipse.swt.graphics.*; public class BndSourceViewerConfiguration extends SourceViewerConfiguration { Token T_DEFAULT; Token T_MACRO; Token T_ERROR; Token T_COMMENT; Token T_INSTRUCTION; Token T_OPTION; Token T_DIRECTIVE; Token T_PROPERTY; Token T_COMPONENT; static final String SINGLELINE_COMMENT_TYPE = "___slc"; static Properties syntax = null; class BndPartitionScanner extends RuleBasedPartitionScanner { public BndPartitionScanner() { IToken singleLineComment = new Token(SINGLELINE_COMMENT_TYPE); IPredicateRule[] rules = new IPredicateRule[] { new EndOfLineRule( "#", singleLineComment), }; setPredicateRules(rules); } } BndScanner scanner; MultiLineCommentScanner multiLineCommentScanner; ISharedTextColors colors; public BndSourceViewerConfiguration(ISharedTextColors colors) { this.colors = colors; T_DEFAULT = new Token(new TextAttribute(colors.getColor(new RGB(0, 0, 0)))); T_MACRO = new Token(new TextAttribute(colors.getColor(new RGB(0, 255, 0)), null, SWT.BOLD)); T_ERROR = new Token(new TextAttribute(colors.getColor(new RGB(255, 0, 0)), null, SWT.BOLD)); T_COMMENT = new Token(new TextAttribute(colors.getColor(new RGB(128, 0, 0)))); T_INSTRUCTION = new Token(new TextAttribute(colors.getColor(new RGB(0, 0, 255)), null, SWT.BOLD)); T_OPTION = new Token(new TextAttribute(colors.getColor(new RGB(0, 0, 255)))); T_DIRECTIVE = new Token(new TextAttribute(colors.getColor(new RGB(60, 60, 255)), null, SWT.BOLD)); T_PROPERTY = new Token(new TextAttribute(colors.getColor(new RGB(60, 60, 255)), null, SWT.BOLD)); T_COMPONENT = new Token(new TextAttribute(colors.getColor(new RGB(60, 60, 255)), null, SWT.BOLD)); } public IPresentationReconciler getPresentationReconciler( ISourceViewer sourceViewer) { PresentationReconciler reconciler = new PresentationReconciler(); configureReconciler(reconciler, IDocument.DEFAULT_CONTENT_TYPE, getBndScanner()); configureReconciler(reconciler, SINGLELINE_COMMENT_TYPE, getMultiLineCommentScanner()); return reconciler; } private void configureReconciler(PresentationReconciler reconciler, String partitionType, ITokenScanner scanner) { DefaultDamagerRepairer dr; dr = new DefaultDamagerRepairer(scanner); reconciler.setDamager(dr, partitionType); reconciler.setRepairer(dr, partitionType); } protected BndScanner getBndScanner() { if (scanner == null) { scanner = new BndScanner(this); } return scanner; } class MultiLineCommentScanner extends RuleBasedScanner { public MultiLineCommentScanner() { setDefaultReturnToken(T_COMMENT); } } protected MultiLineCommentScanner getMultiLineCommentScanner() { if (multiLineCommentScanner == null) { multiLineCommentScanner = new MultiLineCommentScanner(); } return multiLineCommentScanner; } public String[] getDefaultPrefixes(ISourceViewer sourceViewer, String contentType) { if (IDocument.DEFAULT_CONTENT_TYPE == contentType || SINGLELINE_COMMENT_TYPE == contentType) { return new String[] { "#", "//" }; } return null; } @Override public ITextHover getTextHover(ISourceViewer sourceViewer, String contentType) { return new BndHover(); } @Override public IContentAssistant getContentAssistant(ISourceViewer viewer) { ContentAssistant assistant = new ContentAssistant(); assistant.setContentAssistProcessor(new BndCompletionProcessor(), IDocument.DEFAULT_CONTENT_TYPE); assistant.setContentAssistProcessor(new BndCompletionProcessor(), SINGLELINE_COMMENT_TYPE); assistant.enableAutoActivation(true); return assistant; } }bnd-1.50.0/biz.aQute.bnd/src/aQute/bnd/plugin/editors/BndScanner.java0000755000175000017500000000461011656076535025122 0ustar drazzibdrazzibpackage aQute.bnd.plugin.editors; import java.util.*; import org.eclipse.jface.text.rules.*; import aQute.bnd.make.component.*; import aQute.lib.osgi.*; public class BndScanner extends RuleBasedScanner { BndSourceViewerConfiguration bsvc; public BndScanner(BndSourceViewerConfiguration manager) { bsvc = manager; IRule[] rules = new IRule[] { new WhitespaceRule(new IWhitespaceDetector() { public boolean isWhitespace(char c) { return (c == ' ' || c == '\t' || c == '\n' || c == '\r'); } }), new BndWordRule(), new MacroRule(bsvc.T_MACRO), new EndOfLineRule("#", bsvc.T_COMMENT), new EndOfLineRule("\\ ", bsvc.T_ERROR), new EndOfLineRule("\\\t", bsvc.T_ERROR), }; setRules(rules); setDefaultReturnToken(bsvc.T_DEFAULT); } class BndWordRule implements IRule { Map keyWords = new HashMap(); public BndWordRule() { addWords(Analyzer.headers, bsvc.T_INSTRUCTION); addWords(Analyzer.options, bsvc.T_OPTION); addWords(Analyzer.directives, bsvc.T_DIRECTIVE); addWords(Constants.componentDirectives, bsvc.T_COMPONENT); } private boolean isWordStart(char c) { return Character.isJavaIdentifierStart(c); } private boolean isWordPart(char c) { return Character.isJavaIdentifierPart(c) || c == '-'; } public IToken evaluate(ICharacterScanner scanner) { StringBuffer sb = new StringBuffer(); int c = scanner.read(); if (isWordStart((char) c) || c == '-') { do { sb.append((char) c); c = scanner.read(); } while (c != ICharacterScanner.EOF && isWordPart((char) c)); scanner.unread(); IToken token = (IToken) keyWords.get(sb.toString()); if (token != null) return token; return bsvc.T_DEFAULT; } scanner.unread(); return Token.UNDEFINED; } private void addWords(String[] words, IToken token) { for (int i = 0; i < words.length; ++i) { keyWords.put(words[i], token); } } } } bnd-1.50.0/biz.aQute.bnd/src/aQute/bnd/plugin/editors/BndMultiPageEditor.java0000755000175000017500000001617311656076535026576 0ustar drazzibdrazzibpackage aQute.bnd.plugin.editors; import java.io.*; import java.text.*; import java.util.*; import org.eclipse.core.resources.*; import org.eclipse.core.runtime.*; import org.eclipse.jface.dialogs.*; import org.eclipse.jface.viewers.*; import org.eclipse.swt.*; import org.eclipse.swt.custom.*; import org.eclipse.swt.layout.*; import org.eclipse.swt.widgets.*; import org.eclipse.ui.*; import org.eclipse.ui.editors.text.*; import org.eclipse.ui.ide.*; import org.eclipse.ui.part.*; /** */ public class BndMultiPageEditor extends MultiPageEditorPart implements IResourceChangeListener { private Table table; /** The text editor used in page 0. */ private TextEditor editor; /** The text widget used in page 2. */ private StyledText text; /** * Creates a multi-page editor example. */ public BndMultiPageEditor() { super(); ResourcesPlugin.getWorkspace().addResourceChangeListener(this); } /** * Creates page 0 of the multi-page editor, which contains a text editor. */ void createTextEditor() { try { editor = new BndTextEditor(); int index = addPage(editor, getEditorInput()); setPageText(index, editor.getTitle()); } catch (PartInitException e) { ErrorDialog.openError(getSite().getShell(), "Error creating nested text editor", null, e.getStatus()); } } /** * Creates page 1 of the multi-page editor, which allows you to change the * font used in page 2. */ void createPage1() { Composite composite = new Composite(getContainer(), SWT.NONE); GridLayout layout = new GridLayout(); composite.setLayout(layout); int index = addPage(composite); final TableViewer tableViewer = new TableViewer(composite, SWT.BORDER); table = tableViewer.getTable(); table.setLinesVisible(true); table.setHeaderVisible(true); table.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); final TableColumn tableColumn = new TableColumn(table, SWT.NONE); tableColumn.setWidth(100); tableColumn.setText("Key"); final TableColumn tableColumn_1 = new TableColumn(table, SWT.NONE); tableColumn_1.setWidth(1000); tableColumn_1.setText("Value"); setPageText(index, "Properties"); } /** * Creates page 2 of the multi-page editor, which shows the sorted text. */ void createPage2() { Composite composite = new Composite(getContainer(), SWT.NONE); FillLayout layout = new FillLayout(); composite.setLayout(layout); text = new StyledText(composite, SWT.H_SCROLL | SWT.V_SCROLL); text.setEditable(false); int index = addPage(composite); setPageText(index, "Preview"); } void createPage3() { } /** * Creates the pages of the multi-page editor. */ protected void createPages() { createTextEditor(); createPage1(); createPage2(); } /** * The MultiPageEditorPart implementation of this * IWorkbenchPart method disposes all nested editors. * Subclasses may extend. */ public void dispose() { ResourcesPlugin.getWorkspace().removeResourceChangeListener(this); super.dispose(); } /** * Saves the multi-page editor's document. */ public void doSave(IProgressMonitor monitor) { getEditor(0).doSave(monitor); } /** * Saves the multi-page editor's document as another file. Also updates the * text for page 0's tab, and updates this multi-page editor's input to * correspond to the nested editor's. */ public void doSaveAs() { IEditorPart editor = getEditor(0); editor.doSaveAs(); setPageText(0, editor.getTitle()); setInput(editor.getEditorInput()); } public void setInput(IEditorInput iei ) { super.setInput(iei); setPartName( iei.getName()); setContentDescription(iei.getToolTipText()); if ( iei instanceof IFileEditorInput ) { IFileEditorInput in = (IFileEditorInput) iei; IProject project = in.getFile().getProject(); setPartName(project.getName()); } } /* * (non-Javadoc) Method declared on IEditorPart */ public void gotoMarker(IMarker marker) { setActivePage(0); IDE.gotoMarker(getEditor(0), marker); } /** * The MultiPageEditorExample implementation of this method * checks that the input is an instance of IFileEditorInput. */ public void init(IEditorSite site, IEditorInput editorInput) throws PartInitException { if (!(editorInput instanceof IFileEditorInput)) throw new PartInitException( "Invalid Input: Must be IFileEditorInput"); super.init(site, editorInput); } /* * (non-Javadoc) Method declared on IEditorPart. */ public boolean isSaveAsAllowed() { return true; } /** * Calculates the contents of page 2 when the it is activated. */ protected void pageChange(int newPageIndex) { super.pageChange(newPageIndex); if (newPageIndex == 2) { sortWords(); } } /** * Closes all project files on project close. */ public void resourceChanged(final IResourceChangeEvent event) { if (event.getType() == IResourceChangeEvent.PRE_CLOSE) { Display.getDefault().asyncExec(new Runnable() { public void run() { IWorkbenchPage[] pages = getSite().getWorkbenchWindow() .getPages(); for (int i = 0; i < pages.length; i++) { if (((FileEditorInput) editor.getEditorInput()) .getFile().getProject().equals( event.getResource())) { IEditorPart editorPart = pages[i].findEditor(editor .getEditorInput()); pages[i].closeEditor(editorPart, true); } } } }); } } /** * Sorts the words in page 0, and shows them in page 2. */ void sortWords() { String editorText = editor.getDocumentProvider().getDocument( editor.getEditorInput()).get(); StringTokenizer tokenizer = new StringTokenizer(editorText, " \t\n\r\f!@#\u0024%^&*()-_=+`~[]{};:'\",.<>/?|\\"); ArrayList editorWords = new ArrayList(); while (tokenizer.hasMoreTokens()) { editorWords.add(tokenizer.nextToken()); } Collections.sort(editorWords, Collator.getInstance()); StringWriter displayText = new StringWriter(); for (int i = 0; i < editorWords.size(); i++) { displayText.write(((String) editorWords.get(i))); displayText.write(System.getProperty("line.separator")); } text.setText(displayText.toString()); } } bnd-1.50.0/biz.aQute.bnd/src/aQute/bnd/plugin/editors/BndTextEditor.java0000755000175000017500000000124611656076535025626 0ustar drazzibdrazzibpackage aQute.bnd.plugin.editors; import org.eclipse.ui.editors.text.*; public class BndTextEditor extends TextEditor { BndTextEditor() { setSourceViewerConfiguration(new BndSourceViewerConfiguration(getSharedColors())); } protected void createActions() { super.createActions(); // IAction contentAssistAction = new ContentAssistAction(null, "ContentAssistProposal.", this); //$NON-NLS-1$ // contentAssistAction.setActionDefinitionId(ITextEditorActionDefinitionIds.CONTENT_ASSIST_PROPOSALS); // setAction("ContentAssistProposal", contentAssistAction); // markAsStateDependentAction("ContentAssistProposal", true); } } bnd-1.50.0/biz.aQute.bnd/src/aQute/bnd/plugin/editors/BndMultiPageEditorContributor.java0000755000175000017500000000716711656076535031034 0ustar drazzibdrazzibpackage aQute.bnd.plugin.editors; import org.eclipse.jface.action.*; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.ui.IActionBars; import org.eclipse.ui.IEditorPart; import org.eclipse.ui.IWorkbenchActionConstants; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.actions.ActionFactory; import org.eclipse.ui.ide.IDE; import org.eclipse.ui.ide.IDEActionFactory; import org.eclipse.ui.part.MultiPageEditorActionBarContributor; import org.eclipse.ui.texteditor.ITextEditor; import org.eclipse.ui.texteditor.ITextEditorActionConstants; /** * Manages the installation/deinstallation of global actions for multi-page editors. * Responsible for the redirection of global actions to the active editor. * Multi-page contributor replaces the contributors for the individual editors in the multi-page editor. */ public class BndMultiPageEditorContributor extends MultiPageEditorActionBarContributor { private IEditorPart activeEditorPart; private Action sampleAction; /** * Creates a multi-page contributor. */ public BndMultiPageEditorContributor() { super(); createActions(); } /** * Returns the action registed with the given text editor. * @return IAction or null if editor is null. */ protected IAction getAction(ITextEditor editor, String actionID) { return (editor == null ? null : editor.getAction(actionID)); } /* (non-JavaDoc) * Method declared in AbstractMultiPageEditorActionBarContributor. */ public void setActivePage(IEditorPart part) { if (activeEditorPart == part) return; activeEditorPart = part; IActionBars actionBars = getActionBars(); if (actionBars != null) { ITextEditor editor = (part instanceof ITextEditor) ? (ITextEditor) part : null; actionBars.setGlobalActionHandler( ActionFactory.DELETE.getId(), getAction(editor, ITextEditorActionConstants.DELETE)); actionBars.setGlobalActionHandler( ActionFactory.UNDO.getId(), getAction(editor, ITextEditorActionConstants.UNDO)); actionBars.setGlobalActionHandler( ActionFactory.REDO.getId(), getAction(editor, ITextEditorActionConstants.REDO)); actionBars.setGlobalActionHandler( ActionFactory.CUT.getId(), getAction(editor, ITextEditorActionConstants.CUT)); actionBars.setGlobalActionHandler( ActionFactory.COPY.getId(), getAction(editor, ITextEditorActionConstants.COPY)); actionBars.setGlobalActionHandler( ActionFactory.PASTE.getId(), getAction(editor, ITextEditorActionConstants.PASTE)); actionBars.setGlobalActionHandler( ActionFactory.SELECT_ALL.getId(), getAction(editor, ITextEditorActionConstants.SELECT_ALL)); actionBars.setGlobalActionHandler( ActionFactory.FIND.getId(), getAction(editor, ITextEditorActionConstants.FIND)); actionBars.setGlobalActionHandler( IDEActionFactory.BOOKMARK.getId(), getAction(editor, IDEActionFactory.BOOKMARK.getId())); actionBars.updateActionBars(); } } private void createActions() { sampleAction = new Action() { public void run() { MessageDialog.openInformation(null, "aQute Bnd PRO", "Sample Action Executed"); } }; sampleAction.setText("Sample Action"); sampleAction.setToolTipText("Sample Action tool tip"); sampleAction.setImageDescriptor(PlatformUI.getWorkbench().getSharedImages(). getImageDescriptor(IDE.SharedImages.IMG_OBJS_TASK_TSK)); } public void contributeToMenu(IMenuManager manager) { IMenuManager menu = new MenuManager("Editor &Menu"); manager.prependToGroup(IWorkbenchActionConstants.MB_ADDITIONS, menu); menu.add(sampleAction); } public void contributeToToolBar(IToolBarManager manager) { manager.add(new Separator()); manager.add(sampleAction); } } bnd-1.50.0/biz.aQute.bnd/src/aQute/bnd/plugin/editors/BndHover.java0000644000175000017500000000626411656076535024620 0ustar drazzibdrazzibpackage aQute.bnd.plugin.editors; import org.eclipse.jface.text.*; import aQute.bnd.help.*; public class BndHover implements ITextHover { static class DocString implements CharSequence { IDocument doc; public char charAt(int index) { try { return doc.getChar(index); } catch (BadLocationException e) { throw new IndexOutOfBoundsException(); } } public int length() { return doc.getLength(); } public CharSequence subSequence(int start, int end) { return doc.get().subSequence(start, end); } }; public String getHoverInfo(ITextViewer textViewer, IRegion hoverRegion) { if (hoverRegion != null) { IDocument doc = textViewer.getDocument(); try { String key = doc.get(hoverRegion.getOffset(), hoverRegion .getLength()); Syntax syntax = Syntax.HELP.get(key); if (syntax == null) return null; StringBuilder sb = new StringBuilder(); sb.append(syntax.getLead()); sb.append("\nE.g. "); sb.append(syntax.getExample()); String text = sb.toString(); if (text == null) return null; if (text.length() > 30) { text = wrap(text, 30); } return text; } catch (Exception e) { return e + ""; } } return null; } public IRegion getHoverRegion(ITextViewer textViewer, int offset) { IDocument doc = textViewer.getDocument(); try { int start = offset; int end = offset; while (start >= 0 && isWordChar(doc.getChar(start))) start--; while (end < doc.getLength() && isWordChar(doc.getChar(end))) end++; start++; int length = Math.min(doc.getLength(), end - start); start = Math.max(0,start); return new Region(start, length); } catch (BadLocationException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } boolean isWordChar(char c) { return Character.isJavaIdentifierPart(c) || c == '-' || c == '.'; } String wrap(String text, int width) { StringBuilder sb = new StringBuilder(); int n = 0; int r = 0; while (r < text.length()) { char c = text.charAt(r++); switch (c) { case '\r': case '\n': if (n != 0) sb.append('\n'); n = 0; break; case ' ': case '\t': if (n > 20) { sb.append("\n"); n = 0; } else { sb.append(" "); n++; } break; default: sb.append(c); n++; } } return sb.toString(); } } bnd-1.50.0/biz.aQute.bnd/src/aQute/bnd/plugin/builder/0000755000175000017500000000000011656076535022213 5ustar drazzibdrazzibbnd-1.50.0/biz.aQute.bnd/src/aQute/bnd/plugin/builder/BndBuilder.java0000755000175000017500000000677111656076535025106 0ustar drazzibdrazzibpackage aQute.bnd.plugin.builder; import java.util.*; import org.eclipse.core.resources.*; import org.eclipse.core.runtime.*; import aQute.bnd.plugin.*; import aQute.bnd.plugin.popup.actions.*; import aQute.lib.osgi.*; public class BndBuilder extends IncrementalProjectBuilder { class DeltaVisitor implements IResourceDeltaVisitor { /* * (non-Javadoc) * * @see org.eclipse.core.resources.IResourceDeltaVisitor#visit(org.eclipse.core.resources.IResourceDelta) */ public boolean visit(IResourceDelta delta) throws CoreException { IResource resource = delta.getResource(); switch (delta.getKind()) { case IResourceDelta.ADDED: // handle added resource checkBnd(resource); break; case IResourceDelta.REMOVED: // handle removed resource break; case IResourceDelta.CHANGED: // handle changed resource checkBnd(resource); break; } // return true to continue visiting children. return true; } } class ResourceVisitor implements IResourceVisitor { public boolean visit(IResource resource) { checkBnd(resource); // return true to continue visiting children. return true; } } public static final String BUILDER_ID = "biz.aQute.bnd.BndBuilder"; private static final String MARKER_TYPE = "biz.aQute.bnd.xmlProblem"; private void addMarker(IFile file, String message, int lineNumber, int severity) { try { IMarker marker = file.createMarker(MARKER_TYPE); marker.setAttribute(IMarker.MESSAGE, message); marker.setAttribute(IMarker.SEVERITY, severity); if (lineNumber == -1) { lineNumber = 1; } marker.setAttribute(IMarker.LINE_NUMBER, lineNumber); } catch (CoreException e) { } } /* * (non-Javadoc) * * @see org.eclipse.core.internal.events.InternalBuilder#build(int, * java.util.Map, org.eclipse.core.runtime.IProgressMonitor) */ protected IProject[] build(int kind, Map args, IProgressMonitor monitor) throws CoreException { if (kind == FULL_BUILD) { fullBuild(monitor); } else { IResourceDelta delta = getDelta(getProject()); if (delta == null) { fullBuild(monitor); } else { incrementalBuild(delta, monitor); } } return null; } void checkBnd(IResource resource) { if (resource instanceof IFile && resource.getName().endsWith(".bnd")) { IFile file = (IFile) resource; deleteMarkers(file); try { Builder builder = MakeBundle.setBuilder(Activator.getDefault(), resource.getProject(), file.getLocation().toFile()); try { builder.build(); builder.close(); } catch (Exception e1) { addMarker(file, "Unexpected exception: " + e1, 1, Status.ERROR); } for (Iterator i = builder.getErrors().iterator(); i.hasNext();) { addMarker(file, i.next(), 1, Status.ERROR); } for (Iterator i = builder.getWarnings().iterator(); i.hasNext();) { addMarker(file, i.next(), 1, Status.WARNING); } } catch (Exception e) { addMarker(file, "Really bad exception: " + e, 1, Status.ERROR); } } } private void deleteMarkers(IFile file) { try { file.deleteMarkers(MARKER_TYPE, false, IResource.DEPTH_ZERO); } catch (CoreException ce) { } } protected void fullBuild(final IProgressMonitor monitor) throws CoreException { try { getProject().accept(new ResourceVisitor()); } catch (CoreException e) { } } protected void incrementalBuild(IResourceDelta delta, IProgressMonitor monitor) throws CoreException { // the visitor does the work. delta.accept(new DeltaVisitor()); } } bnd-1.50.0/biz.aQute.bnd/src/aQute/bnd/plugin/builder/ToggleNatureAction.java0000755000175000017500000000534211656076535026623 0ustar drazzibdrazzibpackage aQute.bnd.plugin.builder; import java.util.Iterator; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IProjectDescription; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IAdaptable; import org.eclipse.jface.action.IAction; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.ui.IObjectActionDelegate; import org.eclipse.ui.IWorkbenchPart; public class ToggleNatureAction implements IObjectActionDelegate { private ISelection selection; /* * (non-Javadoc) * * @see org.eclipse.ui.IActionDelegate#run(org.eclipse.jface.action.IAction) */ public void run(IAction action) { if (selection instanceof IStructuredSelection) { for (Iterator it = ((IStructuredSelection) selection).iterator(); it .hasNext();) { Object element = it.next(); IProject project = null; if (element instanceof IProject) { project = (IProject) element; } else if (element instanceof IAdaptable) { project = (IProject) ((IAdaptable) element) .getAdapter(IProject.class); } if (project != null) { toggleNature(project); } } } } /* * (non-Javadoc) * * @see org.eclipse.ui.IActionDelegate#selectionChanged(org.eclipse.jface.action.IAction, * org.eclipse.jface.viewers.ISelection) */ public void selectionChanged(IAction action, ISelection selection) { this.selection = selection; } /* * (non-Javadoc) * * @see org.eclipse.ui.IObjectActionDelegate#setActivePart(org.eclipse.jface.action.IAction, * org.eclipse.ui.IWorkbenchPart) */ public void setActivePart(IAction action, IWorkbenchPart targetPart) { } /** * Toggles sample nature on a project * * @param project * to have sample nature added or removed */ private void toggleNature(IProject project) { try { IProjectDescription description = project.getDescription(); String[] natures = description.getNatureIds(); for (int i = 0; i < natures.length; ++i) { if (BndNature.NATURE_ID.equals(natures[i])) { // Remove the nature String[] newNatures = new String[natures.length - 1]; System.arraycopy(natures, 0, newNatures, 0, i); System.arraycopy(natures, i + 1, newNatures, i, natures.length - i - 1); description.setNatureIds(newNatures); project.setDescription(description, null); return; } } // Add the nature String[] newNatures = new String[natures.length + 1]; System.arraycopy(natures, 0, newNatures, 0, natures.length); newNatures[natures.length] = BndNature.NATURE_ID; description.setNatureIds(newNatures); project.setDescription(description, null); } catch (CoreException e) { } } } bnd-1.50.0/biz.aQute.bnd/src/aQute/bnd/plugin/builder/BndNature.java0000755000175000017500000000422511656076535024746 0ustar drazzibdrazzibpackage aQute.bnd.plugin.builder; import org.eclipse.core.resources.ICommand; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IProjectDescription; import org.eclipse.core.resources.IProjectNature; import org.eclipse.core.runtime.CoreException; public class BndNature implements IProjectNature { /** * ID of this project nature */ public static final String NATURE_ID = "biz.aQute.bnd.BndNature"; private IProject project; /* * (non-Javadoc) * * @see org.eclipse.core.resources.IProjectNature#configure() */ public void configure() throws CoreException { IProjectDescription desc = project.getDescription(); ICommand[] commands = desc.getBuildSpec(); for (int i = 0; i < commands.length; ++i) { if (commands[i].getBuilderName().equals(BndBuilder.BUILDER_ID)) { return; } } ICommand[] newCommands = new ICommand[commands.length + 1]; System.arraycopy(commands, 0, newCommands, 0, commands.length); ICommand command = desc.newCommand(); command.setBuilderName(BndBuilder.BUILDER_ID); newCommands[newCommands.length - 1] = command; desc.setBuildSpec(newCommands); project.setDescription(desc, null); } /* * (non-Javadoc) * * @see org.eclipse.core.resources.IProjectNature#deconfigure() */ public void deconfigure() throws CoreException { IProjectDescription description = getProject().getDescription(); ICommand[] commands = description.getBuildSpec(); for (int i = 0; i < commands.length; ++i) { if (commands[i].getBuilderName().equals(BndBuilder.BUILDER_ID)) { ICommand[] newCommands = new ICommand[commands.length - 1]; System.arraycopy(commands, 0, newCommands, 0, i); System.arraycopy(commands, i + 1, newCommands, i, commands.length - i - 1); description.setBuildSpec(newCommands); return; } } } /* * (non-Javadoc) * * @see org.eclipse.core.resources.IProjectNature#getProject() */ public IProject getProject() { return project; } /* * (non-Javadoc) * * @see org.eclipse.core.resources.IProjectNature#setProject(org.eclipse.core.resources.IProject) */ public void setProject(IProject project) { this.project = project; } } bnd-1.50.0/biz.aQute.bnd/src/aQute/bnd/plugin/Activator.java0000755000175000017500000001450711656076535023376 0ustar drazzibdrazzibpackage aQute.bnd.plugin; import java.io.*; import java.util.*; import java.util.List; import org.eclipse.core.runtime.*; import org.eclipse.jface.dialogs.*; import org.eclipse.jface.resource.*; import org.eclipse.swt.widgets.*; import org.eclipse.ui.plugin.*; import org.osgi.framework.*; import aQute.bnd.build.*; import aQute.bnd.service.action.*; import aQute.lib.osgi.*; /** * The activator class controls the plug-in life cycle */ public class Activator extends AbstractUIPlugin { // The plug-in ID public static final String PLUGIN_ID = "aQute.bmaker"; // The shared instance private static Activator plugin; BundleContext context; Central central; /** * The constructor */ public Activator() { plugin = this; } /* * (non-Javadoc) * * @see org.eclipse.ui.plugin.AbstractUIPlugin#start(org.osgi.framework.BundleContext) */ public void start(BundleContext context) throws Exception { super.start(context); plugin = this; this.context = context; this.central = new Central(context); Hashtable p = new Hashtable(); // p.put(Action.ACTION_MENU, new String[] {"a:b", "a:c", "a:d", "a:d:e"}); context.registerService(Action.class.getName(), new ReflectAction(""), p); } /* * (non-Javadoc) * * @see org.eclipse.ui.plugin.AbstractUIPlugin#stop(org.osgi.framework.BundleContext) */ public void stop(BundleContext context) throws Exception { plugin = null; super.stop(context); central.close(); } /** * Returns the shared instance * * @return the shared instance */ public static Activator getDefault() { return plugin; } /** * Returns an image descriptor for the image file at the given plug-in * relative path * * @param path * the path * @return the image descriptor */ public static ImageDescriptor getImageDescriptor(String path) { return imageDescriptorFromPlugin(PLUGIN_ID, path); } static volatile boolean busy; public void error(final String msg, final Throwable t) { Status s = new Status(Status.ERROR, PLUGIN_ID, 0, msg, t); getLog().log(s); async(new Runnable() { public void run() { synchronized(this) { if ( busy ) return; busy = true; } Status s = new Status(Status.ERROR, PLUGIN_ID, 0, "", null); ErrorDialog.openError(null, "Errors during bundle generation", msg + " " + t.getMessage(), s); busy = false; } }); } public void info(String msg) { Status s = new Status(Status.INFO, PLUGIN_ID, 0, msg, null); getLog().log(s); } public void error(List errors) { final StringBuffer sb = new StringBuffer(); for (String msg : errors) { sb.append(msg); sb.append("\n"); } async(new Runnable() { public void run() { Status s = new Status(Status.ERROR, PLUGIN_ID, 0, "", null); ErrorDialog.openError(null, "Errors during bundle generation", sb.toString(), s); } }); } public void message(final String msg) { async(new Runnable() { public void run() { MessageDialog.openInformation(null, "Bnd", msg); } }); } public void warning(List errors) { final StringBuffer sb = new StringBuffer(); for (String msg : errors) { sb.append(msg); sb.append("\n"); } async(new Runnable() { public void run() { Status s = new Status(Status.WARNING, PLUGIN_ID, 0, "", null); ErrorDialog.openError(null, "Warnings during bundle generation", sb.toString(), s); } }); } void async(Runnable run) { if (Display.getCurrent() == null) { Display.getDefault().asyncExec(run); } else run.run(); } public boolean getReportDone() { return true; // return // getPreferenceStore().getBoolean(PreferenceConstants.P_REPORT_DONE); } public File getCopy() { return null; // String path = // getPreferenceStore().getString(PreferenceConstants.P_COPY); // if ( path == null ) // return null; // File file = new File(path); // if ( !file.exists() || file.isFile() ) // return null; // return file; } public boolean isPedantic() { return false; // IPreferenceStore store = getPreferenceStore(); // return store.getBoolean(PreferenceConstants.P_PEDANTIC); } public BundleContext getBundleContext() { return context; } public void report(boolean warnings, boolean acknowledge , Processor reporter, final String title, final String extra ) { if (reporter.getErrors().size() > 0 || (warnings && reporter.getWarnings().size() > 0)) { final StringBuffer sb = new StringBuffer(); sb.append("\n"); if (reporter.getErrors().size() > 0) { sb.append("[Errors]\n"); for (String msg : reporter.getErrors()) { sb.append(msg); sb.append("\n"); } } sb.append("\n"); if (reporter.getWarnings().size() > 0) { sb.append("[Warnings]\n"); for (String msg : reporter.getWarnings()) { sb.append(msg); sb.append("\n"); } } final Status s = new Status(Status.ERROR, PLUGIN_ID, 0, sb.toString(), null); reporter.clear(); async(new Runnable() { public void run() { ErrorDialog.openError(null, title, title + "\n" + extra, s); } }); } else { message(title+ " : ok"); } } public Central getCentral() { return central; } } bnd-1.50.0/biz.aQute.bnd/src/aQute/bnd/plugin/Central.java0000644000175000017500000002321111656076535023017 0ustar drazzibdrazzibpackage aQute.bnd.plugin; import java.io.File; import java.util.*; import java.util.concurrent.*; import org.eclipse.core.internal.resources.*; import org.eclipse.core.resources.*; import org.eclipse.core.runtime.*; import org.eclipse.jdt.core.*; import org.osgi.framework.*; import aQute.bnd.build.Project; import aQute.bnd.build.Workspace; import aQute.bnd.classpath.*; import aQute.bnd.service.*; public class Central implements IResourceChangeListener { static IWorkspace iworkspace; final Map javaProjectToModel = new HashMap(); final List listeners = new CopyOnWriteArrayList(); static Workspace workspace; final BundleContext context; final Workspace ws; Central(BundleContext context) throws Exception { this.context = context; // Add a resource change listener if this is // the first project iworkspace = ResourcesPlugin.getWorkspace(); iworkspace.addResourceChangeListener(this); ws = getWorkspace(); context.registerService(Workspace.class.getName(), ws, null); } public Project getModel(IJavaProject project) { try { Project model = javaProjectToModel.get(project); if (model == null) { File projectDir = project.getProject().getLocation() .makeAbsolute().toFile(); model = Workspace.getProject(projectDir); if (workspace == null) { model.getWorkspace(); } if (model != null) { javaProjectToModel.put(project, model); } } return model; } catch (Exception e) { // TODO do something more useful here throw new RuntimeException(e); } } /** * Implementation of the resource changed interface. We are checking in the * POST_CHANGE phase if one of our tracked models needs to be updated. */ public synchronized void resourceChanged(IResourceChangeEvent event) { if (event.getType() != IResourceChangeEvent.POST_CHANGE) return; long now = System.currentTimeMillis(); IResourceDelta rootDelta = event.getDelta(); try { final Set changed = new HashSet(); rootDelta.accept(new IResourceDeltaVisitor() { public boolean visit(IResourceDelta delta) throws CoreException { try { IPath location = delta.getResource().getLocation(); if (location == null) { System.out .println("Cannot convert resource to file: " + delta.getResource()); } else { File file = location.toFile(); File parent = file.getParentFile(); boolean parentIsWorkspace = parent .equals(getWorkspace().getBase()); // file // /development/osgi/svn/build/org.osgi.test.cases.distribution/bnd.bnd // parent // /development/osgi/svn/build/org.osgi.test.cases.distribution // workspace /development/amf/workspaces/osgi // false if (parent != null && parentIsWorkspace) { // We now are on project level, we do not go // deeper // because projects/workspaces should check for // any // changes. // We are careful not to create unnecessary // projects // here. if (file.getName().equals(Workspace.CNFDIR)) { if (workspace.refresh()) { changed.addAll(workspace .getCurrentProjects()); } return false; } if (workspace.isPresent(file.getName())) { Project project = workspace.getProject(file .getName()); changed.add(project); } else { ; // Project not created yet, so we // have // no cached results } return false; } } return true; } catch (Exception e) { e.printStackTrace(); throw new CoreException(new Status(Status.ERROR, Activator.PLUGIN_ID, "During checking project changes", e)); } } }); for (Project p : changed) { //p.updateModified(now, "Eclipse resource listener"); p.refresh(); changed(p); } } catch (CoreException e) { Activator.getDefault().error("While handling changes", e); // TODO Auto-generated catch block e.printStackTrace(); } } public static Workspace getWorkspace() throws Exception { if (workspace != null) return workspace; IResource resource = iworkspace.getRoot().findMember("/cnf/build.bnd"); if (resource != null) { IPath path = resource.getLocation(); if (path != null) { File f = path.toFile(); workspace = Workspace.getWorkspace(f.getAbsoluteFile() .getParentFile().getParentFile().getAbsoluteFile()); // workspace.setBundleContex(context); return workspace; } } workspace = Workspace.getWorkspace(iworkspace.getRoot().getLocation() .toFile()); return workspace; } public void changed(Project model) { model.setChanged(); for (ModelListener m : listeners) try { m.modelChanged(model); } catch (Exception e) { e.printStackTrace(); } } public void addModelListener(ModelListener m) { if (!listeners.contains(m)) { listeners.add(m); } } public void removeModelListener(ModelListener m) { listeners.remove(m); } public IJavaProject getJavaProject(Project model) { for (IProject iproj : iworkspace.getRoot().getProjects()) { if (iproj.getName().equals(model.getName())) { IJavaProject ij = JavaCore.create(iproj); if (ij != null && ij.exists()) { return ij; } // current project is not a Java project } } return null; } public static IPath toPath(Project project, File file) { String path = file.getAbsolutePath(); String workspace = project.getWorkspace().getBase().getAbsolutePath(); if (path.startsWith(workspace)) path = path.substring(workspace.length()); else return null; IPath p = new Path(path); return p; } public static void refresh(IPath path) { try { IResource r = ResourcesPlugin.getWorkspace().getRoot().findMember( path); if (r != null) return; IPath p = (IPath) path.clone(); while (p.segmentCount() > 0) { p = p.removeLastSegments(1); IResource resource = ResourcesPlugin.getWorkspace().getRoot() .findMember(p); if (resource != null) { resource.refreshLocal(2, null); return; } } } catch( ResourceException re ) { // TODO Ignore for now } catch (Exception e) { Activator.getDefault().error("While refreshing path " + path, e); } } public void refreshPlugins() throws Exception { List rps = getWorkspace().getPlugins(Refreshable.class); for (Refreshable rp : rps) { if (rp.refresh()) { File dir = rp.getRoot(); refreshFile(dir); } } } public void refreshFile(File f) throws Exception { String path = toLocal(f); IResource r = ResourcesPlugin.getWorkspace().getRoot().findMember(path); if (r != null) { r.refreshLocal(IResource.DEPTH_INFINITE, null); } } public void refresh(Project p) throws Exception { IJavaProject jp = getJavaProject(p); if (jp != null) jp.getProject().refreshLocal(IResource.DEPTH_INFINITE, null); } private String toLocal(File f) throws Exception { String root = getWorkspace().getBase().getAbsolutePath(); String path = f.getAbsolutePath().substring(root.length()); return path; } public void close() { } } bnd-1.50.0/biz.aQute.bnd/src/aQute/bnd/plugin/ActionWrapper.java0000644000175000017500000000132611656076535024210 0ustar drazzibdrazzibpackage aQute.bnd.plugin; import org.osgi.framework.*; import aQute.bnd.build.*; import aQute.bnd.service.action.*; public class ActionWrapper implements Action { ServiceReference ref; BundleContext context; public ActionWrapper(BundleContext context, ServiceReference ref) { this.ref = ref; this.context = context; } public void execute(Project project, String action) throws Exception { Action a = (Action) context.getService(ref); if ( a == null ) throw new IllegalStateException("Command provider is gone"); try { a.execute(project, action); } finally { context.ungetService(ref); } } } bnd-1.50.0/biz.aQute.bnd/src/aQute/bnd/plugin/popup/0000755000175000017500000000000011656076535021730 5ustar drazzibdrazzibbnd-1.50.0/biz.aQute.bnd/src/aQute/bnd/plugin/popup/Scripts.java0000644000175000017500000000732611656076535024232 0ustar drazzibdrazzibpackage aQute.bnd.plugin.popup; import java.io.File; import java.util.ArrayList; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IResource; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Status; import org.eclipse.core.runtime.jobs.Job; import org.eclipse.jdt.core.IJavaProject; import org.eclipse.jdt.core.JavaCore; import org.eclipse.jface.action.IContributionItem; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.ui.ISelectionService; import org.eclipse.ui.actions.CompoundContributionItem; import aQute.bnd.build.Project; import aQute.bnd.plugin.Activator; public class Scripts extends CompoundContributionItem { final List projects = new ArrayList(); public Scripts() { ISelectionService is = Activator.getDefault().getWorkbench().getActiveWorkbenchWindow() .getSelectionService(); ISelection s = is.getSelection(); if (s != null && s instanceof IStructuredSelection) { IStructuredSelection ss = (IStructuredSelection) s; for (Iterator i = ss.iterator(); i.hasNext();) { Object oo = i.next(); IJavaProject jp = null; if (oo instanceof IResource) { IResource r = (IResource) oo; IProject iproject = r.getProject(); jp = JavaCore.create(iproject); } else if (oo instanceof IJavaProject) { jp = (IJavaProject) oo; } if (jp != null) { if (!jp.getProject().isAccessible()) { continue; } Project project = Activator.getDefault().getCentral().getModel(jp); if (project != null) { File bndFile = project.getFile("bnd.bnd"); if (!bndFile.exists()) { continue; } projects.add(project); } } } } } public Scripts(String id) { super(id); } @Override protected IContributionItem[] getContributionItems() { if (projects.isEmpty()) return new IContributionItem[0]; Set titles = new HashSet(); boolean first = true; for (Project project : projects) { if (first) { titles.addAll(project.getActions().keySet()); first = false; } else { titles.retainAll(project.getActions().keySet()); } } SubMenu root = new SubMenu("root"); SubMenu sub = new SubMenu("Bnd"); root.add(sub); for (final String title : titles) { sub.add(this, title, title); } return root.getItems(); } void exec(final String label) { Job job = new Job(label) { protected IStatus run(IProgressMonitor monitor) { for (Project project : projects) { if (monitor != null) { if (monitor.isCanceled()) break; monitor.subTask("" + project + " " + label); } Map actions = project.getActions(); aQute.bnd.service.action.Action cmd = actions.get(label); try { project.action(label); monitor.worked(1); Activator.getDefault().getCentral().refresh(project); if (!project.isPerfect()) { // We had errors or warnings Activator.getDefault().report(true, true, project, "During execution of " + label, ""); return Status.CANCEL_STATUS; } } catch (Throwable e) { Activator.getDefault().error("While executing action: " + cmd, e); } } try { Activator.getDefault().getCentral().refreshPlugins(); return Status.OK_STATUS; } catch (Exception e) { return new Status(IStatus.ERROR, Activator.PLUGIN_ID, "Failed to refresh: " + e); } } }; job.setPriority(Job.SHORT); job.schedule(); // start as soon as possible } } bnd-1.50.0/biz.aQute.bnd/src/aQute/bnd/plugin/popup/SubMenu.java0000644000175000017500000000435011656076535024153 0ustar drazzibdrazzibpackage aQute.bnd.plugin.popup; import java.util.*; import org.eclipse.jface.action.*; public class SubMenu extends MenuManager { Map items = new LinkedHashMap(); SubMenu(String name) { super(name); } @Override public IContributionItem[] getItems() { return items.values().toArray(new IContributionItem[items.size()]); } void add(final Scripts script, final String s, final String full) { int n = s.indexOf(':'); if (n < 0) { n = s.indexOf(">"); if (n < 0) { items.put(s, new ActionContributionItem(new Action() { { setText(s); } public void run() { script.exec(full); } })); } else { String name = s.substring(0,n); String remainder = s.substring(n+1); IContributionItem ici = items.get(name); if (ici == null) { ici = new SubMenu(name); items.put(name, ici); } if (!(ici instanceof SubMenu)) { // A leaf & node ... :-( } else { SubMenu sub = (SubMenu) ici; String parts[] = remainder.split(","); for ( String part : parts ) { sub.add(script, part, full); } } } } else { String name = s.substring(0, n); IContributionItem ici = items.get(name); if (ici == null) { ici = new SubMenu(name); items.put(name, ici); } if (!(ici instanceof SubMenu)) { // A leaf & node ... :-( } else { SubMenu sub = (SubMenu) ici; sub.add(script, s.substring(n + 1), full); } } } void add(SubMenu subMenu) { IContributionItem ici = items.get(subMenu.getMenuText()); if (ici == null) { items.put(subMenu.getMenuText(), subMenu); } } } bnd-1.50.0/biz.aQute.bnd/src/aQute/bnd/plugin/popup/actions/0000755000175000017500000000000011656076535023370 5ustar drazzibdrazzibbnd-1.50.0/biz.aQute.bnd/src/aQute/bnd/plugin/popup/actions/VerifyBundle.java0000755000175000017500000000554411656076535026644 0ustar drazzibdrazzibpackage aQute.bnd.plugin.popup.actions; import java.io.File; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.eclipse.core.resources.IFile; import org.eclipse.jface.action.IAction; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.StructuredSelection; import org.eclipse.ui.IActionDelegate; import org.eclipse.ui.IObjectActionDelegate; import org.eclipse.ui.IWorkbenchPart; import aQute.bnd.plugin.Activator; import aQute.lib.osgi.Jar; import aQute.lib.osgi.Verifier; public class VerifyBundle implements IObjectActionDelegate { IFile[] locations; public VerifyBundle() { } /** * @see IActionDelegate#run(IAction) */ public void run(IAction action) { try { if (locations != null) { for (int i = 0; i < locations.length; i++) { File mf = locations[i].getLocation().toFile(); try { Jar jar = new Jar(mf.getName(), mf); Verifier verifier = new Verifier(jar); try { verifier.verify(); if (verifier.getErrors().size() + verifier.getWarnings().size() > 0) { List info = new ArrayList(verifier.getErrors()); info.addAll(verifier.getWarnings()); Activator.getDefault().error(info); } } finally { jar.close(); verifier.close(); } } catch (Exception e) { Activator.getDefault().error( "While verifying JAR " + locations[i], e); } locations[i].getParent().refreshLocal(1, null); } } } catch (Exception e) { Activator.getDefault().error("Could not start verification", e); } } /** * @see IActionDelegate#selectionChanged(IAction, ISelection) */ public void selectionChanged(IAction action, ISelection selection) { locations = getLocations(selection); } @SuppressWarnings("unchecked") IFile[] getLocations(ISelection selection) { if (selection != null && (selection instanceof StructuredSelection)) { StructuredSelection ss = (StructuredSelection) selection; IFile[] result = new IFile[ss.size()]; int n = 0; for (Iterator i = ss.iterator(); i.hasNext();) { result[n++] = i.next(); } return result; } return null; } public void setActivePart(IAction action, IWorkbenchPart targetPart) { } } bnd-1.50.0/biz.aQute.bnd/src/aQute/bnd/plugin/popup/actions/AddToRepo.java0000644000175000017500000000715611656076535026065 0ustar drazzibdrazzibpackage aQute.bnd.plugin.popup.actions; import java.io.*; import java.util.*; import org.eclipse.core.resources.*; import org.eclipse.jface.action.*; import org.eclipse.jface.viewers.*; import org.eclipse.ui.*; import aQute.bnd.build.*; import aQute.bnd.plugin.*; import aQute.bnd.plugin.popup.actions.repo.*; import aQute.bnd.service.*; import aQute.lib.osgi.*; public class AddToRepo implements IObjectActionDelegate { IFile[] locations; public AddToRepo() { } /** * @see IActionDelegate#run(IAction) */ public void run(IAction action) { try { if (locations != null) { for (int i = 0; i < locations.length; i++) { File mf = locations[i].getLocation().toFile(); try { Jar jar = new Jar(mf.getName(), mf); try { Verifier verifier = new Verifier(jar); verifier.verify(); if (verifier.getErrors().size() + verifier.getWarnings().size() > 0) { List info = new ArrayList( verifier.getErrors()); info.addAll(verifier.getWarnings()); Activator.getDefault().error(info); } else { Workspace ws = Central.getWorkspace(); List repos = ws .getPlugins(RepositoryPlugin.class); RepoDialog d = new RepoDialog(null, jar, repos); d.setBlockOnOpen(true); if (d.open() == 0) try { RepositoryPlugin repo = d .getRepository(); repo.put(jar); // Central.refresh(Path.fromOSString(f // .getAbsolutePath())); } finally { d.close(); } } } finally { jar.close(); } } catch (Exception e) { Activator.getDefault().error( "While verifying JAR " + locations[i], e); } locations[i].getParent().refreshLocal(1, null); } } } catch (Exception e) { Activator.getDefault().error("Could not start verification", e); } } /** * @see IActionDelegate#selectionChanged(IAction, ISelection) */ public void selectionChanged(IAction action, ISelection selection) { locations = getLocations(selection); } @SuppressWarnings("unchecked") IFile[] getLocations(ISelection selection) { if (selection != null && (selection instanceof StructuredSelection)) { StructuredSelection ss = (StructuredSelection) selection; IFile[] result = new IFile[ss.size()]; int n = 0; for (Iterator i = ss.iterator(); i.hasNext();) { result[n++] = i.next(); } return result; } return null; } public void setActivePart(IAction action, IWorkbenchPart targetPart) { } } bnd-1.50.0/biz.aQute.bnd/src/aQute/bnd/plugin/popup/actions/InstallBundle.java0000644000175000017500000000671711656076535027006 0ustar drazzibdrazzibpackage aQute.bnd.plugin.popup.actions; import java.io.*; import java.util.*; import org.eclipse.core.resources.*; import org.eclipse.jface.action.*; import org.eclipse.jface.viewers.*; import org.eclipse.ui.*; import org.osgi.framework.*; import org.osgi.service.packageadmin.*; import aQute.bnd.plugin.*; public class InstallBundle implements IObjectActionDelegate { IFile[] locations; public InstallBundle() { } /** * @see IActionDelegate#run(IAction) */ public void run(IAction action) { Activator activator = Activator.getDefault(); Map map = new HashMap(); BundleContext context = activator.getBundle().getBundleContext(); Bundle bundles[] = context.getBundles(); for (int i = 0; i < bundles.length; i++) { map.put(bundles[i].getLocation(), bundles[i]); } if (locations != null) { List installed = new ArrayList(); List updated = new ArrayList(); int errors = 0; for (int i = 0; i < locations.length; i++) { try { File mf = locations[i].getLocation().toFile(); String url = mf.toURI().toURL().toExternalForm(); Bundle b = (Bundle) map.get(url); if (b != null) { b.update(); updated.add(b); } else { b = context.installBundle(url); installed.add(b); } } catch (Exception e) { errors++; Activator.getDefault() .error("Error during install/update ", e); } } if ( !updated.isEmpty()) { ServiceReference ref = context.getServiceReference(PackageAdmin.class.getName()); if ( ref != null ) { PackageAdmin packageAdmin = (PackageAdmin) context.getService(ref); if ( packageAdmin != null ) { packageAdmin.refreshPackages((Bundle[])updated.toArray(new Bundle[updated.size()])); } else activator.error("Can't get Package Admin service to refresh", null); } else activator.error("No Package Admin to refresh", null); } StringBuffer sb = new StringBuffer(); printBundles("Installed Bundles", installed, sb); printBundles("Updated Bundles", updated, sb); switch(errors) { case 0: break; case 1: sb.append("One Error\n"); break; default: sb.append(errors); sb.append(" Errors\n"); } activator.message(sb.toString()); } } private void printBundles(String msg, List list, StringBuffer sb) { if ( list.isEmpty() ) return; sb.append(msg); sb.append('\n'); for ( Bundle b : list ) { String version = (String) b.getHeaders().get("Bundle-Version"); if ( version == null ) version = "0.0.0"; String name = b.getSymbolicName(); if ( name == null ) name = b.getLocation(); sb.append(" "); sb.append(name); for ( int p = name.length(); p<20; p++ ) sb.append(" "); sb.append("- "); sb.append(version); sb.append("\n"); } } /** * @see IActionDelegate#selectionChanged(IAction, ISelection) */ public void selectionChanged(IAction action, ISelection selection) { locations = getLocations(selection); } @SuppressWarnings("unchecked") IFile[] getLocations(ISelection selection) { if (selection != null && (selection instanceof StructuredSelection)) { StructuredSelection ss = (StructuredSelection) selection; IFile[] result = new IFile[ss.size()]; int n = 0; for (Iterator i = ss.iterator(); i.hasNext();) { result[n++] = (IFile) i.next(); } return result; } return null; } public void setActivePart(IAction action, IWorkbenchPart targetPart) { } } bnd-1.50.0/biz.aQute.bnd/src/aQute/bnd/plugin/popup/actions/repo/0000755000175000017500000000000011656076535024335 5ustar drazzibdrazzibbnd-1.50.0/biz.aQute.bnd/src/aQute/bnd/plugin/popup/actions/repo/RepoDialog.java0000644000175000017500000001151011656076535027223 0ustar drazzibdrazzibpackage aQute.bnd.plugin.popup.actions.repo; import java.util.*; import org.eclipse.jface.dialogs.*; import org.eclipse.jface.dialogs.Dialog; import org.eclipse.swt.*; import org.eclipse.swt.events.*; import org.eclipse.swt.graphics.*; import org.eclipse.swt.widgets.*; import aQute.bnd.service.*; import aQute.lib.osgi.*; public class RepoDialog extends Dialog { private Text bsn; private Text version; private Label lblRepository; private Combo repositories; private java.util.List repos; private Jar jar; private Label lblBundleDescription; private Text description; private RepositoryPlugin selected; /** * Create the dialog. * * @param parentShell */ public RepoDialog(Shell parentShell, Jar jar, java.util.List repos) { super(parentShell); setShellStyle(SWT.DIALOG_TRIM); this.repos = repos; this.jar = jar; } /** * Create contents of the dialog. * * @param parent */ @Override protected Control createDialogArea(Composite parent) { Composite container = (Composite) super.createDialogArea(parent); container.setLayout(null); { lblRepository = new Label(container, SWT.NONE); lblRepository.setBounds(8, 8, 160, 24); lblRepository.setText("Repository"); } { repositories = new Combo(container, SWT.READ_ONLY); repositories.setBounds(168, 3, 272, 30); repositories.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { selected = repos.get(repositories.getSelectionIndex()); } }); } { bsn = new Text(container, SWT.BORDER); bsn.setEditable(false); bsn.setBounds(168, 39, 272, 28); } { version = new Text(container, SWT.BORDER); version.setEditable(false); version.setBounds(168, 67, 272, 28); } { Label lblBundleSymbolicName = new Label(container, SWT.NONE); lblBundleSymbolicName.setBounds(8, 40, 160, 24); lblBundleSymbolicName.setText("Bundle Symbolic Name"); } { Label lblVersion = new Label(container, SWT.NONE); lblVersion.setBounds(8, 72, 160, 24); lblVersion.setText("Bundle Version"); } { lblBundleDescription = new Label(container, SWT.NONE); lblBundleDescription.setBounds(8, 105, 160, 24); lblBundleDescription.setText("Bundle Description"); } { description = new Text(container, SWT.BORDER | SWT.V_SCROLL | SWT.MULTI); description.setEditable(false); description.setBounds(168, 101, 272, 117); } setup(); return container; } private void setup() { try { bsn.setText(jar.getManifest().getMainAttributes().getValue( Constants.BUNDLE_SYMBOLICNAME)); String v = jar.getManifest().getMainAttributes().getValue( Constants.BUNDLE_VERSION); if (v == null) v = "0.0.0"; version.setText(v); v = jar.getManifest().getMainAttributes().getValue( Constants.BUNDLE_DESCRIPTION); if (v == null) v = ""; description.setText(v); for (Iterator i = repos.iterator(); i.hasNext();) { RepositoryPlugin plugin = i.next(); if (plugin.canWrite()) repositories.add(plugin.getName()); else i.remove(); } repositories.select(0); selected = repos.get(0); } catch (Exception e) { e.printStackTrace(); } } /** * Create contents of the button bar. * * @param parent */ @Override protected void createButtonsForButtonBar(Composite parent) { Button button = createButton(parent, IDialogConstants.OK_ID, IDialogConstants.OK_LABEL, true); button.setText("Deploy"); createButton(parent, IDialogConstants.CANCEL_ID, IDialogConstants.CANCEL_LABEL, false); } /** * Return the initial size of the dialog. */ @Override protected Point getInitialSize() { return new Point(450, 300); } public RepositoryPlugin getRepository() { return selected; } } bnd-1.50.0/biz.aQute.bnd/src/aQute/bnd/plugin/popup/actions/MakeBundle.java0000755000175000017500000001510411656076535026246 0ustar drazzibdrazzibpackage aQute.bnd.plugin.popup.actions; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.util.Iterator; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IProject; import org.eclipse.jface.action.IAction; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.StructuredSelection; import org.eclipse.ui.IActionDelegate; import org.eclipse.ui.IObjectActionDelegate; import org.eclipse.ui.IWorkbenchPart; import aQute.bnd.build.Project; import aQute.bnd.build.Workspace; import aQute.bnd.plugin.Activator; import aQute.lib.osgi.Builder; import aQute.lib.osgi.Jar; import aQute.lib.osgi.eclipse.EclipseClasspath; public class MakeBundle implements IObjectActionDelegate { IFile[] locations; public MakeBundle() { } /** * @see IActionDelegate#run(IAction) */ public void run(IAction action) { Activator activator = Activator.getDefault(); try { if (locations != null) { for (int i = 0; i < locations.length; i++) { try { File mf = locations[i].getLocation().toFile(); if (mf.getName().equals(Project.BNDFILE)) { Project project = Workspace.getProject(mf .getParentFile()); File[] files = project.build(); String target = ""; if ( files != null ) { for ( File f : files ) { target += f + " "; } } activator.report(true, true, project, "Building " + project, "Created files " + target ); } else { Builder builder = setBuilder(activator, locations[i].getProject(), mf); File cwd = mf.getAbsoluteFile().getParentFile(); File target; builder.build(); String name = builder.getBsn() + ".jar"; Jar jar = builder.getJar(); String path = builder.getProperty("-output"); if (path == null) { target = new File(cwd, name); } else { target = new File(path); if (!target.isAbsolute()) target = new File(cwd, path); if (target.isDirectory()) { target = new File(target, name); } } target.delete(); if (builder.getErrors().size() > 0) { activator.error(builder.getErrors()); } else { jar.write(target); File copy = activator.getCopy(); if (copy != null) { copy = new File(copy, target.getName()); jar.write(copy); } if (builder.getWarnings().size() > 0) { activator.warning(builder.getWarnings()); } else { if (activator.getReportDone()) { String p = target.getPath(); if (p.startsWith(cwd.getAbsolutePath())) p = p .substring(cwd .getAbsolutePath() .length() + 1); String msg = "Saved as " + p; if (copy != null) msg += " and copied to " + copy; activator.message(msg); } } } builder.close(); } } catch (Exception e) { e.printStackTrace(); activator.error("While generating JAR " + locations[i], e); } locations[i].getParent().refreshLocal(1, null); } } } catch (Exception e) { activator.error("Error in bnd", e); } } static public Builder setBuilder(Activator activator, IProject project, File mf) throws Exception, IOException, FileNotFoundException { Builder builder = new Builder(); builder.setPedantic(activator.isPedantic() || activator.isDebugging()); // TODO of course we should get the classpath from // inside API ... File p = project.getLocation().toFile(); // TODO for now we ignore the workspace and use the // project parent directory EclipseClasspath ecp = new EclipseClasspath(builder, p.getParentFile(), p); builder.setClasspath((File[]) ecp.getClasspath().toArray(new File[0])); builder .setSourcepath((File[]) ecp.getSourcepath() .toArray(new File[0])); builder.setProperties(mf); return builder; } /** * @see IActionDelegate#selectionChanged(IAction, ISelection) */ public void selectionChanged(IAction action, ISelection selection) { locations = getLocations(selection); } @SuppressWarnings("unchecked") IFile[] getLocations(ISelection selection) { if (selection != null && (selection instanceof StructuredSelection)) { StructuredSelection ss = (StructuredSelection) selection; IFile[] result = new IFile[ss.size()]; int n = 0; for (Iterator i = ss.iterator(); i.hasNext();) { result[n++] = i.next(); } return result; } return null; } public void setActivePart(IAction action, IWorkbenchPart targetPart) { } } bnd-1.50.0/biz.aQute.bnd/src/aQute/bnd/plugin/popup/actions/WrapBundle.java0000755000175000017500000000262111656076535026302 0ustar drazzibdrazzibpackage aQute.bnd.plugin.popup.actions; import java.util.*; import org.eclipse.core.resources.*; import org.eclipse.jface.action.*; import org.eclipse.jface.dialogs.*; import org.eclipse.jface.viewers.*; import org.eclipse.ui.*; import aQute.bnd.plugin.*; public class WrapBundle implements IObjectActionDelegate { IFile[] locations; public WrapBundle(){} /** * @see IActionDelegate#run(IAction) */ public void run(IAction action) { try { if ( locations!= null) { for (int i = 0; i < locations.length; i++) { // TODO MessageDialog.openInformation(null,"Not Implemented Yet", "TODO implement wrapping"); } } } catch( Exception e ) { Activator.getDefault().error("Could not start Test View", e ); } } /** * @see IActionDelegate#selectionChanged(IAction, ISelection) */ public void selectionChanged(IAction action, ISelection selection) { locations = getLocations(selection); } @SuppressWarnings("unchecked") IFile[] getLocations(ISelection selection) { if (selection != null && (selection instanceof StructuredSelection)) { StructuredSelection ss = (StructuredSelection) selection; IFile[] result = new IFile[ss.size()]; int n = 0; for (Iterator i = ss.iterator(); i.hasNext();) { result[n++] = i.next(); } return result; } return null; } public void setActivePart(IAction action, IWorkbenchPart targetPart) { } } bnd-1.50.0/biz.aQute.bnd/src/aQute/bnd/ant/0000755000175000017500000000000011656076535020051 5ustar drazzibdrazzibbnd-1.50.0/biz.aQute.bnd/src/aQute/bnd/ant/PrepareTask.java0000644000175000017500000000512111656076535023134 0ustar drazzibdrazzibpackage aQute.bnd.ant; /** * The idea of this task is to read all the properties as if bnd has read them. * This makes it easier to use bnd standalone on the same data. */ import java.io.*; import java.util.*; import org.apache.tools.ant.*; import aQute.bnd.build.*; import aQute.bnd.build.Project; public class PrepareTask extends BaseTask { File basedir; boolean print = false; String top; public void execute() throws BuildException { try { if (basedir == null || !basedir.isDirectory()) throw new BuildException("The given base dir does not exist " + basedir); Project project = Workspace.getProject(basedir); project.setProperty("in.ant", "true"); project.setProperty("environment", "ant"); // Check if we are in a sub build, in that case // top will be set to the target directory at the // top project. if ( top!=null && top.length()>0 && !top.startsWith("$")) project.setProperty("top", top); project.setExceptions(true); Properties properties = project.getFlattenedProperties(); if (report() || report(project)) throw new BuildException( "Errors during Eclipse Path inspection"); copyProperties(properties); } catch (Exception e) { e.printStackTrace(); throw new BuildException(e); } } private void copyProperties(Properties flattened) { for (Enumeration k = flattened.propertyNames(); k.hasMoreElements();) { String key = (String) k.nextElement(); String value = flattened.getProperty(key); if (isPrint()) System.out.printf("%-20s = %s\n", key, value); // We override existing values. getProject().setProperty(key, value.trim()); } } public boolean isPrint() { return print; } /** * Print out the properties when they are set in sorted order * * @param print */ public void setPrint(boolean print) { this.print = print; } /** * Set the base directory of the project. This property MUST be set. * * @param basedir */ public void setBasedir(File basedir) { this.basedir = basedir; } /** * Set the base directory of the project. This property MUST be set. * * @param basedir */ public void setTop(String top) { this.top = top; } } bnd-1.50.0/biz.aQute.bnd/src/aQute/bnd/ant/BndTask.java0000755000175000017500000002377111656076535022257 0ustar drazzibdrazzibpackage aQute.bnd.ant; import java.io.*; import java.util.*; import org.apache.tools.ant.*; import org.apache.tools.ant.types.*; import aQute.bnd.build.*; import aQute.bnd.build.Project; import aQute.lib.osgi.*; import aQute.lib.osgi.eclipse.*; import aQute.libg.qtokens.*; /** * This file is the bnd main task for ant. * * Example usage * *
 * 
 *    
 *    
 *      
 *        
 *        
 *          
 *        
 *      
 *      
 *        
 *          
 *        
 *      
 *      
 *        
 *          
 *        
 *      
 * 
 *      
 *      
 * 
 * 
 * 
 * 	    
 * 		  
 * 		    
 * 		      
 * 			    
 *      	  	 	
 * 		  
 * 		  
 * 		    
 * 		      
 * 		    				
 * 		  
 *       
 *    
 *  
 * 
* */ public class BndTask extends BaseTask { String command; File basedir; boolean failok; boolean exceptions; boolean print; // flags aiming to know how classpath & bnd descriptors were set private boolean classpathDirectlySet; private Path classpathReference; private Path bndfilePath; public void execute() throws BuildException { // JME add - ensure every required parameter is present // handle cases where mutual exclusion live.. // this is the ANT tradition .. validate(); updateClasspath(); updateBndFiles(); if (command == null) { executeBackwardCompatible(); return; } if (basedir == null) throw new BuildException("No basedir set"); try { Project project = Workspace.getProject(basedir); project.setProperty("in.ant", "true"); project.setProperty("environment", "ant"); project.setExceptions(true); project.setTrace(trace); project.setPedantic(pedantic); project.action(command); if (report(project)) throw new BuildException("Command " + command + " failed"); } catch (Throwable e) { if (exceptions) e.printStackTrace(); throw new BuildException(e); } } public void setCommand(String command) { this.command = command; } /** * Set the base directory of the project. This property MUST be set. * * @param basedir */ public void setBasedir(File basedir) { this.basedir = basedir; } // Old shit List files = new ArrayList(); List classpath = new ArrayList(); List sourcepath = new ArrayList(); File output = null; File testDir = null; boolean eclipse; boolean inherit = true; private void executeBackwardCompatible() throws BuildException { try { if (files == null) throw new BuildException("No files set"); if (eclipse) { File project = getProject().getBaseDir(); EclipseClasspath cp = new EclipseClasspath(this, project.getParentFile(), project); classpath.addAll(cp.getClasspath()); classpath.addAll(cp.getBootclasspath()); sourcepath.addAll(cp.getSourcepath()); // classpath.add(cp.getOutput()); if (report()) throw new BuildException("Errors during Eclipse Path inspection"); } if (output == null) output = getProject().getBaseDir(); for (Iterator f = files.iterator(); f.hasNext();) { File file = (File) f.next(); Builder builder = new Builder(); builder.setPedantic(isPedantic()); if (file.exists()) { // Do nice property calculations // merging includes etc. builder.setProperties(file); } // get them and merge them with the project // properties, if the inherit flag is specified if (inherit) { Properties projectProperties = new Properties(); projectProperties.putAll((Map) getProject().getProperties()); projectProperties.putAll(builder.getProperties()); builder.setProperties(projectProperties); } builder.setClasspath(toFiles(classpath, "classpath")); builder.setSourcepath(toFiles(sourcepath, "sourcepath")); Jar jars[] = builder.builds(); if (!failok && report() && report(builder)) { throw new BuildException("bnd failed", new Location(file.getAbsolutePath())); } for (int i = 0; i < jars.length; i++) { Jar jar = jars[i]; String bsn = jar.getName(); File base = file.getParentFile(); File output = this.output; String path = builder.getProperty("-output"); if (output == null) { if (path == null) output = getFile(base, bsn + ".jar"); else { output = getFile(base, path); } } else if (output.isDirectory()) { if (path == null) output = getFile(this.output, bsn + ".jar"); else output = getFile(this.output, path); } else if (output.isFile()) { if (files.size() > 1) error("Output is a file but there are multiple input files, these files will overwrite the output file: " + output.getAbsolutePath()); } String msg = ""; if (!output.exists() || output.lastModified() <= jar.lastModified()) { jar.write(output); } else { msg = "(not modified)"; } trace(jar.getName() + " (" + output.getName() + ") " + jar.getResources().size() + " " + msg); report(); jar.close(); } builder.close(); } } catch (Exception e) { // if (exceptions) e.printStackTrace(); if (!failok) throw new BuildException("Failed to build jar file: ", e); } } public void setFiles(String files) { files = files.replaceAll("\\.jar(,|$)", ".bnd"); addAll(this.files, files, ","); } void addAll(List list, String files, String separator) { trace("addAll '%s' with %s", files, separator); QuotedTokenizer qt = new QuotedTokenizer(files, separator); String entries[] = qt.getTokens(); File project = getProject().getBaseDir(); for (int i = 0; i < entries.length; i++) { File f = getFile(project, entries[i]); if (f.exists()) list.add(f); else error("Can not find bnd file to process: " + f.getAbsolutePath()); } } public void setClasspath(String value) { Path p = (Path) getProject().getReference(value); if (p == null) addAll(classpath, value, File.pathSeparator + ","); else { String[] path = p.list(); for (int i = 0; i < path.length; i++) classpath.add(new File(path[i])); } classpathDirectlySet = true; } public void setEclipse(boolean eclipse) { this.eclipse = eclipse; } boolean isFailok() { return failok; } public void setFailok(boolean failok) { this.failok = failok; } boolean isExceptions() { return exceptions; } public void setExceptions(boolean exceptions) { this.exceptions = exceptions; } boolean isPrint() { return print; } void setPrint(boolean print) { this.print = print; } public void setSourcepath(String sourcepath) { addAll(this.sourcepath, sourcepath, File.pathSeparator + ","); } static File[] EMPTY_FILES = new File[0]; File[] toFiles(List files, String what) throws IOException { return files.toArray(EMPTY_FILES); } public void setOutput(File output) { this.output = output; } public void setDestFile(File output) { this.output = output; } public void setTestDir(File testDir) { this.testDir = testDir; } public void setInherit(boolean inherit) { this.inherit = inherit; } public void setClasspathref(Reference reference) { classpathReference = createPath(reference); } public void setBndfilePath(Reference reference) { assertPathNotSet(bndfilePath, "bnd files are already set"); bndfilePath = createPath(reference); } public void addClasspath(Path path) { assertPathNotSet(classpathReference, "Classpath reference is already set"); classpathReference = path; } public void addBndfiles(Path path) { assertPathNotSet(bndfilePath, "bnd files are already set"); bndfilePath = path; } private Path createPath(Reference r) { Path path = new Path(getProject()).createPath(); path.setRefid(r); return path; } private void assertPathNotSet(Path path, String message) { if (path != null) { throw new BuildException(message); } } /** * validate required parameters before starting execution * * @throws BuildException * , if build is impossible */ protected void validate() { // no one of the 2 classpaths handling styles are defined // how could bnd work ? if (classpath == null && classpathReference == null) { log("Unable to get a classpath ...attributes not set"); throw new BuildException("No one of the classpath or classpathref defined..."); } if (classpathDirectlySet == true && classpathReference != null) { log("Unable to choose between classpath & classpathref !!"); throw new BuildException("Can't choose between classpath & classpathref"); } } // updates classpath for classpathref and nested classpath private void updateClasspath() { log("Updating classpath after classpathref setting"); if (classpathReference == null) { return; } addFilesFrom(classpathReference, classpath); } // updateClasspath() private void updateBndFiles() { if (bndfilePath == null) { return; } addFilesFrom(bndfilePath, files); } private void addFilesFrom(Path path, List files) { for (String fileName : path.list()) { files.add(new File(fileName.replace('\\', '/'))); } } } bnd-1.50.0/biz.aQute.bnd/src/aQute/bnd/ant/WrapTask.java0000755000175000017500000000521711656076535022460 0ustar drazzibdrazzib package aQute.bnd.ant; import java.io.*; import java.util.*; import org.apache.tools.ant.*; import org.apache.tools.ant.types.*; import aQute.bnd.main.*; import aQute.libg.qtokens.*; import aQute.libg.reporter.*; public class WrapTask extends BaseTask implements Reporter { List jars = new ArrayList(); File output = null; File definitions = null; List classpath = new ArrayList(); boolean failok; boolean exceptions; boolean print; @SuppressWarnings("unchecked") public void execute() throws BuildException { boolean failed = false; try { if (jars == null) throw new BuildException("No files set"); if (output == null) output = getProject().getBaseDir(); if (definitions == null) definitions = getProject().getBaseDir(); for (Iterator f = jars.iterator(); f.hasNext();) { bnd bnd = new bnd(); bnd.setPedantic(isPedantic()); File file = f.next(); String name = file.getName(); name = name.replaceFirst("(\\.jar)?$", ".bnd"); File bndFile = new File(definitions, name ); bnd.doWrap(bndFile.exists()?bndFile:null, file, output, classpath.toArray(new File[0]), 0, getProject().getProperties()); failed |= report(bnd); } } catch (Exception e) { if (exceptions) e.printStackTrace(); if (!failok) throw new BuildException("Failed to build jar file: " + e, e); } if ( failed && !failok) throw new BuildException("Failed to wrap jar file"); } public void setJars(String files) { addAll(this.jars, files, ","); } void addAll(List list, String files, String separator) { QuotedTokenizer qt = new QuotedTokenizer(files, separator); String entries[] = qt.getTokens(); File project = getProject().getBaseDir(); for (int i = 0; i < entries.length; i++) { File f = getFile(project, entries[i]); if (f.exists()) list.add(f); else error("Can not find bnd file to process: " + f.getAbsolutePath()); } } public void setClasspath(String files) { addAll(classpath, files, File.pathSeparator+","); } boolean isFailok() { return failok; } public void setFailok(boolean failok) { this.failok = failok; } public void setExceptions(boolean exceptions) { this.exceptions = exceptions; } public void setOutput(File output) { this.output = output; } public void setDefinitions(File out) { definitions = out; } public void addConfiguredFileSet(FileSet list) { DirectoryScanner scanner = list.getDirectoryScanner(getProject()); String files[] = scanner.getIncludedFiles(); for (int i = 0; i < files.length; i++) { File f= getFile(scanner.getBasedir(), files[i]); this.jars.add(f); } } } bnd-1.50.0/biz.aQute.bnd/src/aQute/bnd/ant/ExpandPropertiesTask.java0000755000175000017500000000176311656076535025045 0ustar drazzibdrazzibpackage aQute.bnd.ant; import java.io.*; import java.util.*; import org.apache.tools.ant.*; import aQute.lib.osgi.*; public class ExpandPropertiesTask extends BaseTask { File propertyFile; public void execute() throws BuildException { try { if (propertyFile.exists()) { Properties properties = new Properties(); properties.putAll((Map)getProject().getProperties()); Processor processor = new Processor(properties); processor.setProperties(propertyFile); Project project = getProject(); Properties flattened = processor.getFlattenedProperties(); for (Iterator i = flattened.keySet().iterator(); i.hasNext();) { String key = (String) i.next(); if (project.getProperty(key) == null) { project.setProperty(key, flattened.getProperty(key)); } } } report(); } catch (IOException e) { e.printStackTrace(); throw new BuildException(e); } } public void setPropertyFile(File file) { this.propertyFile = file; } } bnd-1.50.0/biz.aQute.bnd/src/aQute/bnd/ant/taskdef.properties0000755000175000017500000000037011656076535023613 0ustar drazzibdrazzibbnd=aQute.bnd.ant.BndTask bndproject=aQute.bnd.ant.ProjectTask bndeclipse=aQute.bnd.ant.EclipseTask bndexpand=aQute.bnd.ant.ExpandPropertiesTask bndwrap=aQute.bnd.ant.WrapTask bnddeploy=aQute.bnd.ant.DeployTask bndprepare=aQute.bnd.ant.PrepareTask bnd-1.50.0/biz.aQute.bnd/src/aQute/bnd/ant/DeployTask.java0000644000175000017500000000316511656076535023000 0ustar drazzibdrazzibpackage aQute.bnd.ant; import java.io.*; import java.util.*; import org.apache.tools.ant.*; import org.apache.tools.ant.types.*; import aQute.bnd.build.*; import aQute.bnd.build.Project; public class DeployTask extends BaseTask { List filesets = new ArrayList(); public void execute() throws BuildException { try { Project project = Workspace.getProject(getProject().getBaseDir()); // Deploy the files that need to be released for (FileSet fileset : filesets) { DirectoryScanner ds = fileset.getDirectoryScanner(getProject()); String[] files = ds.getIncludedFiles(); if (files.length == 0) trace("No files included"); for (int i = 0; i < files.length; i++) { File file = new File(ds.getBasedir(), files[i]); try { if (file.isFile() && file.getName().endsWith(".jar")) { project.deploy(file); } else error("Not a jar file: " + file); } catch (Exception e) { error("Failed to deploy " + file + " : " + e); } } } report(project); if (project.getErrors().size() > 0) throw new BuildException("Deploy failed"); } catch (Throwable t) { t.printStackTrace(); throw new BuildException(t); } } public void addFileset(FileSet files) { this.filesets.add(files); } } bnd-1.50.0/biz.aQute.bnd/src/aQute/bnd/ant/BaseTask.java0000755000175000017500000000623311656076535022420 0ustar drazzibdrazzibpackage aQute.bnd.ant; import java.io.*; import java.util.*; import org.apache.tools.ant.*; import aQute.libg.reporter.*; public class BaseTask extends Task implements Reporter { List errors = new ArrayList(); List warnings = new ArrayList(); List progress = new ArrayList(); boolean pedantic; boolean trace; public void error(String s, Object... args ) { errors.add(String.format(s, args)); } public List getErrors() { return errors; } public List getProgress() { return progress; } public List getWarnings() { // TODO Auto-generated method stub return warnings; } public void progress(String s, Object ... args) { progress.add(String.format(s,args)); } public void warning(String s, Object ... args) { warnings.add(String.format(s, args)); } protected boolean report() { return report(this); } protected boolean report(Reporter reporter) { if (reporter.getWarnings().size() > 0) { System.err.println("Warnings"); for (Iterator e = reporter.getWarnings().iterator(); e.hasNext();) { System.err.println(" " + e.next()); } } if (reporter.getErrors().size() > 0) { System.err.println( reporter.getErrors().size() + " Errors"); for (Iterator e = reporter.getErrors().iterator(); e.hasNext();) { System.err.println(" " + e.next()); } return true; } return false; } public static File getFile(File base, String file) { File f = new File(file); if (!f.isAbsolute()) { int n; f = base.getAbsoluteFile(); while ((n = file.indexOf('/')) > 0) { String first = file.substring(0, n); file = file.substring(n + 1); if (first.equals("..")) f = f.getParentFile(); else f = new File(f, first); } f = new File(f, file); } try { return f.getCanonicalFile(); } catch(IOException e ) { return f.getAbsoluteFile(); } } protected List split(String dependsOn, String string) { if (dependsOn == null) return new ArrayList(); return Arrays.asList(string.split("\\s*" + string + "\\s*")); } protected String join(Collection classpath, String string) { StringBuffer sb = new StringBuffer(); String del = ""; for (Object name : classpath) { sb.append(del); sb.append(name); del = string; } return sb.toString(); } public boolean isPedantic() { return pedantic; } public void setPedantic(boolean pedantic) { this.pedantic = pedantic; } public void setTrace(boolean trace) { this.trace = trace; } public void trace(String s, Object... args) { System.out.printf("# "+s+"\n", args); } } bnd-1.50.0/biz.aQute.bnd/src/aQute/bnd/ant/EclipseTask.java0000755000175000017500000000623011656076535023127 0ustar drazzibdrazzibpackage aQute.bnd.ant; import java.io.*; import java.util.*; import org.apache.tools.ant.*; import aQute.lib.osgi.eclipse.*; public class EclipseTask extends BaseTask { private String prefix = "project."; private List prebuild = new ArrayList(); private File workspaceLocation; private String separator = ","; private File projectLocation; public void execute() throws BuildException { try { if (projectLocation == null) projectLocation = getProject().getBaseDir(); if (workspaceLocation == null) workspaceLocation = projectLocation.getParentFile(); EclipseClasspath eclipse = new EclipseClasspath(this, workspaceLocation, projectLocation); if (report()) throw new BuildException( "Errors during Eclipse Path inspection"); addProperty(prefix + "classpath", join(eclipse.getClasspath(), separator)); addProperty(prefix + "bootclasspath", join(eclipse .getBootclasspath(), separator)); if (!eclipse.getSourcepath().isEmpty()) addProperty(prefix + "sourcepath", join( eclipse.getSourcepath(), separator)); addProperty(prefix + "output", eclipse.getOutput() .getAbsolutePath()); /** * The prebuild is an attribute that is prepended to the dependency * path derived from the Eclipse project */ List dependents = new ArrayList(); addCareful(dependents, prebuild); addCareful(dependents, eclipse.getDependents()); if (dependents.size() > 0) { addProperty(prefix + "buildpath", join(dependents, separator)); } } catch (Exception e) { throw new BuildException( "Error during parsing Eclipse .classpath files", e); } } private void addCareful(List result, Collection projects) { for (Iterator i = projects.iterator(); i.hasNext();) { File d = i.next(); if (!result.contains(d)) result.add(d); } } protected void addProperty(String n, String v) { // System.out.println(" Adding property: " + n + " = " + v); if (v != null) getProject().setProperty(n, v); } public void setPrefix(String prefix) { this.prefix = prefix; } public void setPrebuild(String prebuild) { StringTokenizer st = new StringTokenizer(prebuild, " ,"); while (st.hasMoreTokens()) { this.prebuild.add(getFile( getProject().getBaseDir().getParentFile(), st.nextToken())); } } public void setSeparator(String separator) { this.separator = separator; } public void setProjectLocation(File projectLocation) { this.projectLocation = projectLocation; } public void setWorkspaceLocation(File workspaceLocation) { this.workspaceLocation = workspaceLocation; } } bnd-1.50.0/biz.aQute.bnd/src/aQute/bnd/ant/ProjectTask.java0000644000175000017500000000222211656076535023143 0ustar drazzibdrazzibpackage aQute.bnd.ant; /** * The idea of this task is to read all the properties as if bnd has read them. * This makes it easier to use bnd standalone on the same data. */ import java.io.*; import org.apache.tools.ant.*; import aQute.bnd.build.*; import aQute.bnd.build.Project; public class ProjectTask extends BaseTask { File basedir; boolean underTest; public void execute() throws BuildException { try { if (basedir == null || !basedir.isDirectory()) throw new BuildException("The given base dir does not exist " + basedir); Project project = Workspace.getProject(basedir); project.build(underTest); report(project); } catch (Exception e) { e.printStackTrace(); throw new BuildException(e); } } /** * Set the base directory of the project. This property MUST be set. * * @param basedir */ public void setBasedir(File basedir) { this.basedir = basedir; } public void setUnderTest(boolean underTest) { this.underTest = underTest; } } bnd-1.50.0/biz.aQute.bnd/src/aQute/bnd/launch/0000755000175000017500000000000011656076535020541 5ustar drazzibdrazzibbnd-1.50.0/biz.aQute.bnd/src/aQute/bnd/launch/Shortcut.java0000644000175000017500000000731111656076535023221 0ustar drazzibdrazzibpackage aQute.bnd.launch; import java.util.*; import org.eclipse.core.runtime.*; import org.eclipse.debug.core.*; import org.eclipse.debug.ui.*; import org.eclipse.jdt.core.*; import org.eclipse.jdt.launching.*; import org.eclipse.jface.viewers.*; import org.eclipse.ui.*; public class Shortcut implements ILaunchShortcut { public Shortcut() { // System.out.println("Constructor Launch Shortcut"); } protected String getLaunchConfigurationTypeId() { return "aQute.bnd.launch"; } public void launch(ISelection selection, String mode) { IStructuredSelection is = (IStructuredSelection) selection; if ( is.getFirstElement() != null ) { Object selected = is.getFirstElement(); IJavaElement element = null; if (selected instanceof IJavaElement ) element = (IJavaElement) selected; else if ( selected instanceof IAdaptable ) { element = (IJavaElement) ((IAdaptable)selected).getAdapter(IJavaElement.class); } if ( element != null ) launch(element.getJavaProject(), mode); } // TODO figure out which project we are in??? } public void launch(IEditorPart editor, String mode) { IEditorInput input = editor.getEditorInput(); IJavaElement je = (IJavaElement) input.getAdapter(IJavaElement.class); if (je != null) { IJavaProject jproject = je.getJavaProject(); if (jproject != null) { launch(jproject, mode); } } } void launch(IJavaProject project, String mode) { try { ILaunchConfiguration config = find(project); if (config == null) config = createConfiguration(project); DebugUITools.launch(config, mode); } catch (Exception e) { e.printStackTrace(); } } ILaunchConfigurationType getConfigurationType() { return getLaunchManager() .getLaunchConfigurationType("aQute.bnd.launch"); } ILaunchConfiguration find(IJavaProject project) throws CoreException { List candidateConfigs = new ArrayList(); ILaunchConfiguration[] configs = DebugPlugin.getDefault() .getLaunchManager().getLaunchConfigurations( getConfigurationType()); for (int i = 0; i < configs.length; i++) { ILaunchConfiguration config = configs[i]; if (config .getAttribute( IJavaLaunchConfigurationConstants.ATTR_PROJECT_NAME, "").equals(project.getElementName())) { //$NON-NLS-1$ candidateConfigs.add(config); } } if (candidateConfigs.size() == 0) { return null; } // return the latest return candidateConfigs.get(candidateConfigs.size() - 1); } protected ILaunchManager getLaunchManager() { return DebugPlugin.getDefault().getLaunchManager(); } protected ILaunchConfiguration createConfiguration(IJavaProject type) throws Exception { ILaunchConfiguration config = null; ILaunchConfigurationWorkingCopy wc = null; ILaunchConfigurationType configType = getConfigurationType(); wc = configType.newInstance(null, getLaunchManager() .generateUniqueLaunchConfigurationNameFrom( type.getElementName())); wc.setAttribute(IJavaLaunchConfigurationConstants.ATTR_PROJECT_NAME, type.getElementName()); config = wc.doSave(); return config; } } bnd-1.50.0/biz.aQute.bnd/src/aQute/bnd/launch/LaunchDelegate.java0000644000175000017500000000265111656076535024255 0ustar drazzibdrazzibpackage aQute.bnd.launch; import org.eclipse.core.runtime.*; import org.eclipse.debug.core.*; import org.eclipse.jdt.core.*; import org.eclipse.jdt.launching.*; import aQute.bnd.build.*; import aQute.bnd.plugin.*; import aQute.lib.osgi.*; public class LaunchDelegate extends JavaLaunchDelegate { ProjectLauncher launcher; public void launch(ILaunchConfiguration configuration, String mode, ILaunch launch, IProgressMonitor monitor) throws CoreException { IJavaProject javaProject = getJavaProject(configuration); Project project = Activator.getDefault().getCentral().getModel(javaProject); try { launcher = project.getProjectLauncher(); super.launch(configuration, mode, launch, monitor); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } public String verifyMainTypeName(ILaunchConfiguration configuration) throws CoreException { return launcher.getMainTypeName(); } public String getVMArguments(ILaunchConfiguration c) { return Processor.join(launcher.getRunVM(), " "); } public String getProgramArguments(ILaunchConfiguration c) { return Processor.join(launcher.getArguments(), " "); } public String[] getClasspath(ILaunchConfiguration configuration) { return launcher.getClasspath().toArray(new String[0]); } } bnd-1.50.0/biz.aQute.bnd/src/aQute/bnd/launch/LaunchTabGroup.java0000644000175000017500000000121311656076535024257 0ustar drazzibdrazzibpackage aQute.bnd.launch; import org.eclipse.debug.ui.*; import org.eclipse.debug.ui.sourcelookup.*; import org.eclipse.jdt.debug.ui.launchConfigurations.*; public class LaunchTabGroup extends AbstractLaunchConfigurationTabGroup { public void createTabs(ILaunchConfigurationDialog dialog, String mode) { ILaunchConfigurationTab[] tabs = new ILaunchConfigurationTab[] { new JavaArgumentsTab(), new JavaClasspathTab(), new JavaJRETab(), new SourceLookupTab(), new EnvironmentTab(), new CommonTab(), }; setTabs(tabs); } } bnd-1.50.0/biz.aQute.bnd/src/aQute/bnd/jareditor/0000755000175000017500000000000011656076535021252 5ustar drazzibdrazzibbnd-1.50.0/biz.aQute.bnd/src/aQute/bnd/jareditor/JarDocumentProvider.java0000644000175000017500000000451111656076535026044 0ustar drazzibdrazzibpackage aQute.bnd.jareditor; import java.io.*; import org.eclipse.core.runtime.*; import org.eclipse.jface.text.*; import org.eclipse.jface.text.source.*; import org.eclipse.ui.part.*; import org.eclipse.ui.texteditor.*; public class JarDocumentProvider implements IDocumentProvider { Document doc; PrintWriter out; public void aboutToChange(Object arg0) { // TODO Auto-generated method stub } public void addElementStateListener(IElementStateListener arg0) { // TODO Auto-generated method stub } public boolean canSaveDocument(Object arg0) { // TODO Auto-generated method stub return false; } public void changed(Object arg0) { // TODO Auto-generated method stub } public void connect(Object source) throws CoreException { try { if (source instanceof FileEditorInput) { FileEditorInput input = (FileEditorInput) source; File file = input.getPath().toFile(); doc = new Document(print(file)); } } catch (Exception e) { throw new RuntimeException(e); } } public void disconnect(Object arg0) { // TODO Auto-generated method stub } public IAnnotationModel getAnnotationModel(Object arg0) { // TODO Auto-generated method stub return null; } public IDocument getDocument(Object arg0) { return doc; } public long getModificationStamp(Object arg0) { // TODO Auto-generated method stub return 0; } public long getSynchronizationStamp(Object arg0) { // TODO Auto-generated method stub return 0; } public boolean isDeleted(Object arg0) { // TODO Auto-generated method stub return false; } public boolean mustSaveDocument(Object arg0) { // TODO Auto-generated method stub return false; } public void removeElementStateListener(IElementStateListener arg0) { // TODO Auto-generated method stub } public void resetDocument(Object arg0) throws CoreException { // TODO Auto-generated method stub } public void saveDocument(IProgressMonitor arg0, Object arg1, IDocument arg2, boolean arg3) throws CoreException { // TODO Auto-generated method stub } String print(File file) throws Exception { ByteArrayOutputStream bos = new ByteArrayOutputStream(); PrintStream ps = new PrintStream(bos); aQute.bnd.main.bnd x = new aQute.bnd.main.bnd(); x.setOut(ps); x.doPrint(file.getAbsolutePath(), -1); ps.close(); return new String( bos.toByteArray()); } } bnd-1.50.0/biz.aQute.bnd/src/aQute/bnd/jareditor/JarEditor.java0000644000175000017500000000071711656076535024005 0ustar drazzibdrazzibpackage aQute.bnd.jareditor; import org.eclipse.ui.texteditor.*; public class JarEditor extends AbstractTextEditor { public JarEditor() { //install the source configuration setSourceViewerConfiguration(new JarConfiguration()); //install the document provider setDocumentProvider(new JarDocumentProvider()); } protected void createActions() { super.createActions(); //... add other editor actions here } } bnd-1.50.0/biz.aQute.bnd/src/aQute/bnd/jareditor/JarConfiguration.java0000644000175000017500000000021411656076535025356 0ustar drazzibdrazzibpackage aQute.bnd.jareditor; import org.eclipse.jface.text.source.*; public class JarConfiguration extends SourceViewerConfiguration { } bnd-1.50.0/biz.aQute.bnd/src/aQute/bnd/classpath/0000755000175000017500000000000011656076535021251 5ustar drazzibdrazzibbnd-1.50.0/biz.aQute.bnd/src/aQute/bnd/classpath/BndContainerInitializer.java0000644000175000017500000000716211656076535026674 0ustar drazzibdrazzibpackage aQute.bnd.classpath; import org.eclipse.core.runtime.*; import org.eclipse.jdt.core.*; import aQute.bnd.build.*; import aQute.bnd.plugin.*; /** * A bnd container reads the bnd.bnd file in the project directory and use the * information in there to establish the classpath. The classpath is defined by * the -build-env instruction. This instruction contains a list of bsn's that * are searched in the available repositories and returned as File objects. * * This initializer establishes the link between the container object and the * BndModel. The container object is just a delegator because for some unknown * reasons, you can only update the container (refresh the contents) when you * give it a new object ;-( * * Because this plugin uses the Bnd Builder in different places, the Bnd Model * is centralized and available from the Activator. */ public class BndContainerInitializer extends ClasspathContainerInitializer implements ModelListener { public final static Path ID = new Path("aQute.bnd.classpath.container"); final Central central = Activator.getDefault().getCentral(); public BndContainerInitializer() { central.addModelListener(this); } /** * Called when a new project is found. This class is instantiated once and * then used for any project that has a bnd container associated. We create * a link between the project and the Bnd Model. A delegating container * object is created to link the project to the container so it can get its * classpath entries. Note that the container object is not stored or * remembered because we create a new one for every update (otherwise the * update is not visible for some reason) */ public void initialize(IPath containerPath, IJavaProject project) throws CoreException { // We maintain the models in the actitvator because other // parts also use the model. Unfortunately, one can only // do this with a static method :-( Project model = central.getModel(project); if (model == null) throw new CoreException( new Status(IStatus.ERROR, ID.toString(), "Can not create model, likely the project does not contain a bnd.bnd file")); // Update the Java Model so the changes become visible. // Notice the unreferenced object. requestClasspathContainerUpdate(containerPath, project, new BndContainer(model)); } /** * We can always update. */ public boolean canUpdateClasspathContainer(IPath containerPath, IJavaProject project) { return true; } /** * Update the container. The containerSuggestion should always be a new * BndContainer ... */ public void requestClasspathContainerUpdate(IPath containerPath, IJavaProject project, IClasspathContainer containerSuggestion) throws CoreException { JavaCore.setClasspathContainer(containerPath, new IJavaProject[] { project }, new IClasspathContainer[] { containerSuggestion }, null); } public void modelChanged(Project model) throws Exception { IJavaProject project = central.getJavaProject(model); if (model == null || project == null) { //System.out.println("Help! No IJavaProject for " + model); } else requestClasspathContainerUpdate(ID, project, new BndContainer(model)); } public void workspaceChanged(Workspace ws) throws Exception { //System.out.println("Workspace changed"); } } bnd-1.50.0/biz.aQute.bnd/src/aQute/bnd/classpath/ModelListener.java0000644000175000017500000000022411656076535024660 0ustar drazzibdrazzibpackage aQute.bnd.classpath; import aQute.bnd.build.*; public interface ModelListener { void modelChanged(Project model) throws Exception; } bnd-1.50.0/biz.aQute.bnd/src/aQute/bnd/classpath/BndContainer.java0000644000175000017500000000534111656076535024465 0ustar drazzibdrazzibpackage aQute.bnd.classpath; import java.io.*; import java.util.*; import org.eclipse.core.runtime.*; import org.eclipse.jdt.core.*; import aQute.bnd.build.*; import aQute.bnd.plugin.*; public class BndContainer implements IClasspathContainer { final static IClasspathEntry ICLASSPATHENTRY_EMPTY[] = new IClasspathEntry[0]; final Project project; volatile int count; volatile IClasspathEntry[] cachedEntries; BndContainer(Project project) { this.project = project; } /** * Get the classpath entries ... seems to be called VERY often */ public IClasspathEntry[] getClasspathEntries() { boolean cached = cachedEntries != null && count == project.getChanged(); if (!cached) { try { if (project.lock("get class path " + project) ) try { project.clear(); count = project.getChanged(); ArrayList result = new ArrayList(); // fetch the names of all files that match our filter List entries = new ArrayList(); entries.addAll(project.getBuildpath()); // The first file is always the project directory, Eclipse // already includes that for us. if (entries.size() > 0) entries.remove(0); else ; //System.err.println("Huh? Should have the bin dir! " + entries); // Eclipse does not know a boot classpath, but it compiles // against // a jre. We add anything on the bootpath entries.addAll(project.getBootclasspath()); for (Container c : entries) { IClasspathEntry cpe; IPath sourceAttachment = null; if (c.getError() == null) { File file = c.getFile(); assert file.isAbsolute(); IPath p = Central.toPath(project, file); // JDT seems to ignore files when they // are outside the workspace if (p == null) p = Path.fromOSString(file.getAbsolutePath()); try { Central.refresh(p); } catch (Throwable e) { } if (c.getType() == Container.TYPE.PROJECT) { File sourceDir = c.getProject().getSrc(); if (sourceDir.isDirectory()) sourceAttachment = Central.toPath(c.getProject(), sourceDir); } cpe = JavaCore.newLibraryEntry(p, sourceAttachment, null); result.add(cpe); } } cachedEntries = result.toArray(ICLASSPATHENTRY_EMPTY); } finally { project.unlock(); } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } return cachedEntries; } public String getDescription() { return "bnd"; } public int getKind() { return IClasspathContainer.K_APPLICATION; } public IPath getPath() { return BndContainerInitializer.ID; } public Project getModel() { return project; } } bnd-1.50.0/biz.aQute.bnd/src/aQute/bnd/classpath/messages.properties0000644000175000017500000000105611656076535025200 0ustar drazzibdrazzibBrowse=Browse... DirErr=The directory must be a subdirectory of the project {0} DirLabel=Directory: DirSelect=Select the directory for the Simple Dir Container ExtErr=Extensions are not valid. Verify that the extensions are comma separated and do not include the preceding '.' ExtLabel=Extensions (comma separated, not including .): InvalidContainer=Invalid container: PageDesc=A classpath container that collects files with configured extensions from a configured directory PageName=Simple Directory Container Wizard PageTitle=Simple Directory Container bnd-1.50.0/biz.aQute.bnd/src/aQute/bnd/classpath/BndContainerPage.java0000644000175000017500000002101011656076535025251 0ustar drazzibdrazzibpackage aQute.bnd.classpath; import java.io.*; import org.eclipse.core.resources.*; import org.eclipse.core.runtime.*; import org.eclipse.jdt.core.*; import org.eclipse.jdt.ui.wizards.*; import org.eclipse.jface.viewers.*; import org.eclipse.jface.wizard.*; import org.eclipse.swt.*; import org.eclipse.swt.events.*; import org.eclipse.swt.graphics.*; import org.eclipse.swt.layout.*; import org.eclipse.swt.widgets.*; import aQute.bnd.build.*; import aQute.bnd.plugin.*; public class BndContainerPage extends WizardPage implements IClasspathContainerPage, IClasspathContainerPageExtension { // private Activator activator = Activator.getActivator(); private Table table; private Project model; private File basedir; private IJavaProject javaProject; /** * Default Constructor - sets title, page name, description */ public BndContainerPage() { super("bnd", "bnd - classpath", null); setDescription("Ensures that bnd sees the same classpath as eclipse. The table will show the current contents. If there is no bnd file, you can create it with the button"); setPageComplete(true); } /* * (non-Javadoc) * * @see org.eclipse.jdt.ui.wizards.IClasspathContainerPageExtension#initialize(org.eclipse.jdt.core.IJavaProject, * org.eclipse.jdt.core.IClasspathEntry[]) */ public void initialize(IJavaProject project, IClasspathEntry[] currentEntries) { javaProject = project; model = Activator.getDefault().getCentral().getModel(project); basedir = project.getProject().getLocation().makeAbsolute().toFile(); } /* * (non-Javadoc) * * @see org.eclipse.jface.dialogs.IDialogPage#createControl(org.eclipse.swt.widgets.Composite) */ public void createControl(Composite parent) { Composite composite = new Composite(parent, SWT.NULL); composite.setLayout(new FormLayout()); composite.setLayoutData(new GridData(GridData.VERTICAL_ALIGN_FILL | GridData.HORIZONTAL_ALIGN_FILL)); composite.setFont(parent.getFont()); setControl(composite); final Button wCreate = new Button(composite, SWT.NONE); wCreate.setEnabled(model == null); final FormData fd_wCreate = new FormData(); fd_wCreate.bottom = new FormAttachment(100, -5); fd_wCreate.right = new FormAttachment(100, -4); wCreate.setLayoutData(fd_wCreate); wCreate.setText("Create bnd.bnd"); final TableViewer tableViewer = new TableViewer(composite, SWT.BORDER); table = tableViewer.getTable(); final FormData fd_table = new FormData(); fd_table.top = new FormAttachment(0, 3); fd_table.left = new FormAttachment(0, 3); fd_table.right = new FormAttachment(100, -4); fd_table.bottom = new FormAttachment(100, -37); table.setLayoutData(fd_table); table.setLinesVisible(true); table.setHeaderVisible(true); final TableColumn wBsn = new TableColumn(table, SWT.NONE); wBsn.setWidth(200); wBsn.setText("Bundle Symbolic Name"); final TableColumn wVersion = new TableColumn(table, SWT.NONE); wVersion.setWidth(100); wVersion.setText("Version"); final TableColumn wOptions = new TableColumn(table, SWT.NONE); wOptions.setWidth(200); wOptions.setText("Options"); final TableColumn wFile = new TableColumn(table, SWT.NONE); wFile.setWidth(100); wFile.setText("File"); tableViewer.setContentProvider(new IStructuredContentProvider() { public Object[] getElements(Object inputElement) { if (model != null) try { return model.getBuildpath().toArray(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return new Object[0]; } public void dispose() { // TODO Auto-generated method stub } public void inputChanged(Viewer viewer, Object oldInput, Object newInput) { } }); tableViewer.setLabelProvider(new ITableLabelProvider() { public Image getColumnImage(Object element, int columnIndex) { // TODO Auto-generated method stub return null; } public String getColumnText(Object element, int columnIndex) { Container c = (Container) element; switch (columnIndex) { case 0: return c.getBundleSymbolicName(); case 1: return c.getVersion(); case 2: return c.getError(); case 3: return c.getFile() + " (" + (c.getFile()!=null && c.getFile().exists() ? "exists" : "?") + ")"; } return null; } public void addListener(ILabelProviderListener listener) { // TODO Auto-generated method stub } public void dispose() { // TODO Auto-generated method stub } public boolean isLabelProperty(Object element, String property) { // TODO Auto-generated method stub return false; } public void removeListener(ILabelProviderListener listener) { // TODO Auto-generated method stub } }); tableViewer.setInput(model); wCreate.addSelectionListener(new SelectionListener() { public void widgetDefaultSelected(SelectionEvent e) { //System.out.println("defw selected"); } public void widgetSelected(SelectionEvent e) { wCreate.setEnabled(!createBnd()); tableViewer.setInput(model); } }); } protected boolean createBnd() { if (basedir != null && basedir.isDirectory()) { File bnd = new File(basedir, "bnd.bnd"); try { FileOutputStream out = new FileOutputStream(bnd); PrintStream ps = new PrintStream(out); try { ps.println("# Auto generated by bnd, please adapt"); ps.println(); ps.println("Export-Package: "); ps.println("Private-Package: "); ps .println("Bundle-Name: ${Bundle-SymbolicName}"); ps.println("Bundle-Version: 1.0"); ps.println(); ps.println("#Example buildpath"); ps .println("-buildpath: osgi; version=4.0, \\"); ps .println(" com.springsource.junit; version=\"[3.8,4)\""); } finally { out.close(); ps.close(); } javaProject.getResource().refreshLocal(IResource.DEPTH_ONE, null); model = Activator.getDefault().getCentral().getModel(javaProject); return model != null; } catch (IOException e) { e.printStackTrace(); } catch (CoreException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return false; } /* * (non-Javadoc) * * @see org.eclipse.jdt.ui.wizards.IClasspathContainerPage#finish() */ public boolean finish() { return true; } /* * (non-Javadoc) * * @see org.eclipse.jdt.ui.wizards.IClasspathContainerPage#getSelection() */ public IClasspathEntry getSelection() { IPath containerPath = BndContainerInitializer.ID; IClasspathEntry cpe = JavaCore.newContainerEntry(containerPath); return cpe; } /* * (non-Javadoc) * * @see org.eclipse.jdt.ui.wizards.IClasspathContainerPage#setSelection(org.eclipse.jdt.core.IClasspathEntry) */ public void setSelection(IClasspathEntry containerEntry) { if (containerEntry != null) { // initPath = containerEntry.getPath(); } } } bnd-1.50.0/biz.aQute.bnd/README0000644000175000017500000000027411656076535015541 0ustar drazzibdrazzibThe bnd project creates a Jar that has the following functions: - Command line utility (has a Main-Class) - An Eclipse plugin (this will be replaced soon with bndtools) - An ant plugin bnd-1.50.0/biz.aQute.bnd/.settings/0000755000175000017500000000000011656076535016574 5ustar drazzibdrazzibbnd-1.50.0/biz.aQute.bnd/.settings/org.eclipse.jdt.core.prefs0000644000175000017500000000115211656076535023555 0ustar drazzibdrazzib#Wed Apr 14 09:17:00 CEST 2010 eclipse.preferences.version=1 org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.5 org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve org.eclipse.jdt.core.compiler.compliance=1.5 org.eclipse.jdt.core.compiler.debug.lineNumber=generate org.eclipse.jdt.core.compiler.debug.localVariable=generate org.eclipse.jdt.core.compiler.debug.sourceFile=generate org.eclipse.jdt.core.compiler.problem.assertIdentifier=error org.eclipse.jdt.core.compiler.problem.enumIdentifier=error org.eclipse.jdt.core.compiler.source=1.5 bnd-1.50.0/biz.aQute.bnd/.settings/org.eclipse.core.resources.prefs0000644000175000017500000000012511656076535025005 0ustar drazzibdrazzib#Mon Sep 19 11:00:09 EDT 2005 eclipse.preferences.version=1 encoding/=UTF-8 bnd-1.50.0/biz.aQute.bnd/.settings/org.eclipse.core.runtime.prefs0000644000175000017500000000011611656076535024456 0ustar drazzibdrazzib#Tue Dec 14 12:22:25 EST 2010 eclipse.preferences.version=1 line.separator=\n bnd-1.50.0/build.xml0000644000175000017500000000117511656076535014077 0ustar drazzibdrazzib bnd-1.50.0/demo/0000755000175000017500000000000011656076535013176 5ustar drazzibdrazzibbnd-1.50.0/demo/build.xml0000644000175000017500000000023111656076535015013 0ustar drazzibdrazzib bnd-1.50.0/demo/bnd.bnd0000644000175000017500000000107611656076535014432 0ustar drazzibdrazzibPrivate-Package: com.example.demo Bundle-Activator: com.example.demo.Activator Bundle-SymbolicName: demo -buildpath: osgi.core,\ ee.minimum;version=1.2.1 -testpath: \ biz.aQute.junit; version=snapshot -runpath: \ org.eclipse.osgi, \ biz.aQute.launcher; version=snapshot -runbundles: org.apache.felix.scr,\ org.apache.felix.configadmin Bundle-Activator: test.TestActivator Private-Package: test Import-Package: \ junit.framework;resolution:=optional,\ * -buildpath: osgi.core,\ ee.minimum;version=1.2.1,\ junit.osgi javac.target=1.4 javac.source=1.4 bnd-1.50.0/demo/.classpath0000644000175000017500000000044511656076535015164 0ustar drazzibdrazzib bnd-1.50.0/demo/.project0000644000175000017500000000100111656076535014635 0ustar drazzibdrazzib demo org.eclipse.jdt.core.javabuilder bndtools.core.bndbuilder org.eclipse.jdt.core.javanature bndtools.core.bndnature bnd-1.50.0/demo/src/0000755000175000017500000000000011656076535013765 5ustar drazzibdrazzibbnd-1.50.0/demo/src/test/0000755000175000017500000000000011656076535014744 5ustar drazzibdrazzibbnd-1.50.0/demo/src/test/TestActivator.java0000644000175000017500000000165711656076535020414 0ustar drazzibdrazzibpackage test; import java.util.*; import org.osgi.framework.*; public class TestActivator implements BundleActivator { public void start(BundleContext context) throws Exception { System.out.println("Hello world"); context.registerService(TestActivator.class.getName(), this, null); String p = context.getProperty("test.cmd"); System.out.println("test.cmd='" + p + "'"); if ("exit".equals(p)) System.exit(42); else if ("timeout".equals(p)) { Thread.sleep(10000); } else if ( "main.thread".equals(p)){ Runnable r = new Runnable() { public void run() { System.out.println("Running in main"); } }; Properties props = new Properties(); props.setProperty("main.thread", "true"); context.registerService(Runnable.class.getName(), r, props); } System.out.println("Done " + p); } public void stop(BundleContext arg0) throws Exception { System.out.println("Goodbye world"); } } bnd-1.50.0/demo/src/test/TestCase1.java0000644000175000017500000000056511656076535017411 0ustar drazzibdrazzibpackage test; import junit.framework.*; public class TestCase1 extends TestCase { public void test1() { System.out.println("All ok"); } public void test2() { throw new IllegalArgumentException("Don't talk to me like that!!!!!"); } public void test3() { fail("I am feeling depressive"); } public void test4() { System.out.println("All ok again"); } } bnd-1.50.0/demo/src/com/0000755000175000017500000000000011656076535014543 5ustar drazzibdrazzibbnd-1.50.0/demo/src/com/example/0000755000175000017500000000000011656076535016176 5ustar drazzibdrazzibbnd-1.50.0/demo/src/com/example/demo/0000755000175000017500000000000011656076535017122 5ustar drazzibdrazzibbnd-1.50.0/demo/src/com/example/demo/Activator.java0000644000175000017500000000046711656076535021730 0ustar drazzibdrazzibpackage com.example.demo; import org.osgi.framework.*; public class Activator implements BundleActivator { public void start(BundleContext arg0) throws Exception { System.out.println("Hello World"); } public void stop(BundleContext arg0) throws Exception { System.out.println("Goodbye World"); } } bnd-1.50.0/demo/.settings/0000755000175000017500000000000011656076535015114 5ustar drazzibdrazzibbnd-1.50.0/demo/.settings/org.eclipse.jdt.core.prefs0000644000175000017500000000115611656076535022101 0ustar drazzibdrazzib#Mon Oct 24 15:46:06 CEST 2011 eclipse.preferences.version=1 org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.2 org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve org.eclipse.jdt.core.compiler.compliance=1.4 org.eclipse.jdt.core.compiler.debug.lineNumber=generate org.eclipse.jdt.core.compiler.debug.localVariable=generate org.eclipse.jdt.core.compiler.debug.sourceFile=generate org.eclipse.jdt.core.compiler.problem.assertIdentifier=warning org.eclipse.jdt.core.compiler.problem.enumIdentifier=warning org.eclipse.jdt.core.compiler.source=1.3 bnd-1.50.0/demo/.settings/org.eclipse.core.resources.prefs0000644000175000017500000000012511656076535023325 0ustar drazzibdrazzib#Mon Sep 19 11:00:09 EDT 2005 eclipse.preferences.version=1 encoding/=UTF-8 bnd-1.50.0/demo/.settings/org.eclipse.core.runtime.prefs0000644000175000017500000000011611656076535022776 0ustar drazzibdrazzib#Tue Dec 14 12:22:25 EST 2010 eclipse.preferences.version=1 line.separator=\n bnd-1.50.0/biz.aQute.junit/0000755000175000017500000000000011656076535015244 5ustar drazzibdrazzibbnd-1.50.0/biz.aQute.junit/build.xml0000644000175000017500000000017711656076535017072 0ustar drazzibdrazzib bnd-1.50.0/biz.aQute.junit/bnd.bnd0000644000175000017500000000077311656076535016503 0ustar drazzibdrazzib-buildpath: com.springsource.junit,\ ee.minimum;version=1.2.1,\ osgi.cmpn;version=4.2.1,\ biz.aQute.bndlib;version=project,\ aQute.libg;version=project,\ osgi.core;version=4.2.1 Tester-Plugin: aQute.junit.plugin.ProjectTesterImpl javac.source = 1.5 javac.target = jsr14 Private-Package: aQute.junit.*,\ junit.framework Export-Package: junit.framework; version=3.8 Import-Package: !aQute.*,\ * Bundle-Activator: aQute.junit.Activator Embedded-Activator: aQute.junit.Activator Bundle-Version: 1.0.0 bnd-1.50.0/biz.aQute.junit/.classpath0000644000175000017500000000033011656076535017223 0ustar drazzibdrazzib bnd-1.50.0/biz.aQute.junit/.project0000644000175000017500000000101411656076535016707 0ustar drazzibdrazzib biz.aQute.junit org.eclipse.jdt.core.javabuilder bndtools.core.bndbuilder org.eclipse.jdt.core.javanature bndtools.core.bndnature bnd-1.50.0/biz.aQute.junit/src/0000755000175000017500000000000011656076535016033 5ustar drazzibdrazzibbnd-1.50.0/biz.aQute.junit/src/aQute/0000755000175000017500000000000011656076535017112 5ustar drazzibdrazzibbnd-1.50.0/biz.aQute.junit/src/aQute/junit/0000755000175000017500000000000011656076535020243 5ustar drazzibdrazzibbnd-1.50.0/biz.aQute.junit/src/aQute/junit/BasicTestReport.java0000644000175000017500000000523111656076535024164 0ustar drazzibdrazzibpackage aQute.junit; import java.io.*; import java.lang.reflect.*; import java.util.*; import junit.framework.*; import org.osgi.framework.*; public class BasicTestReport implements TestListener, TestReporter { private int errors; private PrintStream out; private final Tee systemOut; private final Tee systemErr; private int fails; private Bundle targetBundle; private final Activator activator; public BasicTestReport(Activator activator, Tee systemOut, Tee systemErr) { this.systemOut = systemOut; this.systemErr = systemErr; this.activator = activator; } public void setup(Bundle fw, Bundle targetBundle) { this.targetBundle = targetBundle; } public void begin(List tests, int realcount) { activator.trace(">>>> %s, tests %s", targetBundle, tests); } public void addError(Test test, Throwable t) { activator.trace(" add error to %s : %s", test, t); check(); fails++; errors++; } public void addFailure(Test test, AssertionFailedError t) { activator.trace(" add failure to %s : %s", test, t); check(); fails++; errors++; } public void startTest(Test test) { activator.trace(" >> %s", test); check(); Bundle b = targetBundle; if (b == null) b = FrameworkUtil.getBundle(test.getClass()); if (b != null) { BundleContext context = b.getBundleContext(); activator.trace("got bundle context %s from %s in state %s", context, b, b.getState() ); assert context != null; try { Method m = test.getClass().getMethod("setBundleContext", new Class[] { BundleContext.class }); m.setAccessible(true); m.invoke(test, new Object[] { context }); activator.trace("set context through setter"); } catch (Exception e) { Field f; try { f = test.getClass().getField("context"); f.set(test, context); activator.trace("set context in field"); } catch (Exception e1) { // Ok, no problem } } } fails = 0; systemOut.clear().capture(true).echo(true); systemErr.clear().capture(true).echo(true); } public void endTest(Test test) { activator.trace(" << %s, fails=%s", test, fails); systemOut.capture(false); systemErr.capture(false); if (fails > 0) { String sysout = systemOut.getContent(); String syserr = systemErr.getContent(); if (sysout != null) activator.trace("out: %s", sysout); if (syserr != null) { activator.trace("err: %s", syserr); } } check(); } public void end() { activator.trace("<<<<"); } public void aborted() { activator.trace("ABORTED"); out.println("ABORTED"); } protected void check() { } String[] getCaptured() { return new String[] { systemOut.getContent(), systemErr.getContent() }; } } bnd-1.50.0/biz.aQute.junit/src/aQute/junit/Tee.java0000644000175000017500000000144711656076535021631 0ustar drazzibdrazzibpackage aQute.junit; import java.io.*; public class Tee extends OutputStream { PrintStream oldStream; ByteArrayOutputStream buffer = new ByteArrayOutputStream(); boolean capture; boolean echo; public Tee(PrintStream oldOut) { oldStream = oldOut; } public PrintStream getStream() { return new PrintStream(this); } public void write(int character) throws IOException { if (capture) buffer.write(character); if (echo) oldStream.write(character); } public String getContent() { if (buffer.size() == 0) return null; return buffer.toString(); } public Tee clear() { buffer.reset(); return this; } public Tee capture(boolean capture) { this.capture = capture; return this; } public Tee echo(boolean echo) { this.echo = echo; return this; } } bnd-1.50.0/biz.aQute.junit/src/aQute/junit/runtime/0000755000175000017500000000000011656076535021726 5ustar drazzibdrazzibbnd-1.50.0/biz.aQute.junit/src/aQute/junit/runtime/Operation.java0000644000175000017500000000154711656076535024540 0ustar drazzibdrazzib/******************************************************************************* * Copyright (c) 2010 Neil Bartlett. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Neil Bartlett - initial API and implementation ******************************************************************************/ package aQute.junit.runtime; /** * Represents an operation against a service of type S yielding * a result of type R * * @author Neil Bartlett * * @param * The service type * @param * The result type */ public interface Operation { R perform(S service) throws Exception; }bnd-1.50.0/biz.aQute.junit/src/aQute/junit/runtime/OSGiTestCase.java0000644000175000017500000001374411656076535025037 0ustar drazzibdrazzib/******************************************************************************* * Copyright (c) 2010 Neil Bartlett. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Neil Bartlett - initial API and implementation ******************************************************************************/ package aQute.junit.runtime; import java.lang.reflect.*; import java.text.*; import java.util.*; import junit.framework.*; import org.osgi.framework.*; import org.osgi.util.tracker.*; public abstract class OSGiTestCase extends TestCase { /** * Returns the {@link BundleContext} for the current class. This method * should be called by subclasses as their point of entry into the OSGi * Framework, but it may return {@code null} if the class is not associated * by a bundle -- for example, if the Test is executed outside of an OSGi * Framework. * * @return The {@link BundleContext} of the receiver, or {@code null} if the */ protected BundleContext getBundleContext() { Bundle bundle = FrameworkUtil.getBundle(this.getClass()); return bundle != null ? bundle.getBundleContext() : null; } /** * Asserts that at least one service of the specified type is currently * available. If not, an {@link AssertionFailedError} is thrown. * * @param service * The service interface type. * @param filter * An additional service filter, which may be {@code null}. */ protected void assertSvcAvail(Class service, String filter) { assertSvcAvail(null, service, filter); } /** * Asserts that at least one service of the specified type is currently * available. If not, an {@link AssertionFailedError} is thrown with the * given message. * * @param message * @param service * The service interface type. * @param filter * An additional service filter, which may be {@code null}. */ protected void assertSvcAvail(String message, Class service, String filter) { BundleContext context = getBundleContext(); ServiceReference[] refs = null; try { refs = context.getServiceReferences(service.getName(), filter); } catch (InvalidSyntaxException e) { fail("Invalid filter syntax"); } if (refs == null || refs.length == 0) fail(message); Object svcObj = context.getService(refs[0]); if (svcObj == null) fail(message); try { if (!service.isInstance(svcObj)) fail(message); } finally { context.ungetService(refs[0]); } } /** *

* Perform the specified operation against a service, or fail immediately if * a matching service is not available. *

* *

* Example: *

* *

* Example: *

* *
	 * String	reply	= withService(HelloService.class, null, new Operation<HelloService, String>() {
	 * 					public String call(HelloService service) {
	 * 						return service.sayHello();
	 * 					}
	 * 				});
	 * 
* * @param * The service type. * @param * The result type. * @param service * The service class. * @param filter * An additional filter expression, or {@code null}. * @param timeout * The maximum time to wait (in milliseconds) for a service to * become available; a zero or negative timeout implies we should * fail if the service is not immediately available. * @param operation * The operation to perform against the service. * @return * @throws Exception */ protected R withService(Class service, String filter, Operation operation) throws Exception { return withService(service, filter, 0, operation); } /** *

* Perform the specified operation against a service, if available. *

* *

* Example: *

* *
	 * String	reply	= withService(HelloService.class, null, 0, new Operation<HelloService, String>() {
	 * 					public String call(HelloService service) {
	 * 						return service.sayHello();
	 * 					}
	 * 				});
	 * 
* * @param * The service type. * @param * The result type. * @param service * The service class. * @param filter * An additional filter expression, or {@code null}. * @param timeout * The maximum time to wait (in ms) for a service to become * available; a zero or negative timeout implies we should fail * if the service is not immediatelt available. * @param operation * The operation to perform against the service. * @return * @throws Exception */ protected R withService(Class service, String filter, long timeout, Operation operation) throws Exception { BundleContext context = getBundleContext(); ServiceTracker tracker = null; if (filter != null) { try { Filter combined = FrameworkUtil.createFilter("(" + Constants.OBJECTCLASS + "=" + service.getName() + ")"); tracker = new ServiceTracker(context, combined, null); } catch (InvalidSyntaxException e) { fail("Invalid filter syntax."); } } else { tracker = new ServiceTracker(context, service.getName(), null); } try { tracker.open(); Object instance; if (timeout <= 0) { instance = tracker.getService(); } else { instance = tracker.waitForService(timeout); } if (instance == null || !service.isInstance(instance)) fail(MessageFormat.format("Service \"{0}\" not available.", service.getName())); S casted = (S) instance; return operation.perform(casted); } catch (InterruptedException e) { fail("Interrupted."); } finally { tracker.close(); } // unreachable return null; } /** * Default wait timeout is 10 seconds */ public static long DEFAULT_TIMEOUT = 10000; }bnd-1.50.0/biz.aQute.junit/src/aQute/junit/runtime/VoidOperation.java0000644000175000017500000000132611656076535025355 0ustar drazzibdrazzib/******************************************************************************* * Copyright (c) 2010 Neil Bartlett. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Neil Bartlett - initial API and implementation ******************************************************************************/ package aQute.junit.runtime; public abstract class VoidOperation implements Operation { public final Object perform(S param) { doPerform(param); return null; } protected abstract void doPerform(S param); }bnd-1.50.0/biz.aQute.junit/src/aQute/junit/JunitXmlReport.java0000644000175000017500000001443111656076535024057 0ustar drazzibdrazzibpackage aQute.junit; import java.io.*; import java.net.*; import java.text.*; import java.util.*; import junit.framework.*; import org.osgi.framework.*; public class JunitXmlReport implements TestReporter { Tag testsuite = new Tag("testsuite"); Tag testcase; static String hostname; static DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"); long startTime; long testStartTime; int tests = 0; PrintWriter out; boolean finished; boolean progress; Bundle bundle; BasicTestReport basic; public class LogEntry { String clazz; String name; String message; } public JunitXmlReport(Writer report, Bundle bundle, BasicTestReport basic) throws Exception { if (hostname == null) hostname = InetAddress.getLocalHost().getHostName(); out = new PrintWriter(report); this.bundle = bundle; this.basic = basic; } public void setProgress(boolean progress) { this.progress = progress; } public void setup(Bundle fw, Bundle targetBundle) { startTime = System.currentTimeMillis(); testsuite.addAttribute("hostname", hostname); if (targetBundle != null) { testsuite.addAttribute("name", "test." + targetBundle.getSymbolicName()); testsuite.addAttribute("target", targetBundle.getLocation()); } else { testsuite.addAttribute("name", "test.run"); } testsuite.addAttribute("timestamp", df.format(new Date())); testsuite.addAttribute("framework", fw); testsuite.addAttribute("framework-version", fw.getVersion()); Tag properties = new Tag("properties"); testsuite.addContent(properties); for (Map.Entry entry : System.getProperties().entrySet()) { Tag property = new Tag(properties, "property"); property.addAttribute("name", entry.getKey()); property.addAttribute("value", entry.getValue()); } Tag bundles = new Tag(testsuite, "bundles"); Bundle bs[] = fw.getBundleContext().getBundles(); for (int i = 0; i < bs.length; i++) { Tag bundle = new Tag("bundle"); bundle.addAttribute("location", bs[i].getLocation()); bundle.addAttribute("modified", df.format(new Date(bs[i].getLastModified()))); bundle.addAttribute("state", bs[i].getState()); bundle.addAttribute("id", bs[i].getBundleId() + ""); bundle.addAttribute("bsn", bs[i].getSymbolicName()); bundle.addAttribute("version", bs[i].getVersion()); if (bs[i].equals(targetBundle)) bundle.addAttribute("target", "true"); bundles.addContent(bundle); } if (bundle != null) { String header = (String) targetBundle.getHeaders().get("Bnd-AddXMLToTest"); if (header != null) { StringTokenizer st = new StringTokenizer(header, " ,"); while (st.hasMoreTokens()) { String resource = st.nextToken(); URL url = targetBundle.getEntry(resource); if (url != null) { String name = url.getFile(); int n = name.lastIndexOf('/'); if (n < 0) n = 0; else n = n + 1; if (name.endsWith(".xml")) name = name.substring(n, name.length() - 4); else name = name.substring(n, name.length()).replace('.', '_'); testsuite.addContent(url); } else { Tag addxml = new Tag(testsuite, "error"); addxml.addAttribute("reason", "no such resource: " + resource); } } } } } public void begin(List classNames, int realcount) { } public void end() { if (!finished) { finished = true; testsuite.addAttribute("tests", tests); testsuite.addAttribute("time", getFraction(System.currentTimeMillis() - startTime, 1000)); testsuite.addAttribute("timestamp", df.format(new Date())); testsuite.print(0, out); out.close(); } } private String getFraction(long l, int i) { return (l / 1000) + "." + (l % 1000); } // public void startTest(Test test) { testcase = new Tag("testcase"); testsuite.addContent(testcase); testcase.addAttribute("classname", test.getClass().getName()); String nameAndClass = test.toString(); String name = nameAndClass; int n = nameAndClass.indexOf('('); if (n > 0 && nameAndClass.endsWith(")")) { name = nameAndClass.substring(0, n); } testcase.addAttribute("name", name); testStartTime = System.currentTimeMillis(); progress(name); } public void setTests(List flattened) { } // // java.lang.Exception: // at test.AnalyzerTest.testMultilevelInheritance(AnalyzerTest.java:47) // // public void addError(Test test, Throwable t) { Tag error = new Tag("error"); error.setCDATA(); error.addAttribute("type", t.getClass().getName()); error.addContent(getTrace(t)); if (testcase == null) testsuite.addContent(error); else testcase.addContent(error); progress(" e"); } private void progress(String s) { } private String getTrace(Throwable t) { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); pw.println(t.toString()); StackTraceElement ste[] = t.getStackTrace(); for (int i = 0; i < ste.length; i++) { pw.println("at " + ste[i].toString().trim()); } pw.close(); return sw.toString(); } // // junit.framework.AssertionFailedError // at test.AnalyzerTest.testFindClass(AnalyzerTest.java:25) // // // public void addFailure(Test test, AssertionFailedError t) { Tag failure = new Tag("failure"); failure.setCDATA(); failure.addAttribute("type", t.getClass().getName()); failure.addContent(getTrace(t)); testcase.addContent(failure); progress(" f"); } public void endTest(Test test) { String[] outs = basic.getCaptured(); if (outs[0] != null) { Tag sysout = new Tag(testcase, "sys-out"); sysout.addContent(outs[0]); } if (outs[1] != null) { Tag sysout = new Tag(testcase, "sys-err"); sysout.addContent(outs[1]); } testcase .addAttribute("time", getFraction(System.currentTimeMillis() - testStartTime, 1000)); } public void close() { end(); } public void aborted() { testsuite.addAttribute("aborted", "true"); close(); } public void addTag(Tag tag) { testsuite.addContent(tag); } }bnd-1.50.0/biz.aQute.junit/src/aQute/junit/Activator.java0000644000175000017500000002256011656076535023047 0ustar drazzibdrazzibpackage aQute.junit; import java.io.*; import java.lang.reflect.*; import java.net.*; import java.util.*; import junit.framework.*; import org.osgi.framework.*; import aQute.junit.constants.*; public class Activator extends Thread implements BundleActivator, TesterConstants { BundleContext context; volatile boolean active; int port = -1; String reportPath; boolean continuous = false; boolean trace = false; PrintStream out = System.err; JUnitEclipseReport jUnitEclipseReport; public Activator() { super("bnd Runtime Test Bundle"); } public void start(BundleContext context) throws Exception { this.context = context; active = true; start(); } public void stop(BundleContext context) throws Exception { active = false; if ( jUnitEclipseReport != null) jUnitEclipseReport.close(); interrupt(); join(10000); } public void run() { continuous = Boolean.valueOf(context.getProperty(TESTER_CONTINUOUS)); trace = context.getProperty(TESTER_TRACE) != null; String testcases = context.getProperty(TESTER_NAMES); if (context.getProperty(TESTER_PORT) != null) { port = Integer.parseInt(context.getProperty(TESTER_PORT)); try { jUnitEclipseReport = new JUnitEclipseReport(port); } catch (Exception e) { System.err.println("Cannot create link Eclipse JUnit on port " + port); System.exit(-2); } } if (testcases == null) { trace("automatic testing of all bundles with Test-Cases header"); automatic(); } else { trace("receivednames of classes to test %s", testcases); try { int errors = test(null, testcases, null); System.exit(errors); } catch (Exception e) { e.printStackTrace(); System.exit(-2); } } } void automatic() { String testerDir = context.getProperty(TESTER_DIR); if ( testerDir == null) testerDir ="testdir"; final File reportDir = new File(testerDir); final List queue = new Vector(); trace( "using %s, needed creation %s", reportDir, reportDir.mkdirs()); trace("adding Bundle Listener for getting test bundle events"); context.addBundleListener(new SynchronousBundleListener() { public void bundleChanged(BundleEvent event) { if (event.getType() == BundleEvent.STARTED) { checkBundle(queue, event.getBundle()); } } }); for (Bundle b : context.getBundles()) { checkBundle(queue, b); } trace("starting queue"); int result = 0; outer: while (active) { Bundle bundle; synchronized (queue) { while (queue.isEmpty() && active) { try { queue.wait(); } catch (InterruptedException e) { trace("tests bundle queue interrupted"); interrupt(); break outer; } } } try { bundle = (Bundle) queue.remove(0); trace("received bundle to test: %s", bundle.getLocation()); Writer report = getReportWriter(reportDir, bundle); try { trace("test will run"); result += test(bundle, (String) bundle.getHeaders().get("Test-Cases"), report); trace("test ran"); if ( queue.isEmpty() && !continuous) { trace( "queue " + queue ); System.exit(result); } } finally { if (report != null) report.close(); } } catch (Exception e) { error("Not sure what happened anymore %s", e); System.exit(-2); } } } private void checkBundle(List queue, Bundle bundle) { if (bundle.getState() == Bundle.ACTIVE) { String testcases = (String) bundle.getHeaders().get("Test-Cases"); if (testcases != null) { trace("found active bundle with test cases %s : %s", bundle, testcases); synchronized (queue) { queue.add(bundle); queue.notifyAll(); } } } } private Writer getReportWriter(File reportDir, Bundle bundle) throws IOException { if (reportDir.isDirectory()) { Version v = bundle.getVersion(); File f = new File(reportDir, "TEST-" + bundle.getSymbolicName() + "-" + v.getMajor() + "." + v.getMinor() + "." + v.getMicro() + ".xml"); return new FileWriter(f); } return null; } /** * The main test routine. * * @param bundle * The bundle under test or null * @param testnames * The names to test * @param report * The report writer or null * @return # of errors */ int test(Bundle bundle, String testnames, Writer report) { trace("testing bundle %s with %s", bundle, testnames); Bundle fw = context.getBundle(0); try { List names = new ArrayList(); StringTokenizer st = new StringTokenizer(testnames, " ,"); while (st.hasMoreTokens()) names.add(st.nextToken()); List reporters = new ArrayList(); final TestResult result = new TestResult(); Tee systemErr; Tee systemOut; systemOut = new Tee(System.out); systemErr = new Tee(System.err); systemOut.capture(trace).echo(true); systemErr.capture(trace).echo(true); System.setOut(systemOut.getStream()); System.setErr(systemErr.getStream()); trace("changed streams"); try { BasicTestReport basic = new BasicTestReport(this, systemOut, systemErr) { public void check() { if (!active) result.stop(); } }; add(reporters, result, basic); if (port > 0) { add(reporters, result, jUnitEclipseReport); } if (report != null) { add(reporters, result, new JunitXmlReport(report, bundle, basic)); } for (TestReporter tr : reporters) { tr.setup(fw,bundle); } try { TestSuite suite = createSuite(bundle, names, result); trace("created suite " + suite); List flattened = new ArrayList(); int realcount = flatten(flattened, suite); for (TestReporter tr : reporters) { tr.begin(flattened, realcount); } trace("running suite " + suite); suite.run(result); } catch (Throwable t) { trace( t.getMessage()); result.addError(null, t); } finally { for (TestReporter tr : reporters) { tr.end(); } } } catch(Throwable t) { System.out.println("exiting " + t); t.printStackTrace(); } finally { System.setOut(systemOut.oldStream); System.setErr(systemErr.oldStream); trace("unset streams"); } System.err.println("Errors: " + result.errorCount()); System.err.println("Failures: " + result.failureCount()); return result.errorCount() + result.failureCount(); } catch (Exception e) { e.printStackTrace(); } return -1; } private TestSuite createSuite(Bundle tfw, List testNames, TestResult result) throws Exception { TestSuite suite = new TestSuite(); for (String fqn : testNames) { try { int n = fqn.indexOf(':'); if (n > 0) { String method = fqn.substring(n + 1); fqn = fqn.substring(0, n); Class clazz = loadClass(tfw, fqn); suite.addTest(TestSuite.createTest(clazz, method)); } else { Class clazz = loadClass(tfw, fqn); suite.addTestSuite(clazz); } } catch (Throwable e) { System.err.println("Can not create test case for: " + fqn + " : " + e); result.addError(suite, e); } } return suite; } private Class loadClass(Bundle tfw, String fqn) { if (tfw != null) try { return tfw.loadClass(fqn); } catch (ClassNotFoundException e1) { return null; } Bundle bundles[] = context.getBundles(); for (int i = bundles.length - 1; i >= 0; i--) { try { return bundles[i].loadClass(fqn); } catch (Exception e) { // Ignore, looking further } } return null; } public int flatten(List list, TestSuite suite) { int realCount = 0; for (Enumeration e = suite.tests(); e.hasMoreElements();) { Test test = (Test) e.nextElement(); list.add(test); if (test instanceof TestSuite) realCount += flatten(list, (TestSuite) test); else realCount++; } return realCount; } private void add(List reporters, TestResult result, TestReporter rp) { reporters.add(rp); result.addListener(rp); } static public String replace(String source, String symbol, String replace) { StringBuffer sb = new StringBuffer(source); int n = sb.indexOf(symbol, 0); while (n > 0) { sb.replace(n, n + symbol.length(), replace); n = n - symbol.length() + replace.length(); n = sb.indexOf(replace, n); } return sb.toString(); } public void trace(String msg, Object... objects) { if (trace) { message("# ", msg, objects); } } private void message(String prefix, String string, Object[] objects) { Throwable e = null; StringBuffer sb = new StringBuffer(); int n = 0; sb.append(prefix); for (int i = 0; i < string.length(); i++) { char c = string.charAt(i); if (c == '%') { c = string.charAt(++i); switch (c) { case 's': if (n < objects.length) { Object o = objects[n++]; if (o instanceof Throwable) { e = (Throwable) o; if (o instanceof InvocationTargetException) { Throwable t = (InvocationTargetException) o; sb.append(t.getMessage()); e = t; } else sb.append(e.getMessage()); } else { sb.append(o); } } else sb.append(""); break; default: sb.append(c); } } else { sb.append(c); } } out.println(sb); if (e != null && trace) e.printStackTrace(out); } public void error(String msg, Object... objects) { message("! ", msg, objects); } static void main() throws URISyntaxException { URI uri = new URI("/abc/def"); } } bnd-1.50.0/biz.aQute.junit/src/aQute/junit/plugin/0000755000175000017500000000000011656076535021541 5ustar drazzibdrazzibbnd-1.50.0/biz.aQute.junit/src/aQute/junit/plugin/ProjectTesterImpl.java0000644000175000017500000000321511656076535026024 0ustar drazzibdrazzibpackage aQute.junit.plugin; import java.util.*; import aQute.bnd.build.*; import aQute.bnd.service.*; import aQute.junit.constants.*; import aQute.lib.osgi.*; public class ProjectTesterImpl extends ProjectTester implements TesterConstants, EclipseJUnitTester { int port = -1; String host; Project project; String report; boolean prepared; public ProjectTesterImpl(Project project) throws Exception { super(project); this.project = project; } public boolean prepare() throws Exception { if (!prepared) { prepared = true; super.prepare(); ProjectLauncher launcher = getProjectLauncher(); if (port > 0) { launcher.getRunProperties().put(TESTER_PORT, "" + port); if (host != null) launcher.getRunProperties().put(TESTER_HOST, "" + host); } launcher.getRunProperties().put(TESTER_DIR, getReportDir().getAbsolutePath()); launcher.getRunProperties().put(TESTER_CONTINUOUS, "" + getContinuous()); if ( Processor.isTrue(project.getProperty(Constants.RUNTRACE))) launcher.getRunProperties().put(TESTER_TRACE, "true"); Collection testnames = getTests(); if (testnames.size() > 0) { launcher.getRunProperties().put(TESTER_NAMES, Processor.join(testnames)); } // This is only necessary because we might be picked // as default and that implies we're not on the -testpath launcher.addDefault(Constants.DEFAULT_TESTER_BSN); launcher.prepare(); } return true; } public int test() throws Exception { prepare(); return getProjectLauncher().launch(); } public void setHost(String host) { this.host = host; } public void setPort(int port) { this.port = port; } } bnd-1.50.0/biz.aQute.junit/src/aQute/junit/TestReporter.java0000644000175000017500000000044211656076535023550 0ustar drazzibdrazzibpackage aQute.junit; import java.util.*; import junit.framework.*; import org.osgi.framework.*; public interface TestReporter extends TestListener { void setup(Bundle framework, Bundle targetBundle); void begin( List tests, int realcount); void aborted(); void end(); } bnd-1.50.0/biz.aQute.junit/src/aQute/junit/Tag.java0000755000175000017500000002624511656076535021635 0ustar drazzibdrazzibpackage aQute.junit; import java.io.*; import java.net.*; import java.text.*; import java.util.*; /** * The Tag class represents a minimal XML tree. It consist of a named element * with a hashtable of named attributes. Methods are provided to walk the tree * and get its constituents. The content of a Tag is a list that contains String * objects or other Tag objects. */ public class Tag { Tag parent; // Parent element String name; // Name of the tag Hashtable attributes = new Hashtable(); // Attributes name -> value Vector content = new Vector(); // Content elements boolean cdata; static SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss.SSS"); /** * Construct a new Tag with a name. */ public Tag(String name) { this.name = name; } /** * Construct a new Tag with a name. */ public Tag(String name, Hashtable attributes) { this.name = name; this.attributes = attributes; } /** * Construct a new Tag with a name and a set of attributes. The attributes * are given as ( name, value ) ... */ public Tag(String name, String[] attributes) { this.name = name; for (int i = 0; i < attributes.length; i += 2) addAttribute(attributes[i], attributes[i + 1]); } /** * Construct a new Tag with a single string as content. */ public Tag(String name, String content) { this.name = name; addContent(content); } public Tag(Tag testsuite, String name) { this(name); testsuite.addContent(this); } /** * Add a new attribute. */ public void addAttribute(String key, String value) { attributes.put(key, value); } /** * Add a new attribute. */ public void addAttribute(String key, Object value) { if (value == null) return; attributes.put(key, value.toString()); } /** * Add a new attribute. */ public void addAttribute(String key, int value) { attributes.put(key, Integer.toString(value)); } /** * Add a new date attribute. The date is formatted as the SimpleDateFormat * describes at the top of this class. */ public void addAttribute(String key, Date value) { attributes.put(key, format.format(value)); } /** * Add a new content string. */ public void addContent(String string) { content.addElement(string); } /** * Add a new content tag. */ public void addContent(Tag tag) { content.addElement(tag); tag.parent = this; } /** * Return the name of the tag. */ public String getName() { return name; } /** * Return the attribute value. */ public String getAttribute(String key) { return (String) attributes.get(key); } /** * Return the attribute value or a default if not defined. */ public String getAttribute(String key, String deflt) { String answer = getAttribute(key); return answer == null ? deflt : answer; } /** * Answer the attributes as a Dictionary object. */ public Dictionary getAttributes() { return attributes; } /** * Return the contents. */ public Vector getContents() { return content; } /** * Return a string representation of this Tag and all its children * recursively. */ public String toString() { StringWriter sw = new StringWriter(); print(0, new PrintWriter(sw)); return sw.toString(); } /** * Return only the tags of the first level of descendants that match the * name. */ public Vector getContents(String tag) { Vector out = new Vector(); for (Enumeration e = content.elements(); e.hasMoreElements();) { Object o = e.nextElement(); if (o instanceof Tag && ((Tag) o).getName().equals(tag)) out.addElement(o); } return out; } /** * Return the whole contents as a String (no tag info and attributes). */ public String getContentsAsString() { StringBuffer sb = new StringBuffer(); getContentsAsString(sb); return sb.toString(); } /** * convenient method to get the contents in a StringBuffer. */ public void getContentsAsString(StringBuffer sb) { for (Enumeration e = content.elements(); e.hasMoreElements();) { Object o = e.nextElement(); if (o instanceof Tag) ((Tag) o).getContentsAsString(sb); else sb.append(o.toString()); } } /** * Print the tag formatted to a PrintWriter. */ public void print(int indent, PrintWriter pw) { pw.print("\n"); spaces(pw, indent); pw.print('<'); pw.print(name); for (Enumeration e = attributes.keys(); e.hasMoreElements();) { String key = (String) e.nextElement(); String value = escape((String) attributes.get(key)); pw.print(' '); pw.print(key); pw.print("="); String quote = "'"; if (value.indexOf(quote) >= 0) quote = "\""; pw.print(quote); pw.print(value); pw.print(quote); } if (content.size() == 0) pw.print('/'); else { pw.print('>'); for (Enumeration e = content.elements(); e.hasMoreElements();) { Object content = e.nextElement(); if (content instanceof String) { if (cdata) { pw.print(" // specifier, so clean it up int l = sb.indexOf("]]>"); while ( l >=0) { sb.insert(l+2, '\\'); l = sb.indexOf("]]>", l+2); } pw.print(sb); pw.print("]]>"); } else formatted(pw, indent + 2, 60, escape((String) content)); } else if (content instanceof Tag) { Tag tag = (Tag) content; tag.print(indent + 2, pw); } else if (content instanceof URL) { copyURL(pw, (URL) content); } } pw.print("\n"); spaces(pw, indent); pw.print("'); } private void copyURL(PrintWriter pw, URL url) { try { InputStream in = url.openStream(); BufferedReader rdr = new BufferedReader(new InputStreamReader(in, "UTF8")); try { String line = rdr.readLine(); if (line != null) { while (line.trim().startsWith(" width - 3)) { pw.print("\n"); spaces(pw, left); pos = 0; } switch (c) { case '<': pw.print("<"); pos += 4; break; case '>': pw.print(">"); pos += 4; break; case '&': pw.print("&"); pos += 5; break; default: pw.print(c); pos++; break; } } } /** * Escape a string, do entity conversion. */ String escape(String s) { StringBuffer sb = new StringBuffer(); for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); switch (c) { case '<': sb.append("<"); break; case '>': sb.append(">"); break; case '&': sb.append("&"); break; default: sb.append(c); break; } } return sb.toString(); } /** * Make spaces. */ void spaces(PrintWriter pw, int n) { while (n-- > 0) pw.print(' '); } /** * root/preferences/native/os */ public Tag[] select(String path) { return select(path, (Tag) null); } public Tag[] select(String path, Tag mapping) { Vector v = new Vector(); select(path, v, mapping); Tag[] result = new Tag[v.size()]; v.copyInto(result); return result; } void select(String path, Vector results, Tag mapping) { if (path.startsWith("//")) { int i = path.indexOf('/', 2); String name = path.substring(2, i < 0 ? path.length() : i); for (Enumeration e = content.elements(); e.hasMoreElements();) { Object o = e.nextElement(); if (o instanceof Tag) { Tag child = (Tag) o; if (match(name, child, mapping)) results.add(child); child.select(path, results, mapping); } } return; } if (path.length() == 0) { results.addElement(this); return; } int i = path.indexOf("/"); String elementName = path; String remainder = ""; if (i > 0) { elementName = path.substring(0, i); remainder = path.substring(i + 1); } for (Enumeration e = content.elements(); e.hasMoreElements();) { Object o = e.nextElement(); if (o instanceof Tag) { Tag child = (Tag) o; if (child.getName().equals(elementName) || elementName.equals("*")) child.select(remainder, results, mapping); } } } public boolean match(String search, Tag child, Tag mapping) { String target = child.getName(); String sn = null; String tn = null; if (search.equals("*")) return true; int s = search.indexOf(':'); if (s > 0) { sn = search.substring(0, s); search = search.substring(s + 1); } int t = target.indexOf(':'); if (t > 0) { tn = target.substring(0, t); target = target.substring(t + 1); } if (!search.equals(target)) // different tag names return false; if (mapping == null) { return tn == sn || (sn != null && sn.equals(tn)); } else { String suri = sn == null ? mapping.getAttribute("xmlns") : mapping .getAttribute("xmlns:" + sn); String turi = tn == null ? child.findRecursiveAttribute("xmlns") : child.findRecursiveAttribute("xmlns:" + tn); return turi == suri || (turi != null && suri != null && turi.equals(suri)); } } public String getString(String path) { String attribute = null; int index = path.indexOf("@"); if (index >= 0) { // attribute attribute = path.substring(index + 1); if (index > 0) { // prefix path path = path.substring(index - 1); // skip -1 } else path = ""; } Tag tags[] = select(path); StringBuffer sb = new StringBuffer(); for (int i = 0; i < tags.length; i++) { if (attribute == null) tags[i].getContentsAsString(sb); else sb.append(tags[i].getAttribute(attribute)); } return sb.toString(); } public String getStringContent() { StringBuffer sb = new StringBuffer(); for (Enumeration e = content.elements(); e.hasMoreElements();) { Object c = e.nextElement(); if (!(c instanceof Tag)) sb.append(c); } return sb.toString(); } public String getNameSpace() { return getNameSpace(name); } public String getNameSpace(String name) { int index = name.indexOf(':'); if (index > 0) { String ns = name.substring(0, index); return findRecursiveAttribute("xmlns:" + ns); } else return findRecursiveAttribute("xmlns"); } public String findRecursiveAttribute(String name) { String value = getAttribute(name); if (value != null) return value; if (parent != null) return parent.findRecursiveAttribute(name); return null; } public String getLocalName() { int index = name.indexOf(':'); if (index <= 0) return name; return name.substring(index + 1); } public void rename(String string) { name = string; } public void addContent(URL url) { content.add(url); } public void setCDATA() { cdata = true; } } bnd-1.50.0/biz.aQute.junit/src/aQute/junit/JUnitEclipseReport.java0000644000175000017500000000713111656076535024642 0ustar drazzibdrazzibpackage aQute.junit; import java.io.*; import java.lang.reflect.*; import java.net.*; import java.util.*; import junit.framework.*; import org.osgi.framework.*; public class JUnitEclipseReport implements TestReporter { int port; boolean open; BufferedReader in; PrintWriter out; long startTime; Bundle targetBundle; List tests; boolean verbose = false; Test current; public JUnitEclipseReport(int port) throws Exception { Socket socket = null; for (int i = 0; socket == null && i < 10; i++) { try { socket = new Socket("127.0.0.1", port); } catch (ConnectException ce) { Thread.sleep(i * 100); } } if (socket == null) { System.err.println("Cannot open the JUnit Port: " + port); System.exit(-2); } in = new BufferedReader(new InputStreamReader(socket.getInputStream(), "UTF-8")); out = new PrintWriter(new OutputStreamWriter(socket.getOutputStream(), "UTF-8")); } public void setup(Bundle fw, Bundle targetBundle) { this.targetBundle = targetBundle; } public void begin(List tests, int realcount) { this.tests = tests; message("%TESTC ", realcount + " v2"); report(tests); startTime = System.currentTimeMillis(); } public void end() { message("%RUNTIME", "" + (System.currentTimeMillis() - startTime)); out.flush(); out.close(); } public void addError(Test test, Throwable t) { message("%ERROR ", test); trace(t); } public void addFailure(Test test, AssertionFailedError t) { message("%FAILED ", test); trace(t); } void trace(Throwable t) { message("%TRACES ", ""); t.printStackTrace(out); out.println(); message("%TRACEE ", ""); } public void endTest(Test test) { message("%TESTE ", test); } public void startTest(Test test) { this.current = test; message("%TESTS ", test); try { Method m = test.getClass().getMethod("setBundleContext", new Class[] { BundleContext.class }); m.invoke(test, new Object[] { targetBundle.getBundleContext() }); } catch (Exception e) { } } private void message(String key, String payload) { if (key.length() != 8) throw new IllegalArgumentException(key + " is not 8 characters"); out.print(key); out.println(payload); out.flush(); if (verbose) System.out.println(key + payload); } private void message(String key, Test test) { if ( tests == null ) message(key, "?,"+test); else message(key, (tests.indexOf(test) + 1) + "," + test); } private void report(List flattened) { for (int i = 0; i < flattened.size(); i++) { StringBuffer sb = new StringBuffer(); sb.append(i + 1); sb.append(","); Test test = (Test) flattened.get(i); sb.append(flattened.get(i)); sb.append(","); sb.append(test instanceof TestSuite); sb.append(","); sb.append(test.countTestCases()); message("%TSTTREE", sb.toString()); } } public void aborted() { end(); } public void close() { try { in.close(); } catch (Exception ioe) { // ignore } } } bnd-1.50.0/biz.aQute.junit/src/aQute/junit/constants/0000755000175000017500000000000011656076535022257 5ustar drazzibdrazzibbnd-1.50.0/biz.aQute.junit/src/aQute/junit/constants/TesterConstants.java0000644000175000017500000000227211656076535026270 0ustar drazzibdrazzibpackage aQute.junit.constants; public interface TesterConstants { /** * The port to send the JUnit information to in a format defined by Eclipse. * If this property is not set, no information is send but tests are still * run. */ String TESTER_PORT = "tester.port"; /** * The host to send the JUnit information to in a formated defined by * Eclipse. If this property is not set localhost is assumed. */ String TESTER_HOST = "tester.host"; /** * Fully qualified names of classes to test. If this property is null * automatic mode is chosen, otherwise these classes are going to be tested * and then the test ends. */ String TESTER_NAMES = "tester.names"; /** * A directory to put the test reports. If the directory does not exist, no * reports are generated. The default is tester-dir. */ String TESTER_DIR = "tester.dir"; /** * In automatic mode, no {@link #TESTER_NAMES} set, continue watching the * bundles and re-run a bundle's tests when it is started. */ String TESTER_CONTINUOUS = "tester.continuous"; /** * Trace the test framework in detail. Default is false, must be set to true * or false. */ String TESTER_TRACE = "tester.trace"; } bnd-1.50.0/biz.aQute.junit/README0000644000175000017500000000015711656076535016127 0ustar drazzibdrazzibThe junit project is a plugin that extends the ProjectTester.java class to run OSGi tests inside a framework. bnd-1.50.0/biz.aQute.junit/.settings/0000755000175000017500000000000011656076535017162 5ustar drazzibdrazzibbnd-1.50.0/biz.aQute.junit/.settings/org.eclipse.jdt.core.prefs0000644000175000017500000000116011656076535024142 0ustar drazzibdrazzib#Tue May 25 12:16:34 CEST 2010 eclipse.preferences.version=1 org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled org.eclipse.jdt.core.compiler.codegen.targetPlatform=jsr14 org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve org.eclipse.jdt.core.compiler.compliance=1.5 org.eclipse.jdt.core.compiler.debug.lineNumber=generate org.eclipse.jdt.core.compiler.debug.localVariable=generate org.eclipse.jdt.core.compiler.debug.sourceFile=generate org.eclipse.jdt.core.compiler.problem.assertIdentifier=warning org.eclipse.jdt.core.compiler.problem.enumIdentifier=warning org.eclipse.jdt.core.compiler.source=1.5 bnd-1.50.0/biz.aQute.junit/.settings/org.eclipse.core.resources.prefs0000644000175000017500000000012511656076535025373 0ustar drazzibdrazzib#Mon Sep 19 11:00:09 EDT 2005 eclipse.preferences.version=1 encoding/=UTF-8 bnd-1.50.0/biz.aQute.junit/.settings/org.eclipse.core.runtime.prefs0000644000175000017500000000011611656076535025044 0ustar drazzibdrazzib#Tue Dec 14 12:22:25 EST 2010 eclipse.preferences.version=1 line.separator=\n bnd-1.50.0/cnf/0000755000175000017500000000000011656076535013020 5ustar drazzibdrazzibbnd-1.50.0/cnf/releaserepo/0000755000175000017500000000000011656076535015326 5ustar drazzibdrazzibbnd-1.50.0/cnf/releaserepo/repository.xml0000644000175000017500000000020611656076535020265 0ustar drazzibdrazzib bnd-1.50.0/cnf/build.xml0000644000175000017500000001363111656076535014645 0ustar drazzibdrazzib Enter project ${project.name} verbose: ${verbose} project.name: ${project.name} project.output: ${project.output} project.sourcepath: ${project.sourcepath} project.allsourcepath: ${project.allsourcepath} project.buildpath: ${project.buildpath} project.testpath: ${project.testpath} project.dependson: ${project.dependson} project.bootclasspath: ${project.bootclasspath} javac: ${javac} p: ${p} btool.manifestVersion: ${btool.manifestVersion} btool.analyse: ${btool.analyse} btool.showmanifest: ${btool.showmanifest} btool.noversion: ${btool.noversion} btool.sources: ${btool.sources} btool.noextraheaders: ${btool.noextraheaders} jars.compile.order: ${jars.compile.order} bin.includes: ${bin.includes} base.modfied: ${base.modified} (${base.modified.readable}) target: ${target} release.target: ${release.target} licensed repo: ${licensed-repo} repo: ${repo} releaserepo: ${releaserepo} use.bnd: ${use.bnd} nodeploy: ${nodeploy} -dependson: ${-dependson} bnd-1.50.0/cnf/build.bnd0000644000175000017500000000411611656076535014606 0ustar drazzibdrazzib# We use git Git-Descriptor: ${system;git describe --dirty --always} Git-SHA: ${system;git rev-list -1 HEAD} Bundle-SCM = git://github.com/bndtools/bnd.git # Very general project.dependson = ${p-dependson;:} project.bootclasspath = ${p-bootclasspath;:} project.buildpath = ${p-buildpath;:} project.sourcepath = ${p-sourcepath;:} project.allsourcepath = ${p-allsourcepath;:} project.output = ${p-output} project.testpath = ${p-testpath;:} -verbose = true project = ${basedir} src = src bin = bin target = ${project}/${target-dir} build = ${workspace}/cnf repo = ${build}/repo releaserepo = ${workspace}/../repo/bundles target-dir = tmp p = ${basename;${project}} project.name = ${p} # Java compiler options java = java javac = javac javac.debug = on javac.source = 1.5 javac.target = 1.5 # default version policies # -provider-policy = ${range;[==,=+)} # -consumer-policy = ${range;[==,+)} #Bnd options -sources = true -sourcepath = ${project}/src -plugin = \ aQute.lib.deployer.FileRepo;name='Main';location=${repo},\ aQute.lib.deployer.FileRepo;name='Release';location=${releaserepo} -releaserepo: Release -make = \ (*).(jar); type=bnd; recipe="bnd/$1.bnd" copyright = Copyright (c) aQute (2000, ${tstamp;yyyy}). All Rights Reserved. copyright.html = Copyright © aQute (2000, ${tstamp;yyyy}). All Rights Reserved. # Documentation Bundle-Vendor: aQute SARL http://www.aQute.biz Bundle-Copyright: All files contained in this JAR are licensed under the Apache 2.0 license, unless noted differently in their source (see swing2swt). Bundle-License: http://www.opensource.org/licenses/apache2.0.php; \ description="${Bundle-Copyright}"; \ link=LICENSE -removeheader = Include-Resource -runpath = \ org.eclipse.osgi; version=3.5,\ com.springsource.junit; export="junit.framework;version=3.8" bnd-1.50.0/cnf/.project0000644000175000017500000000030411656076535014464 0ustar drazzibdrazzib cnf bnd-1.50.0/cnf/repo/0000755000175000017500000000000011656076535013765 5ustar drazzibdrazzibbnd-1.50.0/cnf/repo/org.eclipse.jdt.launching/0000755000175000017500000000000011656076535020726 5ustar drazzibdrazzibbnd-1.50.0/cnf/repo/org.eclipse.debug.ui/0000755000175000017500000000000011656076535017700 5ustar drazzibdrazzibbnd-1.50.0/cnf/repo/org.eclipse.ui.editors/0000755000175000017500000000000011656076535020263 5ustar drazzibdrazzibbnd-1.50.0/cnf/repo/org.apache.felix.webconsole/0000755000175000017500000000000011656076535021241 5ustar drazzibdrazzibbnd-1.50.0/cnf/repo/bndtools.bndplugins.analysis/0000755000175000017500000000000011656076535021577 5ustar drazzibdrazzibbnd-1.50.0/cnf/repo/org.eclipse.equinox.ds/0000755000175000017500000000000011656076535020273 5ustar drazzibdrazzibbnd-1.50.0/cnf/repo/org.eclipse.jdt.debug.ui/0000755000175000017500000000000011656076535020460 5ustar drazzibdrazzibbnd-1.50.0/cnf/repo/org.eclipse.gemini.dbaccess.derby.cs/0000755000175000017500000000000011656076535022724 5ustar drazzibdrazzibbnd-1.50.0/cnf/repo/ee.minimum/0000755000175000017500000000000011656076535016030 5ustar drazzibdrazzibbnd-1.50.0/cnf/repo/org.eclipse.ui.ide/0000755000175000017500000000000011656076535017353 5ustar drazzibdrazzibbnd-1.50.0/cnf/repo/org.apache.felix.shell/0000755000175000017500000000000011656076535020210 5ustar drazzibdrazzibbnd-1.50.0/cnf/repo/org.apache.felix.ipojo.arch/0000755000175000017500000000000011656076535021135 5ustar drazzibdrazzibbnd-1.50.0/cnf/repo/org.eclipse.jdt.core/0000755000175000017500000000000011656076535017706 5ustar drazzibdrazzibbnd-1.50.0/cnf/repo/org.eclipse.ui.workbench/0000755000175000017500000000000011656076535020574 5ustar drazzibdrazzibbnd-1.50.0/cnf/repo/org.apache.felix.configadmin/0000755000175000017500000000000011656076535021357 5ustar drazzibdrazzibbnd-1.50.0/cnf/repo/osgi.cmpn/0000755000175000017500000000000011656076535015662 5ustar drazzibdrazzibbnd-1.50.0/cnf/repo/org.eclipse.equinox.metatype/0000755000175000017500000000000011656076535021515 5ustar drazzibdrazzibbnd-1.50.0/cnf/repo/org.apache.felix.shell.tui/0000755000175000017500000000000011656076535021010 5ustar drazzibdrazzibbnd-1.50.0/cnf/repo/osgi.core/0000755000175000017500000000000011656076535015655 5ustar drazzibdrazzibbnd-1.50.0/cnf/repo/ee.j2se/0000755000175000017500000000000011656076535015220 5ustar drazzibdrazzibbnd-1.50.0/cnf/repo/org.eclipse.osgi/0000755000175000017500000000000011656076535017137 5ustar drazzibdrazzibbnd-1.50.0/cnf/repo/org.eclipse.osgi/configuration/0000755000175000017500000000000011656076535022006 5ustar drazzibdrazzibbnd-1.50.0/cnf/repo/org.eclipse.osgi/configuration/org.eclipse.osgi/0000755000175000017500000000000011656076535025160 5ustar drazzibdrazzibbnd-1.50.0/cnf/repo/org.eclipse.osgi/configuration/org.eclipse.osgi/.manager/0000755000175000017500000000000011656076535026650 5ustar drazzibdrazzibbnd-1.50.0/cnf/repo/org.eclipse.osgi/configuration/org.eclipse.osgi/.manager/.fileTable.20000644000175000017500000000011411656076535030674 0ustar drazzibdrazzib#safe table #Fri Jun 12 15:35:03 CEST 2009 .state=0 .lazy=0 .crcca867930.v1 bnd-1.50.0/cnf/repo/org.eclipse.osgi/configuration/org.eclipse.osgi/.manager/.fileTable.10000644000175000017500000000010411656076535030672 0ustar drazzibdrazzib#safe table #Fri Jun 12 15:35:03 CEST 2009 .state=0 .crcb5f44ec2.v1 bnd-1.50.0/cnf/repo/org.eclipse.osgi/configuration/org.eclipse.osgi/.manager/.fileTableLock0000644000175000017500000000000011656076535031337 0ustar drazzibdrazzibbnd-1.50.0/cnf/repo/org.objectweb.asm/0000755000175000017500000000000011656076535017276 5ustar drazzibdrazzibbnd-1.50.0/cnf/repo/biz.aQute.bnd/0000755000175000017500000000000011656076535016371 5ustar drazzibdrazzibbnd-1.50.0/cnf/repo/org.glassfish.javax.servlet/0000755000175000017500000000000011656076535021331 5ustar drazzibdrazzibbnd-1.50.0/cnf/repo/org.eclipse.text/0000755000175000017500000000000011656076535017162 5ustar drazzibdrazzibbnd-1.50.0/cnf/repo/xorg.eclipse.swt.win/0000755000175000017500000000000011656076535017777 5ustar drazzibdrazzibbnd-1.50.0/cnf/repo/bndtools.runtime.junit/0000755000175000017500000000000011656076535020423 5ustar drazzibdrazzibbnd-1.50.0/cnf/repo/org.eclipse.equinox.supplement/0000755000175000017500000000000011656076535022061 5ustar drazzibdrazzibbnd-1.50.0/cnf/repo/org.osgi.ee.minimum/0000755000175000017500000000000011656076535017556 5ustar drazzibdrazzibbnd-1.50.0/cnf/repo/osgi.enterprise/0000755000175000017500000000000011656076535017105 5ustar drazzibdrazzibbnd-1.50.0/cnf/repo/org.eclipse.jface/0000755000175000017500000000000011656076535017246 5ustar drazzibdrazzibbnd-1.50.0/cnf/repo/biz.aQute.runtime/0000755000175000017500000000000011656076535017311 5ustar drazzibdrazzibbnd-1.50.0/cnf/repo/org.apache.felix.gogo.commands/0000755000175000017500000000000011656076535021634 5ustar drazzibdrazzibbnd-1.50.0/cnf/repo/biz.aQute.bnd.annotation/0000755000175000017500000000000011656076535020542 5ustar drazzibdrazzibbnd-1.50.0/cnf/repo/org.osgi.impl.bundle.servlet/0000755000175000017500000000000011656076535021407 5ustar drazzibdrazzibbnd-1.50.0/cnf/repo/com.vaadin/0000755000175000017500000000000011656076535016004 5ustar drazzibdrazzibbnd-1.50.0/cnf/repo/org.eclipse.core.runtime/0000755000175000017500000000000011656076535020610 5ustar drazzibdrazzibbnd-1.50.0/cnf/repo/org.apache.bcel/0000755000175000017500000000000011656076535016700 5ustar drazzibdrazzibbnd-1.50.0/cnf/repo/org.easymock/0000755000175000017500000000000011656076535016366 5ustar drazzibdrazzibbnd-1.50.0/cnf/repo/org.osgi.tools.console/0000755000175000017500000000000011656076535020314 5ustar drazzibdrazzibbnd-1.50.0/cnf/repo/org.apache.felix.gogo.console/0000755000175000017500000000000011656076535021475 5ustar drazzibdrazzibbnd-1.50.0/cnf/repo/xorg.eclipse.swt.cocoa/0000755000175000017500000000000011656076535020266 5ustar drazzibdrazzibbnd-1.50.0/cnf/repo/junit.osgi/0000755000175000017500000000000011656076535016056 5ustar drazzibdrazzibbnd-1.50.0/cnf/repo/org.apache.felix.gogo.command/0000755000175000017500000000000011656076535021451 5ustar drazzibdrazzibbnd-1.50.0/cnf/repo/org.apache.felix.gogo.runtime/0000755000175000017500000000000011656076535021516 5ustar drazzibdrazzibbnd-1.50.0/cnf/repo/org.apache.felix.metatype/0000755000175000017500000000000011656076535020731 5ustar drazzibdrazzibbnd-1.50.0/cnf/repo/org.osgi.impl.bundle.bindex/0000755000175000017500000000000011656076535021174 5ustar drazzibdrazzibbnd-1.50.0/cnf/repo/bndtools.runtime.eclipse.applaunch/0000755000175000017500000000000011656076535022670 5ustar drazzibdrazzibbnd-1.50.0/cnf/repo/org.eclipse.equinox.common/0000755000175000017500000000000011656076535021155 5ustar drazzibdrazzibbnd-1.50.0/cnf/repo/com.springsource.util.io/0000755000175000017500000000000011656076535020647 5ustar drazzibdrazzibbnd-1.50.0/cnf/repo/org.eclipse.debug.core/0000755000175000017500000000000011656076535020213 5ustar drazzibdrazzibbnd-1.50.0/cnf/repo/org.eclipse.ui.workbench.texteditor/0000755000175000017500000000000011656076535022766 5ustar drazzibdrazzibbnd-1.50.0/cnf/repo/org.eclipse.equinox.registry/0000755000175000017500000000000011656076535021535 5ustar drazzibdrazzibbnd-1.50.0/cnf/repo/org.eclipse.core.commands/0000755000175000017500000000000011656076535020726 5ustar drazzibdrazzibbnd-1.50.0/cnf/repo/org.apache.commons.cli/0000755000175000017500000000000011656076535020214 5ustar drazzibdrazzibbnd-1.50.0/cnf/repo/com.springsource.util.math/0000755000175000017500000000000011656076535021171 5ustar drazzibdrazzibbnd-1.50.0/cnf/repo/org.eclipse.swt.carbon.macosx/0000755000175000017500000000000011656076535021547 5ustar drazzibdrazzibbnd-1.50.0/cnf/repo/org.eclipse.osgi.v43prototype/0000755000175000017500000000000011656076535021540 5ustar drazzibdrazzibbnd-1.50.0/cnf/repo/com.springsource.net.sf.cglib/0000755000175000017500000000000011656076535021540 5ustar drazzibdrazzibbnd-1.50.0/cnf/repo/org.apache.felix.org.apache.felix.ipojo.ant/0000755000175000017500000000000011656076535024116 5ustar drazzibdrazzibbnd-1.50.0/cnf/repo/org.apache.jakarta.oro/0000755000175000017500000000000011656076535020206 5ustar drazzibdrazzibbnd-1.50.0/cnf/repo/com.springsource.util.common/0000755000175000017500000000000011656076535021530 5ustar drazzibdrazzibbnd-1.50.0/cnf/repo/org.apache.felix.main/0000755000175000017500000000000011656076535020025 5ustar drazzibdrazzibbnd-1.50.0/cnf/repo/org.eclipse.equinox.event/0000755000175000017500000000000011656076535021006 5ustar drazzibdrazzibbnd-1.50.0/cnf/repo/org.apache.felix.log/0000755000175000017500000000000011656076535017662 5ustar drazzibdrazzibbnd-1.50.0/cnf/repo/org.apache.felix.http.jetty/0000755000175000017500000000000011656076535021216 5ustar drazzibdrazzibbnd-1.50.0/cnf/repo/org.apache.felix.gogo.shell/0000755000175000017500000000000011656076535021142 5ustar drazzibdrazzibbnd-1.50.0/cnf/repo/org.apache.commons-logging/0000755000175000017500000000000011656076535021072 5ustar drazzibdrazzibbnd-1.50.0/cnf/repo/org.eclipse.ui/0000755000175000017500000000000011656076535016613 5ustar drazzibdrazzibbnd-1.50.0/cnf/repo/org.eclipse.core.jobs/0000755000175000017500000000000011656076535020062 5ustar drazzibdrazzibbnd-1.50.0/cnf/repo/org.eclipse.core.resources/0000755000175000017500000000000011656076535021137 5ustar drazzibdrazzibbnd-1.50.0/cnf/repo/org.apache.commons.net/0000755000175000017500000000000011656076535020233 5ustar drazzibdrazzibbnd-1.50.0/cnf/repo/org.eclipse.jdt.junit/0000755000175000017500000000000011656076535020107 5ustar drazzibdrazzibbnd-1.50.0/cnf/repo/biz.aQute.bndlib/0000755000175000017500000000000011656076535017060 5ustar drazzibdrazzibbnd-1.50.0/cnf/repo/org.apache.felix.scr/0000755000175000017500000000000011656076535017670 5ustar drazzibdrazzibbnd-1.50.0/cnf/repo/org.eclipse.jdt.ui/0000755000175000017500000000000011656076535017373 5ustar drazzibdrazzibbnd-1.50.0/cnf/repo/org.eclipse.swt/0000755000175000017500000000000011656076535017013 5ustar drazzibdrazzibbnd-1.50.0/cnf/repo/org.eclipse.equinox.ip/0000755000175000017500000000000011656076535020275 5ustar drazzibdrazzibbnd-1.50.0/cnf/repo/bndtools.launcher/0000755000175000017500000000000011656076535017411 5ustar drazzibdrazzibbnd-1.50.0/cnf/repo/org.eclipse.equinox.util/0000755000175000017500000000000011656076535020642 5ustar drazzibdrazzibbnd-1.50.0/cnf/repo/org.apache.felix.ipojo/0000755000175000017500000000000011656076535020221 5ustar drazzibdrazzibbnd-1.50.0/cnf/repo/org.apache.tools.ant/0000755000175000017500000000000011656076535017714 5ustar drazzibdrazzibbnd-1.50.0/cnf/repo/org.eclipse.jface.text/0000755000175000017500000000000011656076535020231 5ustar drazzibdrazzibbnd-1.50.0/cnf/repo/com.springsource.junit/0000755000175000017500000000000011656076535020415 5ustar drazzibdrazzibbnd-1.50.0/cnf/repo/org.eclipse.equinox.cm/0000755000175000017500000000000011656076535020264 5ustar drazzibdrazzibbnd-1.50.0/cnf/repo/org.apache.felix.framework/0000755000175000017500000000000011656076535021076 5ustar drazzibdrazzibbnd-1.50.0/cnf/.settings/0000755000175000017500000000000011656076535014736 5ustar drazzibdrazzibbnd-1.50.0/cnf/.settings/org.eclipse.core.resources.prefs0000644000175000017500000000012511656076535023147 0ustar drazzibdrazzib#Mon Sep 19 11:00:09 EDT 2005 eclipse.preferences.version=1 encoding/=UTF-8 bnd-1.50.0/cnf/.settings/org.eclipse.core.runtime.prefs0000644000175000017500000000011611656076535022620 0ustar drazzibdrazzib#Tue Dec 14 12:22:25 EST 2010 eclipse.preferences.version=1 line.separator=\n bnd-1.50.0/cnf/.settings/bndtools.core.prefs0000644000175000017500000000023211656076535020547 0ustar drazzibdrazzib#Tue Mar 29 16:19:39 CEST 2011 eclipse.preferences.version=1 installedRepoVersion-bndtools.repository.base=0.0.13 installedRepos=bndtools.repository.base bnd-1.50.0/README0000644000175000017500000000737611656076535013147 0ustar drazzibdrazzibREADME bnd bnd is a swiss army knife for OSGi, it creates manifest headers for you based on analyzing the class code, it verifies your settings, it manages project dependencies, gives you quote of the day, diffs jars, and much more. The information about bnd can be found at http://www.aQute.biz/Bnd Repository The git repository contains all code. It contains the following projects: 1) bndlib - Core library function, also contains most tests 2) bnd - Command line tool, eclipse plugin, and ant plugin 3) launcher - A launcher plugin for bnd 4) libg - Small, simple library utilities that are useful outside bnd 5) junit - A tester plugin for JUnit 3.8 testing for bnd 6) cnf - The bnd project directory, contains the repo with dependencies 7) demo - A project used in testing 8) compiler - A wrapped version of the eclipse java compiler API All code is Apache 2.0 Licensed so you can do what you want with the source code. though I am usually pretty good at backward compatibility, there is no guarantee. This is an unpaid project and one of the most annoying thing of work is being backward compatible on the Java API when you know a better way to do it. Properties will be backward compatible if there is any possibility. So be aware, its ok to use this package but do not complain if new releases require some work. If you're building a tool with a general audience, e.g. bndtools, that includes bnd for a general audience I would appreciate if you got in touch with me so I can keep in touch. I am always interested in ideas. Eclipse bnd is build with itself, which can create some headaches. Overall, you want to your work therefore in Eclipse with a recent bnd.jar in the Eclipse dropins folder. Currently, bndtools is not yet ready for bnd itself :-( however, that is being worked on. Once bndtools handles the bnd launcher/tester then the eclipse plugin will be removed. Until that moment, we need to use the old code in Eclipse. It is advised to not mix bnd and bndtools but use different instances of Eclipse. Building The workspace root has a build.xml that builds all project in proper order. Due to the fact that bnd builds itself there are certain cases where you get an error during build. Trying again should fix the issue. Each project directory has a build.xml. The following targets are available: ant build (default) - Build ant clean - Clean the project ant test - Run a bnd OSGi test ant junit - Run standard JUnit tests in the test package Outputs are stored in the tmp directory in the different projects. Testing The main tests are in the bndlib project. These are standard JUnit tests. They are all in the src/test directory. Tests are quite extensive and run from the Eclipse JUnit screen. Release The current release process could use some work. The following steps are used: 1) Changes to the tree are made on the next branch 2) After the next branch is done, commit all changes. There are a few files changed by tests that should not be committed every time: # biz.aQute.bndlib/test/ws/p1/bnd.bnd # biz.aQute.bndlib/test/ws/p1/bnd.bnd.bak # biz.aQute.bndlib/test/ws/p3/generated/p3.jar This needs fixing btw. The test should not touch those files or at least restore 3) Switch to master 4) ant clean build 5) run the tests 6) if successful, release the jars 7) bump the version (bnd bump command does this) 8) switch to next branch This process is likely to change because it contains too many manual steps Feedback Feedback is always welcome, for general discussions use bndtools-users@googlegroups.com Bugs and issues should go to https://github.com/bndtools/bnd Other feedback or specific functionality send to Peter.Kriens@aQute.biz Donations should go to http://pledgie.com/campaigns/10548 bnd-1.50.0/biz.aQute.bndlib/0000755000175000017500000000000011656076535015345 5ustar drazzibdrazzibbnd-1.50.0/biz.aQute.bndlib/test.out0000644000175000017500000000616211656076535017062 0ustar drazzibdrazzib bnd-1.50.0/biz.aQute.bndlib/LICENSE0000755000175000017500000002613611656076535016365 0ustar drazzibdrazzib Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. bnd-1.50.0/biz.aQute.bndlib/build.xml0000644000175000017500000000017711656076535017173 0ustar drazzibdrazzib bnd-1.50.0/biz.aQute.bndlib/compilerversions/0000755000175000017500000000000011656076535020750 5ustar drazzibdrazzibbnd-1.50.0/biz.aQute.bndlib/compilerversions/compilerversions.bnd0000755000175000017500000000004311656076535025040 0ustar drazzibdrazzib-classpath: src Export-Package: * bnd-1.50.0/biz.aQute.bndlib/compilerversions/src/0000755000175000017500000000000011656076535021537 5ustar drazzibdrazzibbnd-1.50.0/biz.aQute.bndlib/compilerversions/src/sun_1_5/0000755000175000017500000000000011656076535023010 5ustar drazzibdrazzibbnd-1.50.0/biz.aQute.bndlib/compilerversions/src/sun_1_5/ClassRef.java0000755000175000017500000000027511656076535025364 0ustar drazzibdrazzibpackage sun_1_5; public class ClassRef { class Inner { }; static { System.out.println(Inner.class); } public static void main() { System.out.println(javax.swing.Box.class); } }bnd-1.50.0/biz.aQute.bndlib/compilerversions/src/sun_1_4/0000755000175000017500000000000011656076535023007 5ustar drazzibdrazzibbnd-1.50.0/biz.aQute.bndlib/compilerversions/src/sun_1_4/ClassRef.java0000755000175000017500000000027411656076535025362 0ustar drazzibdrazzibpackage sun_1_4; public class ClassRef { class Inner { }; static { System.out.println(Inner.class); } public static void main() { System.out.println(javax.swing.Box.class); } }bnd-1.50.0/biz.aQute.bndlib/compilerversions/src/sun_1_6/0000755000175000017500000000000011656076535023011 5ustar drazzibdrazzibbnd-1.50.0/biz.aQute.bndlib/compilerversions/src/sun_1_6/ClassRef.java0000755000175000017500000000027511656076535025365 0ustar drazzibdrazzibpackage sun_1_6; public class ClassRef { class Inner { }; static { System.out.println(Inner.class); } public static void main() { System.out.println(javax.swing.Box.class); } }bnd-1.50.0/biz.aQute.bndlib/compilerversions/src/sun_1_2/0000755000175000017500000000000011656076535023005 5ustar drazzibdrazzibbnd-1.50.0/biz.aQute.bndlib/compilerversions/src/sun_1_2/ClassRef.java0000755000175000017500000000027511656076535025361 0ustar drazzibdrazzibpackage sun_1_2; public class ClassRef { class Inner { }; static { System.out.println(Inner.class); } public static void main() { System.out.println(javax.swing.Box.class); } }bnd-1.50.0/biz.aQute.bndlib/compilerversions/src/eclipse_1_5/0000755000175000017500000000000011656076535023627 5ustar drazzibdrazzibbnd-1.50.0/biz.aQute.bndlib/compilerversions/src/eclipse_1_5/ClassRef.java0000755000175000017500000000030111656076535026171 0ustar drazzibdrazzibpackage eclipse_1_5; public class ClassRef { class Inner { }; static { System.out.println(Inner.class); } public static void main() { System.out.println(javax.swing.Box.class); } }bnd-1.50.0/biz.aQute.bndlib/compilerversions/src/eclipse_1_6/0000755000175000017500000000000011656076535023630 5ustar drazzibdrazzibbnd-1.50.0/biz.aQute.bndlib/compilerversions/src/eclipse_1_6/ClassRef.java0000755000175000017500000000030111656076535026172 0ustar drazzibdrazzibpackage eclipse_1_6; public class ClassRef { class Inner { }; static { System.out.println(Inner.class); } public static void main() { System.out.println(javax.swing.Box.class); } }bnd-1.50.0/biz.aQute.bndlib/compilerversions/src/eclipse_1_2/0000755000175000017500000000000011656076535023624 5ustar drazzibdrazzibbnd-1.50.0/biz.aQute.bndlib/compilerversions/src/eclipse_1_2/ClassRef.java0000755000175000017500000000030111656076535026166 0ustar drazzibdrazzibpackage eclipse_1_2; public class ClassRef { class Inner { }; static { System.out.println(Inner.class); } public static void main() { System.out.println(javax.swing.Box.class); } }bnd-1.50.0/biz.aQute.bndlib/compilerversions/src/eclipse_jsr14/0000755000175000017500000000000011656076535024206 5ustar drazzibdrazzibbnd-1.50.0/biz.aQute.bndlib/compilerversions/src/eclipse_jsr14/ClassRef.java0000755000175000017500000000030311656076535026552 0ustar drazzibdrazzibpackage eclipse_jsr14; public class ClassRef { class Inner { }; static { System.out.println(Inner.class); } public static void main() { System.out.println(javax.swing.Box.class); } }bnd-1.50.0/biz.aQute.bndlib/compilerversions/src/sun_jsr14/0000755000175000017500000000000011656076535023367 5ustar drazzibdrazzibbnd-1.50.0/biz.aQute.bndlib/compilerversions/src/sun_jsr14/ClassRef.java0000755000175000017500000000027711656076535025745 0ustar drazzibdrazzibpackage sun_jsr14; public class ClassRef { class Inner { }; static { System.out.println(Inner.class); } public static void main() { System.out.println(javax.swing.Box.class); } }bnd-1.50.0/biz.aQute.bndlib/compilerversions/src/eclipse_1_3/0000755000175000017500000000000011656076535023625 5ustar drazzibdrazzibbnd-1.50.0/biz.aQute.bndlib/compilerversions/src/eclipse_1_3/ClassRef.java0000755000175000017500000000017611656076535026201 0ustar drazzibdrazzibpackage eclipse_1_3; public class ClassRef { public static void main() { System.out.println(javax.swing.Box.class); } }bnd-1.50.0/biz.aQute.bndlib/compilerversions/src/sun_1_3/0000755000175000017500000000000011656076535023006 5ustar drazzibdrazzibbnd-1.50.0/biz.aQute.bndlib/compilerversions/src/sun_1_3/ClassRef.java0000755000175000017500000000027511656076535025362 0ustar drazzibdrazzibpackage sun_1_3; public class ClassRef { class Inner { }; static { System.out.println(Inner.class); } public static void main() { System.out.println(javax.swing.Box.class); } }bnd-1.50.0/biz.aQute.bndlib/compilerversions/src/eclipse_1_4/0000755000175000017500000000000011656076535023626 5ustar drazzibdrazzibbnd-1.50.0/biz.aQute.bndlib/compilerversions/src/eclipse_1_4/ClassRef.java0000755000175000017500000000030111656076535026170 0ustar drazzibdrazzibpackage eclipse_1_4; public class ClassRef { class Inner { }; static { System.out.println(Inner.class); } public static void main() { System.out.println(javax.swing.Box.class); } }bnd-1.50.0/biz.aQute.bndlib/compilerversions/src/eclipse_1_1/0000755000175000017500000000000011656076535023623 5ustar drazzibdrazzibbnd-1.50.0/biz.aQute.bndlib/compilerversions/src/eclipse_1_1/ClassRef.java0000755000175000017500000000060711656076535026176 0ustar drazzibdrazzibpackage eclipse_1_1; public class ClassRef { class Inner { }; static { System.out.println(Inner.class); } public static void main() { int a= 3; a++; switch( a ) { case 1: System.out.println(javax.swing.event.ChangeEvent.class); break; case 2: System.out.println(javax.swing.event.ChangeEvent.class); break; default: } System.out.println(javax.swing.Box.class); } }bnd-1.50.0/biz.aQute.bndlib/compilerversions/src/sun_1_1/0000755000175000017500000000000011656076535023004 5ustar drazzibdrazzibbnd-1.50.0/biz.aQute.bndlib/compilerversions/src/sun_1_1/ClassRef.java0000755000175000017500000000027511656076535025360 0ustar drazzibdrazzibpackage sun_1_1; public class ClassRef { class Inner { }; static { System.out.println(Inner.class); } public static void main() { System.out.println(javax.swing.Box.class); } }bnd-1.50.0/biz.aQute.bndlib/compilerversions/download_bundle.gif0000644000175000017500000000206611656076535024603 0ustar drazzibdrazzibGIF89aÄÿÿÿÿûøÇûÕúøòè¼ìÞ´ëܳëÛ³êÛ²æÓ¬ßÇ£Ù¼šÖ·–Õ·—Õ·–Õ¶—Õ¶–Ó±’˦‰ÉÉýÇž‚Æž‚¿’w¿‘w¾’v¸†l·†l­u]žpX_??,@b ŽdInA@$Â00ÖVhÁp.³&P ΆÁëùtBÆ ·ƒ¹”ÌFF¢-$¹ØÎÈåvF‚-Pà“"‰Av¾(©Ãá´\xç;bJ/1r3Zj%a|]!;À¦ÿÿÿÿЦî<”ÒøààîLï!î<î< ïT'‘| î<7)‘|Ðï3‘|Ðï—+î<¨î bnd-1.50.0/biz.aQute.bndlib/.project0000755000175000017500000000056711656076535017027 0ustar drazzibdrazzib biz.aQute.bndlib org.eclipse.jdt.core.javabuilder org.eclipse.jdt.core.javanature bnd-1.50.0/biz.aQute.bndlib/bnd/0000755000175000017500000000000011656076535016110 5ustar drazzibdrazzibbnd-1.50.0/biz.aQute.bndlib/bnd/ondemand.bnd0000644000175000017500000000003711656076535020362 0ustar drazzibdrazzibExport-Package: aQute.bnd.make bnd-1.50.0/biz.aQute.bndlib/bnd/makesondemand.bnd0000644000175000017500000000006311656076535021402 0ustar drazzibdrazzibInclude-Resource: ondemand.jar -resourceonly: true bnd-1.50.0/biz.aQute.bndlib/test/0000755000175000017500000000000011656076535016324 5ustar drazzibdrazzibbnd-1.50.0/biz.aQute.bndlib/test/w o r k s p a c e/0000755000175000017500000000000011656076535020722 5ustar drazzibdrazzibbnd-1.50.0/biz.aQute.bndlib/test/w o r k s p a c e/p r o j e c t/0000755000175000017500000000000011656076535022670 5ustar drazzibdrazzibbnd-1.50.0/biz.aQute.bndlib/test/w o r k s p a c e/p r o j e c t/bnd.bnd0000644000175000017500000000000011656076535024106 0ustar drazzibdrazzibbnd-1.50.0/biz.aQute.bndlib/test/w o r k s p a c e/cnf/0000755000175000017500000000000011656076535021470 5ustar drazzibdrazzibbnd-1.50.0/biz.aQute.bndlib/test/w o r k s p a c e/cnf/ext/0000755000175000017500000000000011656076535022270 5ustar drazzibdrazzibbnd-1.50.0/biz.aQute.bndlib/test/w o r k s p a c e/cnf/ext/extension.bnd0000644000175000017500000000004011656076535024763 0ustar drazzibdrazzibext = true override = extension bnd-1.50.0/biz.aQute.bndlib/test/w o r k s p a c e/cnf/build.bnd0000644000175000017500000000003411656076535023251 0ustar drazzibdrazzibtest=abcdef override=parent bnd-1.50.0/biz.aQute.bndlib/test/ws/0000755000175000017500000000000011656076535016755 5ustar drazzibdrazzibbnd-1.50.0/biz.aQute.bndlib/test/ws/p-maven-remote/0000755000175000017500000000000011656076535021611 5ustar drazzibdrazzibbnd-1.50.0/biz.aQute.bndlib/test/ws/p-maven-remote/bnd.bnd0000644000175000017500000000004511656076535023040 0ustar drazzibdrazzib-buildpath: junit+junit; version=3.8 bnd-1.50.0/biz.aQute.bndlib/test/ws/p1/0000755000175000017500000000000011656076535017275 5ustar drazzibdrazzibbnd-1.50.0/biz.aQute.bndlib/test/ws/p1/p1b.bndrun0000644000175000017500000000002011656076535021161 0ustar drazzibdrazzib-runbuilds: truebnd-1.50.0/biz.aQute.bndlib/test/ws/p1/bnd.bnd0000644000175000017500000000010511656076535020521 0ustar drazzibdrazzibBundle-Version: 1.260.0.${build} Header-1: 1 Header-1: 2 Header-1: 3 bnd-1.50.0/biz.aQute.bndlib/test/ws/p1/p1a.bndrun0000644000175000017500000000000711656076535021165 0ustar drazzibdrazzib# blankbnd-1.50.0/biz.aQute.bndlib/test/ws/maven1/0000755000175000017500000000000011656076535020144 5ustar drazzibdrazzibbnd-1.50.0/biz.aQute.bndlib/test/ws/maven1/maven-dependencies.txt0000755000175000017500000000500711656076535024444 0ustar drazzibdrazzib org.eclipse.osgi org.eclipse.osgi 3.2.0-v20060601 compile org.eclipse.equinox org.eclipse.equinox.common 3.2.0-v20060603 compile org.eclipse.core org.eclipse.core.resources 3.2.0-v20060603 compile org.eclipse.core org.eclipse.core.runtime 3.2.0-v20060603 compile org.eclipse.core org.eclipse.core.jobs 3.2.0-v20060603 compile org.eclipse.equinox org.eclipse.equinox.registry 3.2.0-v20060601 compile org.eclipse.jface org.eclipse.jface 3.2.0-I20060605-1400 compile org.eclipse.ui org.eclipse.ui.workbench 3.2.0-I20060605-1400 compile org.eclipse.swt org.eclipse.swt.win32.win32.x86 3.2.0-v3232 compile org.eclipse.jdt org.eclipse.jdt.core 3.2.0-v_671 compile org.apache.ant ant 1.7.0 compile bnd-1.50.0/biz.aQute.bndlib/test/ws/maven1/pom.xml0000644000175000017500000000720311656076535021463 0ustar drazzibdrazzib 4.0.0 org.apache.felix felix-parent 1.2.0 parentpom.xml org.apache.felix.metatype bundle Apache Felix Metatype Service Implementation of the OSGi Metatype Service Specification 1.1 1.0.5-SNAPSHOT ${pom.groupId} org.osgi.core 1.0.0 ${pom.groupId} org.osgi.compendium 1.0.0 net.sf.kxml kxml2 2.2.2 org.apache.felix maven-bundle-plugin 2.0.1 true osgi ${pom.artifactId} http://felix.apache.org/site/apache-felix-metatype-service.html org.apache.felix.metatype; version=${pom.version}, org.osgi.service.metatype; version=1.1 org.apache.felix.metatype.internal, org.apache.felix.metatype.internal.l10n, org.osgi.util.tracker org.apache.felix.metatype.internal.Activator kxml2 bnd-1.50.0/biz.aQute.bndlib/test/ws/maven1/testparentpom.xml0000644000175000017500000000203411656076535023572 0ustar drazzibdrazzib 4.0.0 group-parent artifact-parent pom Parent 0.0.0 Parent Description junit junit 4.0 test org.easymock easymock 2.4 compile a from parent b from parent ${a}${a} bnd-1.50.0/biz.aQute.bndlib/test/ws/maven1/bnd.bnd0000644000175000017500000000030711656076535021374 0ustar drazzibdrazzib-plugin: aQute.bnd.maven.support.MavenRemoteRepository;repositories=${project}/m2 -buildpath: \ com.springsource.org.apache.commons.beanutils;version=1.6.1;groupId=org.apache.commons;scope=compile bnd-1.50.0/biz.aQute.bndlib/test/ws/maven1/testpom.xml0000644000175000017500000000221011656076535022354 0ustar drazzibdrazzib 4.0.0 group-parent artifact-parent 1.0.0-parent testparentpom.xml artifact bundle Artifact Description ${pom.artifactId} 1.0.0 xyz dep1 1.0.1 ${pom.groupId} ${pom.artifactId} 1.0.2 aa ${a}${b}${pom.artifactId} bnd-1.50.0/biz.aQute.bndlib/test/ws/maven1/m2/0000755000175000017500000000000011656076535020462 5ustar drazzibdrazzibbnd-1.50.0/biz.aQute.bndlib/test/ws/maven1/m2/org/0000755000175000017500000000000011656076535021251 5ustar drazzibdrazzibbnd-1.50.0/biz.aQute.bndlib/test/ws/maven1/m2/org/apache/0000755000175000017500000000000011656076535022472 5ustar drazzibdrazzibbnd-1.50.0/biz.aQute.bndlib/test/ws/maven1/m2/org/apache/commons/0000755000175000017500000000000011656076535024145 5ustar drazzibdrazzib././@LongLink0000000000000000000000000000016200000000000011564 Lustar rootrootbnd-1.50.0/biz.aQute.bndlib/test/ws/maven1/m2/org/apache/commons/com.springsource.org.apache.commons.collections/bnd-1.50.0/biz.aQute.bndlib/test/ws/maven1/m2/org/apache/commons/com.springsource.org.apache.commons0000755000175000017500000000000011656076535033046 5ustar drazzibdrazzib././@LongLink0000000000000000000000000000017000000000000011563 Lustar rootrootbnd-1.50.0/biz.aQute.bndlib/test/ws/maven1/m2/org/apache/commons/com.springsource.org.apache.commons.collections/2.1.1/bnd-1.50.0/biz.aQute.bndlib/test/ws/maven1/m2/org/apache/commons/com.springsource.org.apache.commons0000755000175000017500000000000011656076535033046 5ustar drazzibdrazzib././@LongLink0000000000000000000000000000026100000000000011564 Lustar rootrootbnd-1.50.0/biz.aQute.bndlib/test/ws/maven1/m2/org/apache/commons/com.springsource.org.apache.commons.collections/2.1.1/com.springsource.org.apache.commons.collections-2.1.1.pombnd-1.50.0/biz.aQute.bndlib/test/ws/maven1/m2/org/apache/commons/com.springsource.org.apache.commons0000644000175000017500000000115311656076535033050 0ustar drazzibdrazzib 4.0.0 org.apache.commons com.springsource.org.apache.commons.collections jar 2.1.1 ././@LongLink0000000000000000000000000000021300000000000011561 Lustar rootrootbnd-1.50.0/biz.aQute.bndlib/test/ws/maven1/m2/org/apache/commons/com.springsource.org.apache.commons.collections/2.1.1/_maven.repositoriesbnd-1.50.0/biz.aQute.bndlib/test/ws/maven1/m2/org/apache/commons/com.springsource.org.apache.commons0000644000175000017500000000051711656076535033053 0ustar drazzibdrazzib#NOTE: This is an internal implementation file, its format can be changed without prior notice. #Mon Apr 11 15:25:58 CEST 2011 com.springsource.org.apache.commons.collections-2.1.1.pom>com.springsource.repository.bundles.external= com.springsource.org.apache.commons.collections-2.1.1.jar>com.springsource.repository.bundles.external= ././@LongLink0000000000000000000000000000027500000000000011571 Lustar rootrootbnd-1.50.0/biz.aQute.bndlib/test/ws/maven1/m2/org/apache/commons/com.springsource.org.apache.commons.collections/2.1.1/com.springsource.org.apache.commons.collections-2.1.1.pom.lastUpdatedbnd-1.50.0/biz.aQute.bndlib/test/ws/maven1/m2/org/apache/commons/com.springsource.org.apache.commons0000644000175000017500000000055411656076535033054 0ustar drazzibdrazzib#NOTE: This is an internal implementation file, its format can be changed without prior notice. #Mon Apr 11 15:25:50 CEST 2011 http\://repository.springsource.com/maven/bundles/external/.lastUpdated=1302528350745 http\://repository.springsource.com/maven/bundles/release/.lastUpdated=1302528350108 http\://repository.springsource.com/maven/bundles/release/.error= ././@LongLink0000000000000000000000000000026600000000000011571 Lustar rootrootbnd-1.50.0/biz.aQute.bndlib/test/ws/maven1/m2/org/apache/commons/com.springsource.org.apache.commons.collections/2.1.1/com.springsource.org.apache.commons.collections-2.1.1.pom.sha1bnd-1.50.0/biz.aQute.bndlib/test/ws/maven1/m2/org/apache/commons/com.springsource.org.apache.commons0000644000175000017500000000005011656076535033043 0ustar drazzibdrazzib8ab8879eace517560f11c5748ae13e572eb2e4fb././@LongLink0000000000000000000000000000026600000000000011571 Lustar rootrootbnd-1.50.0/biz.aQute.bndlib/test/ws/maven1/m2/org/apache/commons/com.springsource.org.apache.commons.collections/2.1.1/com.springsource.org.apache.commons.collections-2.1.1.jar.sha1bnd-1.50.0/biz.aQute.bndlib/test/ws/maven1/m2/org/apache/commons/com.springsource.org.apache.commons0000644000175000017500000000005011656076535033043 0ustar drazzibdrazzib4c374fa693f45eb667e19882a029444c9629e96e././@LongLink0000000000000000000000000000027500000000000011571 Lustar rootrootbnd-1.50.0/biz.aQute.bndlib/test/ws/maven1/m2/org/apache/commons/com.springsource.org.apache.commons.collections/2.1.1/com.springsource.org.apache.commons.collections-2.1.1.jar.lastUpdatedbnd-1.50.0/biz.aQute.bndlib/test/ws/maven1/m2/org/apache/commons/com.springsource.org.apache.commons0000644000175000017500000000055411656076535033054 0ustar drazzibdrazzib#NOTE: This is an internal implementation file, its format can be changed without prior notice. #Mon Apr 11 15:25:58 CEST 2011 http\://repository.springsource.com/maven/bundles/external/.lastUpdated=1302528358636 http\://repository.springsource.com/maven/bundles/release/.lastUpdated=1302528352816 http\://repository.springsource.com/maven/bundles/release/.error= ././@LongLink0000000000000000000000000000017000000000000011563 Lustar rootrootbnd-1.50.0/biz.aQute.bndlib/test/ws/maven1/m2/org/apache/commons/com.springsource.org.apache.commons.collections/3.2.0/bnd-1.50.0/biz.aQute.bndlib/test/ws/maven1/m2/org/apache/commons/com.springsource.org.apache.commons0000755000175000017500000000000011656076535033046 5ustar drazzibdrazzib././@LongLink0000000000000000000000000000026600000000000011571 Lustar rootrootbnd-1.50.0/biz.aQute.bndlib/test/ws/maven1/m2/org/apache/commons/com.springsource.org.apache.commons.collections/3.2.0/com.springsource.org.apache.commons.collections-3.2.0.jar.sha1bnd-1.50.0/biz.aQute.bndlib/test/ws/maven1/m2/org/apache/commons/com.springsource.org.apache.commons0000644000175000017500000000005011656076535033043 0ustar drazzibdrazzib3d524f807d7ffca076a6bed03690496bcc5c57d6././@LongLink0000000000000000000000000000026100000000000011564 Lustar rootrootbnd-1.50.0/biz.aQute.bndlib/test/ws/maven1/m2/org/apache/commons/com.springsource.org.apache.commons.collections/3.2.0/com.springsource.org.apache.commons.collections-3.2.0.pombnd-1.50.0/biz.aQute.bndlib/test/ws/maven1/m2/org/apache/commons/com.springsource.org.apache.commons0000644000175000017500000000115311656076535033050 0ustar drazzibdrazzib 4.0.0 org.apache.commons com.springsource.org.apache.commons.collections jar 3.2.0 ././@LongLink0000000000000000000000000000026600000000000011571 Lustar rootrootbnd-1.50.0/biz.aQute.bndlib/test/ws/maven1/m2/org/apache/commons/com.springsource.org.apache.commons.collections/3.2.0/com.springsource.org.apache.commons.collections-3.2.0.pom.sha1bnd-1.50.0/biz.aQute.bndlib/test/ws/maven1/m2/org/apache/commons/com.springsource.org.apache.commons0000644000175000017500000000005011656076535033043 0ustar drazzibdrazzibc9dafa4ac73acb6fc34125d66bd299859de4fe38././@LongLink0000000000000000000000000000015400000000000011565 Lustar rootrootbnd-1.50.0/biz.aQute.bndlib/test/ws/maven1/m2/org/apache/commons/com.springsource.org.apache.commons.codec/bnd-1.50.0/biz.aQute.bndlib/test/ws/maven1/m2/org/apache/commons/com.springsource.org.apache.commons0000755000175000017500000000000011656076535033046 5ustar drazzibdrazzib././@LongLink0000000000000000000000000000016200000000000011564 Lustar rootrootbnd-1.50.0/biz.aQute.bndlib/test/ws/maven1/m2/org/apache/commons/com.springsource.org.apache.commons.codec/1.3.0/bnd-1.50.0/biz.aQute.bndlib/test/ws/maven1/m2/org/apache/commons/com.springsource.org.apache.commons0000755000175000017500000000000011656076535033046 5ustar drazzibdrazzib././@LongLink0000000000000000000000000000026100000000000011564 Lustar rootrootbnd-1.50.0/biz.aQute.bndlib/test/ws/maven1/m2/org/apache/commons/com.springsource.org.apache.commons.codec/1.3.0/com.springsource.org.apache.commons.codec-1.3.0.pom.lastUpdatedbnd-1.50.0/biz.aQute.bndlib/test/ws/maven1/m2/org/apache/commons/com.springsource.org.apache.commons0000644000175000017500000000112011656076535033042 0ustar drazzibdrazzib#NOTE: This is an internal implementation file, its format can be changed without prior notice. #Wed Mar 30 11:39:38 CEST 2011 http\://repository.springsource.com/maven/bundles/external/.lastUpdated=1301477978052 http\://repository.jboss.com/maven2/.lastUpdated=1301477977430 http\://maven.springframework.org/snapshot/.lastUpdated=1301477976616 http\://repository.springsource.com/maven/bundles/release/.lastUpdated=1301477977582 http\://repository.jboss.com/maven2/.error= http\://maven.springframework.org/snapshot/.error= http\://repository.springsource.com/maven/bundles/release/.error= ././@LongLink0000000000000000000000000000020500000000000011562 Lustar rootrootbnd-1.50.0/biz.aQute.bndlib/test/ws/maven1/m2/org/apache/commons/com.springsource.org.apache.commons.codec/1.3.0/_maven.repositoriesbnd-1.50.0/biz.aQute.bndlib/test/ws/maven1/m2/org/apache/commons/com.springsource.org.apache.commons0000644000175000017500000000034111656076535033046 0ustar drazzibdrazzib#NOTE: This is an internal implementation file, its format can be changed without prior notice. #Wed Mar 30 11:39:38 CEST 2011 com.springsource.org.apache.commons.codec-1.3.0.pom>com.springsource.repository.bundles.external= ././@LongLink0000000000000000000000000000025200000000000011564 Lustar rootrootbnd-1.50.0/biz.aQute.bndlib/test/ws/maven1/m2/org/apache/commons/com.springsource.org.apache.commons.codec/1.3.0/com.springsource.org.apache.commons.codec-1.3.0.pom.sha1bnd-1.50.0/biz.aQute.bndlib/test/ws/maven1/m2/org/apache/commons/com.springsource.org.apache.commons0000644000175000017500000000005011656076535033043 0ustar drazzibdrazzibb3538f1187f1e86ca9ed86b82ef4467653481f2c././@LongLink0000000000000000000000000000024500000000000011566 Lustar rootrootbnd-1.50.0/biz.aQute.bndlib/test/ws/maven1/m2/org/apache/commons/com.springsource.org.apache.commons.codec/1.3.0/com.springsource.org.apache.commons.codec-1.3.0.pombnd-1.50.0/biz.aQute.bndlib/test/ws/maven1/m2/org/apache/commons/com.springsource.org.apache.commons0000644000175000017500000000114511656076535033051 0ustar drazzibdrazzib 4.0.0 org.apache.commons com.springsource.org.apache.commons.codec jar 1.3.0 ././@LongLink0000000000000000000000000000015600000000000011567 Lustar rootrootbnd-1.50.0/biz.aQute.bndlib/test/ws/maven1/m2/org/apache/commons/com.springsource.org.apache.commons.logging/bnd-1.50.0/biz.aQute.bndlib/test/ws/maven1/m2/org/apache/commons/com.springsource.org.apache.commons0000755000175000017500000000000011656076535033046 5ustar drazzibdrazzib././@LongLink0000000000000000000000000000016400000000000011566 Lustar rootrootbnd-1.50.0/biz.aQute.bndlib/test/ws/maven1/m2/org/apache/commons/com.springsource.org.apache.commons.logging/1.1.1/bnd-1.50.0/biz.aQute.bndlib/test/ws/maven1/m2/org/apache/commons/com.springsource.org.apache.commons0000755000175000017500000000000011656076535033046 5ustar drazzibdrazzib././@LongLink0000000000000000000000000000025100000000000011563 Lustar rootrootbnd-1.50.0/biz.aQute.bndlib/test/ws/maven1/m2/org/apache/commons/com.springsource.org.apache.commons.logging/1.1.1/com.springsource.org.apache.commons.logging-1.1.1.pombnd-1.50.0/biz.aQute.bndlib/test/ws/maven1/m2/org/apache/commons/com.springsource.org.apache.commons0000644000175000017500000000203511656076535033050 0ustar drazzibdrazzib 4.0.0 org.apache.commons com.springsource.org.apache.commons.logging jar 1.1.1 javax.servlet com.springsource.javax.servlet 2.4.0 provided org.apache.log4j com.springsource.org.apache.log4j 1.2.15 true ././@LongLink0000000000000000000000000000025600000000000011570 Lustar rootrootbnd-1.50.0/biz.aQute.bndlib/test/ws/maven1/m2/org/apache/commons/com.springsource.org.apache.commons.logging/1.1.1/com.springsource.org.apache.commons.logging-1.1.1.jar.sha1bnd-1.50.0/biz.aQute.bndlib/test/ws/maven1/m2/org/apache/commons/com.springsource.org.apache.commons0000644000175000017500000000005011656076535033043 0ustar drazzibdrazzib7657caf2c78e1d79c74d36f2ae128a115f7cc180././@LongLink0000000000000000000000000000025600000000000011570 Lustar rootrootbnd-1.50.0/biz.aQute.bndlib/test/ws/maven1/m2/org/apache/commons/com.springsource.org.apache.commons.logging/1.1.1/com.springsource.org.apache.commons.logging-1.1.1.pom.sha1bnd-1.50.0/biz.aQute.bndlib/test/ws/maven1/m2/org/apache/commons/com.springsource.org.apache.commons0000644000175000017500000000005011656076535033043 0ustar drazzibdrazzib30493963029f45cdd6fc0f2dd7aa4cc78e8f3329././@LongLink0000000000000000000000000000016400000000000011566 Lustar rootrootbnd-1.50.0/biz.aQute.bndlib/test/ws/maven1/m2/org/apache/commons/com.springsource.org.apache.commons.logging/1.0.4/bnd-1.50.0/biz.aQute.bndlib/test/ws/maven1/m2/org/apache/commons/com.springsource.org.apache.commons0000755000175000017500000000000011656076535033046 5ustar drazzibdrazzib././@LongLink0000000000000000000000000000026500000000000011570 Lustar rootrootbnd-1.50.0/biz.aQute.bndlib/test/ws/maven1/m2/org/apache/commons/com.springsource.org.apache.commons.logging/1.0.4/com.springsource.org.apache.commons.logging-1.0.4.jar.lastUpdatedbnd-1.50.0/biz.aQute.bndlib/test/ws/maven1/m2/org/apache/commons/com.springsource.org.apache.commons0000644000175000017500000000055411656076535033054 0ustar drazzibdrazzib#NOTE: This is an internal implementation file, its format can be changed without prior notice. #Wed Apr 13 12:42:00 CEST 2011 http\://repository.springsource.com/maven/bundles/external/.lastUpdated=1302691320835 http\://repository.springsource.com/maven/bundles/release/.lastUpdated=1302691318506 http\://repository.springsource.com/maven/bundles/release/.error= ././@LongLink0000000000000000000000000000020700000000000011564 Lustar rootrootbnd-1.50.0/biz.aQute.bndlib/test/ws/maven1/m2/org/apache/commons/com.springsource.org.apache.commons.logging/1.0.4/_maven.repositoriesbnd-1.50.0/biz.aQute.bndlib/test/ws/maven1/m2/org/apache/commons/com.springsource.org.apache.commons0000644000175000017500000000050711656076535033052 0ustar drazzibdrazzib#NOTE: This is an internal implementation file, its format can be changed without prior notice. #Wed Apr 13 12:42:00 CEST 2011 com.springsource.org.apache.commons.logging-1.0.4.pom>com.springsource.repository.bundles.external= com.springsource.org.apache.commons.logging-1.0.4.jar>com.springsource.repository.bundles.external= ././@LongLink0000000000000000000000000000025600000000000011570 Lustar rootrootbnd-1.50.0/biz.aQute.bndlib/test/ws/maven1/m2/org/apache/commons/com.springsource.org.apache.commons.logging/1.0.4/com.springsource.org.apache.commons.logging-1.0.4.jar.sha1bnd-1.50.0/biz.aQute.bndlib/test/ws/maven1/m2/org/apache/commons/com.springsource.org.apache.commons0000644000175000017500000000005011656076535033043 0ustar drazzibdrazzibb34d071ef5281fb76a9f8c4a2543943485578861././@LongLink0000000000000000000000000000026500000000000011570 Lustar rootrootbnd-1.50.0/biz.aQute.bndlib/test/ws/maven1/m2/org/apache/commons/com.springsource.org.apache.commons.logging/1.0.4/com.springsource.org.apache.commons.logging-1.0.4.pom.lastUpdatedbnd-1.50.0/biz.aQute.bndlib/test/ws/maven1/m2/org/apache/commons/com.springsource.org.apache.commons0000644000175000017500000000055411656076535033054 0ustar drazzibdrazzib#NOTE: This is an internal implementation file, its format can be changed without prior notice. #Wed Apr 13 12:41:57 CEST 2011 http\://repository.springsource.com/maven/bundles/external/.lastUpdated=1302691317770 http\://repository.springsource.com/maven/bundles/release/.lastUpdated=1302691317425 http\://repository.springsource.com/maven/bundles/release/.error= ././@LongLink0000000000000000000000000000025100000000000011563 Lustar rootrootbnd-1.50.0/biz.aQute.bndlib/test/ws/maven1/m2/org/apache/commons/com.springsource.org.apache.commons.logging/1.0.4/com.springsource.org.apache.commons.logging-1.0.4.pombnd-1.50.0/biz.aQute.bndlib/test/ws/maven1/m2/org/apache/commons/com.springsource.org.apache.commons0000644000175000017500000000153011656076535033047 0ustar drazzibdrazzib 4.0.0 org.apache.commons com.springsource.org.apache.commons.logging jar 1.0.4 org.apache.log4j com.springsource.org.apache.log4j 1.2.15 true ././@LongLink0000000000000000000000000000025600000000000011570 Lustar rootrootbnd-1.50.0/biz.aQute.bndlib/test/ws/maven1/m2/org/apache/commons/com.springsource.org.apache.commons.logging/1.0.4/com.springsource.org.apache.commons.logging-1.0.4.pom.sha1bnd-1.50.0/biz.aQute.bndlib/test/ws/maven1/m2/org/apache/commons/com.springsource.org.apache.commons0000644000175000017500000000005011656076535033043 0ustar drazzibdrazzib2041f5ba898e62d37ea8ecb3b5a334ef1c93c5b7././@LongLink0000000000000000000000000000016000000000000011562 Lustar rootrootbnd-1.50.0/biz.aQute.bndlib/test/ws/maven1/m2/org/apache/commons/com.springsource.org.apache.commons.beanutils/bnd-1.50.0/biz.aQute.bndlib/test/ws/maven1/m2/org/apache/commons/com.springsource.org.apache.commons0000755000175000017500000000000011656076535033046 5ustar drazzibdrazzib././@LongLink0000000000000000000000000000016600000000000011570 Lustar rootrootbnd-1.50.0/biz.aQute.bndlib/test/ws/maven1/m2/org/apache/commons/com.springsource.org.apache.commons.beanutils/1.7.0/bnd-1.50.0/biz.aQute.bndlib/test/ws/maven1/m2/org/apache/commons/com.springsource.org.apache.commons0000755000175000017500000000000011656076535033046 5ustar drazzibdrazzib././@LongLink0000000000000000000000000000021100000000000011557 Lustar rootrootbnd-1.50.0/biz.aQute.bndlib/test/ws/maven1/m2/org/apache/commons/com.springsource.org.apache.commons.beanutils/1.7.0/_maven.repositoriesbnd-1.50.0/biz.aQute.bndlib/test/ws/maven1/m2/org/apache/commons/com.springsource.org.apache.commons0000644000175000017500000000034511656076535033052 0ustar drazzibdrazzib#NOTE: This is an internal implementation file, its format can be changed without prior notice. #Wed Mar 30 11:38:26 CEST 2011 com.springsource.org.apache.commons.beanutils-1.7.0.pom>com.springsource.repository.bundles.external= ././@LongLink0000000000000000000000000000027100000000000011565 Lustar rootrootbnd-1.50.0/biz.aQute.bndlib/test/ws/maven1/m2/org/apache/commons/com.springsource.org.apache.commons.beanutils/1.7.0/com.springsource.org.apache.commons.beanutils-1.7.0.pom.lastUpdatedbnd-1.50.0/biz.aQute.bndlib/test/ws/maven1/m2/org/apache/commons/com.springsource.org.apache.commons0000644000175000017500000000112011656076535033042 0ustar drazzibdrazzib#NOTE: This is an internal implementation file, its format can be changed without prior notice. #Wed Mar 30 11:38:26 CEST 2011 http\://repository.springsource.com/maven/bundles/external/.lastUpdated=1301477906233 http\://repository.jboss.com/maven2/.lastUpdated=1301477905614 http\://maven.springframework.org/snapshot/.lastUpdated=1301477904839 http\://repository.springsource.com/maven/bundles/release/.lastUpdated=1301477905759 http\://repository.jboss.com/maven2/.error= http\://maven.springframework.org/snapshot/.error= http\://repository.springsource.com/maven/bundles/release/.error= ././@LongLink0000000000000000000000000000025500000000000011567 Lustar rootrootbnd-1.50.0/biz.aQute.bndlib/test/ws/maven1/m2/org/apache/commons/com.springsource.org.apache.commons.beanutils/1.7.0/com.springsource.org.apache.commons.beanutils-1.7.0.pombnd-1.50.0/biz.aQute.bndlib/test/ws/maven1/m2/org/apache/commons/com.springsource.org.apache.commons0000644000175000017500000000207411656076535033053 0ustar drazzibdrazzib 4.0.0 org.apache.commons com.springsource.org.apache.commons.beanutils jar 1.7.0 org.apache.commons com.springsource.org.apache.commons.collections 3.2.0 compile org.apache.commons com.springsource.org.apache.commons.logging 1.1.1 compile ././@LongLink0000000000000000000000000000026200000000000011565 Lustar rootrootbnd-1.50.0/biz.aQute.bndlib/test/ws/maven1/m2/org/apache/commons/com.springsource.org.apache.commons.beanutils/1.7.0/com.springsource.org.apache.commons.beanutils-1.7.0.pom.sha1bnd-1.50.0/biz.aQute.bndlib/test/ws/maven1/m2/org/apache/commons/com.springsource.org.apache.commons0000644000175000017500000000005011656076535033043 0ustar drazzibdrazzibca401599b796afc13a1d1d18ba857371184c6933././@LongLink0000000000000000000000000000016600000000000011570 Lustar rootrootbnd-1.50.0/biz.aQute.bndlib/test/ws/maven1/m2/org/apache/commons/com.springsource.org.apache.commons.beanutils/1.6.1/bnd-1.50.0/biz.aQute.bndlib/test/ws/maven1/m2/org/apache/commons/com.springsource.org.apache.commons0000755000175000017500000000000011656076535033046 5ustar drazzibdrazzib././@LongLink0000000000000000000000000000021100000000000011557 Lustar rootrootbnd-1.50.0/biz.aQute.bndlib/test/ws/maven1/m2/org/apache/commons/com.springsource.org.apache.commons.beanutils/1.6.1/_maven.repositoriesbnd-1.50.0/biz.aQute.bndlib/test/ws/maven1/m2/org/apache/commons/com.springsource.org.apache.commons0000644000175000017500000000051311656076535033047 0ustar drazzibdrazzib#NOTE: This is an internal implementation file, its format can be changed without prior notice. #Mon Apr 11 15:25:58 CEST 2011 com.springsource.org.apache.commons.beanutils-1.6.1.jar>com.springsource.repository.bundles.external= com.springsource.org.apache.commons.beanutils-1.6.1.pom>com.springsource.repository.bundles.external= ././@LongLink0000000000000000000000000000026200000000000011565 Lustar rootrootbnd-1.50.0/biz.aQute.bndlib/test/ws/maven1/m2/org/apache/commons/com.springsource.org.apache.commons.beanutils/1.6.1/com.springsource.org.apache.commons.beanutils-1.6.1.jar.sha1bnd-1.50.0/biz.aQute.bndlib/test/ws/maven1/m2/org/apache/commons/com.springsource.org.apache.commons0000644000175000017500000000005011656076535033043 0ustar drazzibdrazzibacf9dcc171b716c185310d763bf06e0aa51bf4e6././@LongLink0000000000000000000000000000026200000000000011565 Lustar rootrootbnd-1.50.0/biz.aQute.bndlib/test/ws/maven1/m2/org/apache/commons/com.springsource.org.apache.commons.beanutils/1.6.1/com.springsource.org.apache.commons.beanutils-1.6.1.pom.sha1bnd-1.50.0/biz.aQute.bndlib/test/ws/maven1/m2/org/apache/commons/com.springsource.org.apache.commons0000644000175000017500000000005011656076535033043 0ustar drazzibdrazzib3bbaae493db3b84499ef263f2d5ab91293aa450d././@LongLink0000000000000000000000000000025500000000000011567 Lustar rootrootbnd-1.50.0/biz.aQute.bndlib/test/ws/maven1/m2/org/apache/commons/com.springsource.org.apache.commons.beanutils/1.6.1/com.springsource.org.apache.commons.beanutils-1.6.1.pombnd-1.50.0/biz.aQute.bndlib/test/ws/maven1/m2/org/apache/commons/com.springsource.org.apache.commons0000644000175000017500000000207411656076535033053 0ustar drazzibdrazzib 4.0.0 org.apache.commons com.springsource.org.apache.commons.beanutils jar 1.6.1 org.apache.commons com.springsource.org.apache.commons.collections 2.1.1 compile org.apache.commons com.springsource.org.apache.commons.logging 1.0.4 compile bnd-1.50.0/biz.aQute.bndlib/test/ws/maven1/m2/org/apache/log4j/0000755000175000017500000000000011656076535023511 5ustar drazzibdrazzibbnd-1.50.0/biz.aQute.bndlib/test/ws/maven1/m2/org/apache/log4j/com.springsource.org.apache.log4j/0000755000175000017500000000000011656076535032035 5ustar drazzibdrazzib././@LongLink0000000000000000000000000000015100000000000011562 Lustar rootrootbnd-1.50.0/biz.aQute.bndlib/test/ws/maven1/m2/org/apache/log4j/com.springsource.org.apache.log4j/1.2.15/bnd-1.50.0/biz.aQute.bndlib/test/ws/maven1/m2/org/apache/log4j/com.springsource.org.apache.log4j/1.20000755000175000017500000000000011656076535032256 5ustar drazzibdrazzib././@LongLink0000000000000000000000000000023200000000000011562 Lustar rootrootbnd-1.50.0/biz.aQute.bndlib/test/ws/maven1/m2/org/apache/log4j/com.springsource.org.apache.log4j/1.2.15/com.springsource.org.apache.log4j-1.2.15.pom.sha1bnd-1.50.0/biz.aQute.bndlib/test/ws/maven1/m2/org/apache/log4j/com.springsource.org.apache.log4j/1.20000644000175000017500000000005011656076535032253 0ustar drazzibdrazzib2fac2bb83c65119a05fe4359587de32229b06510././@LongLink0000000000000000000000000000023200000000000011562 Lustar rootrootbnd-1.50.0/biz.aQute.bndlib/test/ws/maven1/m2/org/apache/log4j/com.springsource.org.apache.log4j/1.2.15/com.springsource.org.apache.log4j-1.2.15.jar.sha1bnd-1.50.0/biz.aQute.bndlib/test/ws/maven1/m2/org/apache/log4j/com.springsource.org.apache.log4j/1.20000644000175000017500000000005011656076535032253 0ustar drazzibdrazzibc506424c00adc6df9a367632c45351fb48e52216././@LongLink0000000000000000000000000000022500000000000011564 Lustar rootrootbnd-1.50.0/biz.aQute.bndlib/test/ws/maven1/m2/org/apache/log4j/com.springsource.org.apache.log4j/1.2.15/com.springsource.org.apache.log4j-1.2.15.pombnd-1.50.0/biz.aQute.bndlib/test/ws/maven1/m2/org/apache/log4j/com.springsource.org.apache.log4j/1.20000644000175000017500000000177511656076535032272 0ustar drazzibdrazzib 4.0.0 org.apache.log4j com.springsource.org.apache.log4j jar 1.2.15 javax.jms com.springsource.javax.jms 1.1.0 provided javax.mail com.springsource.javax.mail 1.4.0 true bnd-1.50.0/biz.aQute.bndlib/test/ws/maven1/mvndeploy0000755000175000017500000000033711656076535022112 0ustar drazzibdrazzibmvn -e gpg:sign-and-deploy-file -Durl=http://oss.sonatype.org/content/repositories/aqute-releases -DrepositoryId=aqute-releases -DupdateReleaseInfo=true -DpomFile=bnd.pom -Dfile=bnd.jar bnd-1.50.0/biz.aQute.bndlib/test/ws/maven1/parentpom.xml0000644000175000017500000002223011656076535022672 0ustar drazzibdrazzib 4.0.0 testPom testPom .. org.apache apache 8 org.apache.felix felix-parent pom Apache Felix 2-SNAPSHOT http://felix.apache.org/ 2006 Apache Felix is an OSGi implementation. Jira http://issues.apache.org/jira/browse/FELIX Felix Dev dev-subscribe@felix.apache.org dev-unsubscribe@felix.apache.org - http://www.mail-archive.com/dev%40felix.apache.org/ Felix Commits commits-subscribe@felix.apache.org commits-unsubscribe@felix.apache.org - http://www.mail-archive.com/commits%40felix.apache.org/ scm:svn:http://svn.apache.org/repos/asf/felix/trunk scm:svn:http://svn.apache.org/repos/asf/felix/trunk http://svn.apache.org/viewvc/felix/trunk/?root=Apache-SVN felix website file:///${user.dir}/target/site-deployed/ testPom testPom file:maven apache.snapshots snapshot plugins http://repository.apache.org/snapshots false true junit junit 4.0 test org.easymock easymock 2.4 test org.mockito mockito-all 1.7 test org.apache.maven.plugins maven-project-info-reports-plugin 2.1 org.apache.maven.plugins maven-jxr-plugin 2.1 org.apache.maven.plugins maven-surefire-report-plugin 2.4.3 org.codehaus.mojo ianal-maven-plugin 1.0-alpha-1 org.apache.rat apache-rat-plugin 0.7 org.apache.maven.plugins maven-compiler-plugin 1.3 1.3 org.apache.rat apache-rat-plugin verify check src/** src/main/appended-resources/** org.codehaus.mojo ianal-maven-plugin verify-legal-files true src/main/resources . META-INF changelog.txt org.apache.maven.wagon wagon-ssh 1.0-beta-6 org.apache.maven.plugins maven-site-plugin ${user.dir}/src/site/ org.apache.maven.plugins maven-surefire-report-plugin org.apache.maven.plugins maven-jxr-plugin org.apache.maven.plugins maven-project-info-reports-plugin index dependencies project-team mailing-list issue-tracking license scm bnd-1.50.0/biz.aQute.bndlib/test/ws/p2/0000755000175000017500000000000011656076535017276 5ustar drazzibdrazzibbnd-1.50.0/biz.aQute.bndlib/test/ws/p2/Resources/0000755000175000017500000000000011656076535021250 5ustar drazzibdrazzibbnd-1.50.0/biz.aQute.bndlib/test/ws/p2/Resources/stuff/0000755000175000017500000000000011656076535022377 5ustar drazzibdrazzibbnd-1.50.0/biz.aQute.bndlib/test/ws/p2/Resources/stuff/resource9.res0000644000175000017500000000001111656076535025022 0ustar drazzibdrazzibResource8bnd-1.50.0/biz.aQute.bndlib/test/ws/p2/Resources/resource2.res0000644000175000017500000000001111656076535023664 0ustar drazzibdrazzibResource2bnd-1.50.0/biz.aQute.bndlib/test/ws/p2/Resources/more/0000755000175000017500000000000011656076535022212 5ustar drazzibdrazzibbnd-1.50.0/biz.aQute.bndlib/test/ws/p2/Resources/more/resource6.txt0000644000175000017500000000001111656076535024660 0ustar drazzibdrazzibResource6bnd-1.50.0/biz.aQute.bndlib/test/ws/p2/Resources/more/resource7.txt0000644000175000017500000000001111656076535024661 0ustar drazzibdrazzibResource7bnd-1.50.0/biz.aQute.bndlib/test/ws/p2/Resources/more/resource8.res0000644000175000017500000000001111656076535024634 0ustar drazzibdrazzibResource8bnd-1.50.0/biz.aQute.bndlib/test/ws/p2/Resources/resource4.txt0000644000175000017500000000001111656076535023714 0ustar drazzibdrazzibResource4bnd-1.50.0/biz.aQute.bndlib/test/ws/p2/Resources/resource3.txt0000644000175000017500000000001111656076535023713 0ustar drazzibdrazzibResource3bnd-1.50.0/biz.aQute.bndlib/test/ws/p2/Resources/resource5.asc0000644000175000017500000000001111656076535023644 0ustar drazzibdrazzibResource5bnd-1.50.0/biz.aQute.bndlib/test/ws/p2/Resources/resource1.res0000644000175000017500000000001111656076535023663 0ustar drazzibdrazzibResource1bnd-1.50.0/biz.aQute.bndlib/test/ws/p2/Resources/text.txt0000644000175000017500000000001111656076535022765 0ustar drazzibdrazzibResource4bnd-1.50.0/biz.aQute.bndlib/test/ws/p2/bnd.bnd0000644000175000017500000000010311656076535020520 0ustar drazzibdrazzibBundle-Version: 1.2.3.${build} Include-Resource: -runbuilds: false bnd-1.50.0/biz.aQute.bndlib/test/ws/p2/generated/0000755000175000017500000000000011656076535021234 5ustar drazzibdrazzibbnd-1.50.0/biz.aQute.bndlib/test/ws/maven2/0000755000175000017500000000000011656076535020145 5ustar drazzibdrazzibbnd-1.50.0/biz.aQute.bndlib/test/ws/maven2/pom.xml0000644000175000017500000000161511656076535021465 0ustar drazzibdrazzib 4.0.0 group-parent artifact-parent 1.0.0-parent parentpom.xml artifact bundle Artifact Description ${user.dir} 1.0.0 org.apache.commons com.springsource.org.apache.commons.beanutils 1.6.1 bnd-1.50.0/biz.aQute.bndlib/test/ws/maven2/bnd.bnd0000644000175000017500000000001711656076535021373 0ustar drazzibdrazzib-buildpath: pombnd-1.50.0/biz.aQute.bndlib/test/ws/maven2/parentpom.xml0000644000175000017500000000115411656076535022675 0ustar drazzibdrazzib 4.0.0 parent-pom-=group parent-pom pom bnd Description testPom testPom ../maven1/m2 bnd-1.50.0/biz.aQute.bndlib/test/ws/p3/0000755000175000017500000000000011656076535017277 5ustar drazzibdrazzibbnd-1.50.0/biz.aQute.bndlib/test/ws/p3/bnd.bnd0000644000175000017500000000007511656076535020531 0ustar drazzibdrazzib -buildpath: org.apache.felix.configadmin Export-Package: * bnd-1.50.0/biz.aQute.bndlib/test/ws/p4-sub/0000755000175000017500000000000011656076535020067 5ustar drazzibdrazzibbnd-1.50.0/biz.aQute.bndlib/test/ws/p4-sub/c.bnd0000644000175000017500000000012411656076535020773 0ustar drazzibdrazzibExport-Package: * Sub-Header: c # Test if recursion is handled properly -sub: c.bndbnd-1.50.0/biz.aQute.bndlib/test/ws/p4-sub/bnd.bnd0000644000175000017500000000010711656076535021315 0ustar drazzibdrazzib-buildpath: org.apache.felix.configadmin Base-Header: base -sub: *.bnd bnd-1.50.0/biz.aQute.bndlib/test/ws/p4-sub/generated/0000755000175000017500000000000011656076535022025 5ustar drazzibdrazzibbnd-1.50.0/biz.aQute.bndlib/test/ws/p4-sub/b.bnd0000644000175000017500000000004011656076535020767 0ustar drazzibdrazzibExport-Package: * Sub-Header: b bnd-1.50.0/biz.aQute.bndlib/test/ws/p4-sub/a.bnd0000644000175000017500000000004011656076535020766 0ustar drazzibdrazzibExport-Package: * Sub-Header: a bnd-1.50.0/biz.aQute.bndlib/test/ws/cnf/0000755000175000017500000000000011656076535017523 5ustar drazzibdrazzibbnd-1.50.0/biz.aQute.bndlib/test/ws/cnf/releaserepo/0000755000175000017500000000000011656076535022031 5ustar drazzibdrazzibbnd-1.50.0/biz.aQute.bndlib/test/ws/cnf/releaserepo/org.apache.felix.configadmin/0000755000175000017500000000000011656076535027423 5ustar drazzibdrazzibbnd-1.50.0/biz.aQute.bndlib/test/ws/cnf/build.bnd0000644000175000017500000000056111656076535021311 0ustar drazzibdrazzibbuild = sometime -plugin = \ aQute.lib.deployer.FileRepo; \ location=${workspace}/cnf/releaserepo; \ readonly=false, \ aQute.lib.deployer.FileRepo; \ location=${workspace}/cnf/repo; \ readonly=truebnd-1.50.0/biz.aQute.bndlib/test/ws/cnf/repo/0000755000175000017500000000000011656076535020470 5ustar drazzibdrazzibbnd-1.50.0/biz.aQute.bndlib/test/ws/cnf/repo/libtest/0000755000175000017500000000000011656076535022136 5ustar drazzibdrazzibbnd-1.50.0/biz.aQute.bndlib/test/ws/cnf/repo/libtest/libtest-1.0.0.lib0000644000175000017500000000022011656076535024720 0ustar drazzibdrazziborg.apache.felix.configadmin; strategy=highest org.apache.felix.configadmin; strategy=lowest org.apache.felix.ipojo org.apache.felix.ipojo.arch bnd-1.50.0/biz.aQute.bndlib/test/ws/cnf/repo/org.apache.felix.ipojo.arch/0000755000175000017500000000000011656076535025640 5ustar drazzibdrazzibbnd-1.50.0/biz.aQute.bndlib/test/ws/cnf/repo/org.apache.felix.configadmin/0000755000175000017500000000000011656076535026062 5ustar drazzibdrazzibbnd-1.50.0/biz.aQute.bndlib/test/ws/cnf/repo/osgi.core/0000755000175000017500000000000011656076535022360 5ustar drazzibdrazzibbnd-1.50.0/biz.aQute.bndlib/test/ws/cnf/repo/org.apache.felix.org.apache.felix.ipojo.ant/0000755000175000017500000000000011656076535030621 5ustar drazzibdrazzibbnd-1.50.0/biz.aQute.bndlib/test/ws/cnf/repo/org.apache.felix.ipojo/0000755000175000017500000000000011656076535024724 5ustar drazzibdrazzibbnd-1.50.0/biz.aQute.bndlib/test/redirectws/0000755000175000017500000000000011656076535020477 5ustar drazzibdrazzibbnd-1.50.0/biz.aQute.bndlib/test/redirectws/bnd/0000755000175000017500000000000011656076535021242 5ustar drazzibdrazzibbnd-1.50.0/biz.aQute.bndlib/test/redirectws/bnd/ext/0000755000175000017500000000000011656076535022042 5ustar drazzibdrazzibbnd-1.50.0/biz.aQute.bndlib/test/redirectws/bnd/ext/test.bnd0000644000175000017500000000001111656076535023476 0ustar drazzibdrazzibext=true bnd-1.50.0/biz.aQute.bndlib/test/redirectws/bnd/build.bnd0000644000175000017500000000001511656076535023022 0ustar drazzibdrazzibtestcnf=true bnd-1.50.0/biz.aQute.bndlib/test/redirectws/wss/0000755000175000017500000000000011656076535021313 5ustar drazzibdrazzibbnd-1.50.0/biz.aQute.bndlib/test/redirectws/wss/ws/0000755000175000017500000000000011656076535021744 5ustar drazzibdrazzibbnd-1.50.0/biz.aQute.bndlib/test/redirectws/wss/ws/cnf0000644000175000017500000000000611656076535022431 0ustar drazzibdrazzib../.. bnd-1.50.0/biz.aQute.bndlib/test/keystore0000644000175000017500000000253711656076535020123 0ustar drazzibdrazzibþíþítest栂 ¼0‚¸0 +*‚¤š¶-KK0òõùŠá°Q`*‹?úY>ÅFÇ: #ÈÑØEìZiãœ3ïVœešë¼:=å—Ó6£xjÒæz¨ bbxBŸZ …uê‡ý'Íê¡·6cú»˜­–`ð*c•ª5»RaVŸˆ8ߖƵš¨/1Ï Þß Os}r–žF Ä¡{)’/¿XIn§fI:HÈ÷[«–Õôà}“*ÞнcÃcO„÷Q@Û ÉÈ=õŠjaˆWn2¯é0û û0ÓB)ìHQe ¡þHx^d‘6“IfÀÉ,¦Ðï&€bFOãaØ«[V{’ÝèY4†|Õã\;V=eH\¥¬”Ìà(p°¼@îåºûCºOÎÔV|‘ØëøjŽpög£ìóÜWž´:C“BC»<LJ‹ÝFv6´–\qoÎS0£³vÑJùÛf…€/3ÿIXãL!l‘ܽʱ|Ìäl9d^3W2™ašPw 6mWè×VåÎÔNë ³N†øÕŸr%‰[·6/4饸iê¨-žþšJŠ—œ£²!ä.\*Û [f‚Ú[š×®‡6ùŽ~)Ö<¹}ØÞ; .sVG²]·v°Ôùß *Z`§¬£"á&ÛÔøÅΦV Ëuä.ÇÎs¬¤ejîæ]©#þ[ ý¼^±?/ÕÔ×gåé y”ÚtÞô(Wc% êœGùúTB ÏãÏ•yRœ§™£ìê%†ê‚ñ¨÷¿Ë–úwJA}Bo/*;ƒ:/­"Øc¤Èò×u[ j^“!âHŽÔÜAS+ÖÑ`ß!†wi³¶*úæËÀIía€´—Ï?Rvà3€È^ÜØW–…Pk겕j¥¿ê&é ÿ¼vàX.509^0‚Z0‚ÃCFG]0  *†H†÷ 0t1 0 UUS10 UTexas10 UAustin10U ACME Cert Authority10U ACME Inc10U John Smith0 051007100101Z 131224100101Z0t1 0 UUS10 UTexas10 UAustin10U ACME Cert Authority10U ACME Inc10U John Smith0Ÿ0  *†H†÷ 0‰«„¦Ù·öC0ˆÌ‰ÂF˜ ›iǼ·.û véÓž#8­![30E ØO1$"QõÒx{O9äÂëUrœ;™M£;Ú©‘iåî@>„‚€ß«ŽýO—“ç÷–ø±`G`d?©„z¿æ‹žoß÷Z(Ž3) Ã¦Ž‘ÐËP¤ÿÆO0  *†H†÷ …w/Š× "„œ¢HÜœÎ2- &ü0¾ìô;¢ âvi#Oöšøm‚k‰âŸmS‚ ƒÄ•bþØYe¿ŸêP¿¾U¸ïŒƒ£®7*æWš¤ê¾þR^µ5ÞEìŸ%EÚ P»}?8DúòÞŒ.Þ@ãùídº×©¦XL)Ájèbvn×(Möˆ»â¡r^B± ðÿ«bnd-1.50.0/biz.aQute.bndlib/test/eclipse/0000755000175000017500000000000011656076535017750 5ustar drazzibdrazzibbnd-1.50.0/biz.aQute.bndlib/test/eclipse/plugins/0000755000175000017500000000000011656076535021431 5ustar drazzibdrazzibbnd-1.50.0/biz.aQute.bndlib/test/eclipse/bnd.index0000644000175000017500000000000011656076535021532 0ustar drazzibdrazzibbnd-1.50.0/biz.aQute.bndlib/test/http/0000755000175000017500000000000011656076535017303 5ustar drazzibdrazzibbnd-1.50.0/biz.aQute.bndlib/test/http/bundles/0000755000175000017500000000000011656076535020737 5ustar drazzibdrazzibbnd-1.50.0/biz.aQute.bndlib/com.springsource.org.apache.commons.logging/0000755000175000017500000000000011656076535025752 5ustar drazzibdrazzibbnd-1.50.0/biz.aQute.bndlib/com.springsource.org.apache.commons.logging/1.1.1/0000755000175000017500000000000011656076535026410 5ustar drazzibdrazzib././@LongLink0000000000000000000000000000020400000000000011561 Lustar rootrootbnd-1.50.0/biz.aQute.bndlib/com.springsource.org.apache.commons.logging/1.1.1/com.springsource.org.apache.commons.logging-1.1.1.pombnd-1.50.0/biz.aQute.bndlib/com.springsource.org.apache.commons.logging/1.1.1/com.springsource.org.a0000644000175000017500000000203511656076535032640 0ustar drazzibdrazzib 4.0.0 org.apache.commons com.springsource.org.apache.commons.logging jar 1.1.1 javax.servlet com.springsource.javax.servlet 2.4.0 provided org.apache.log4j com.springsource.org.apache.log4j 1.2.15 true ././@LongLink0000000000000000000000000000021100000000000011557 Lustar rootrootbnd-1.50.0/biz.aQute.bndlib/com.springsource.org.apache.commons.logging/1.1.1/com.springsource.org.apache.commons.logging-1.1.1.jar.sha1bnd-1.50.0/biz.aQute.bndlib/com.springsource.org.apache.commons.logging/1.1.1/com.springsource.org.a0000644000175000017500000000005011656076535032633 0ustar drazzibdrazzib7657caf2c78e1d79c74d36f2ae128a115f7cc180././@LongLink0000000000000000000000000000021100000000000011557 Lustar rootrootbnd-1.50.0/biz.aQute.bndlib/com.springsource.org.apache.commons.logging/1.1.1/com.springsource.org.apache.commons.logging-1.1.1.pom.sha1bnd-1.50.0/biz.aQute.bndlib/com.springsource.org.apache.commons.logging/1.1.1/com.springsource.org.a0000644000175000017500000000005011656076535032633 0ustar drazzibdrazzib30493963029f45cdd6fc0f2dd7aa4cc78e8f3329bnd-1.50.0/biz.aQute.bndlib/com.springsource.org.apache.commons.logging/1.0.4/0000755000175000017500000000000011656076535026412 5ustar drazzibdrazzib././@LongLink0000000000000000000000000000022000000000000011557 Lustar rootrootbnd-1.50.0/biz.aQute.bndlib/com.springsource.org.apache.commons.logging/1.0.4/com.springsource.org.apache.commons.logging-1.0.4.jar.lastUpdatedbnd-1.50.0/biz.aQute.bndlib/com.springsource.org.apache.commons.logging/1.0.4/com.springsource.org.a0000644000175000017500000000055411656076535032646 0ustar drazzibdrazzib#NOTE: This is an internal implementation file, its format can be changed without prior notice. #Wed Apr 13 12:42:00 CEST 2011 http\://repository.springsource.com/maven/bundles/external/.lastUpdated=1302691320835 http\://repository.springsource.com/maven/bundles/release/.lastUpdated=1302691318506 http\://repository.springsource.com/maven/bundles/release/.error= bnd-1.50.0/biz.aQute.bndlib/com.springsource.org.apache.commons.logging/1.0.4/_maven.repositories0000644000175000017500000000050711656076535032332 0ustar drazzibdrazzib#NOTE: This is an internal implementation file, its format can be changed without prior notice. #Wed Apr 13 12:42:00 CEST 2011 com.springsource.org.apache.commons.logging-1.0.4.pom>com.springsource.repository.bundles.external= com.springsource.org.apache.commons.logging-1.0.4.jar>com.springsource.repository.bundles.external= ././@LongLink0000000000000000000000000000021100000000000011557 Lustar rootrootbnd-1.50.0/biz.aQute.bndlib/com.springsource.org.apache.commons.logging/1.0.4/com.springsource.org.apache.commons.logging-1.0.4.jar.sha1bnd-1.50.0/biz.aQute.bndlib/com.springsource.org.apache.commons.logging/1.0.4/com.springsource.org.a0000644000175000017500000000005011656076535032635 0ustar drazzibdrazzibb34d071ef5281fb76a9f8c4a2543943485578861././@LongLink0000000000000000000000000000022000000000000011557 Lustar rootrootbnd-1.50.0/biz.aQute.bndlib/com.springsource.org.apache.commons.logging/1.0.4/com.springsource.org.apache.commons.logging-1.0.4.pom.lastUpdatedbnd-1.50.0/biz.aQute.bndlib/com.springsource.org.apache.commons.logging/1.0.4/com.springsource.org.a0000644000175000017500000000055411656076535032646 0ustar drazzibdrazzib#NOTE: This is an internal implementation file, its format can be changed without prior notice. #Wed Apr 13 12:41:57 CEST 2011 http\://repository.springsource.com/maven/bundles/external/.lastUpdated=1302691317770 http\://repository.springsource.com/maven/bundles/release/.lastUpdated=1302691317425 http\://repository.springsource.com/maven/bundles/release/.error= ././@LongLink0000000000000000000000000000020400000000000011561 Lustar rootrootbnd-1.50.0/biz.aQute.bndlib/com.springsource.org.apache.commons.logging/1.0.4/com.springsource.org.apache.commons.logging-1.0.4.pombnd-1.50.0/biz.aQute.bndlib/com.springsource.org.apache.commons.logging/1.0.4/com.springsource.org.a0000644000175000017500000000153011656076535032641 0ustar drazzibdrazzib 4.0.0 org.apache.commons com.springsource.org.apache.commons.logging jar 1.0.4 org.apache.log4j com.springsource.org.apache.log4j 1.2.15 true ././@LongLink0000000000000000000000000000021100000000000011557 Lustar rootrootbnd-1.50.0/biz.aQute.bndlib/com.springsource.org.apache.commons.logging/1.0.4/com.springsource.org.apache.commons.logging-1.0.4.pom.sha1bnd-1.50.0/biz.aQute.bndlib/com.springsource.org.apache.commons.logging/1.0.4/com.springsource.org.a0000644000175000017500000000005011656076535032635 0ustar drazzibdrazzib2041f5ba898e62d37ea8ecb3b5a334ef1c93c5b7bnd-1.50.0/biz.aQute.bndlib/src/0000755000175000017500000000000011656076535016134 5ustar drazzibdrazzibbnd-1.50.0/biz.aQute.bndlib/src/DefaultPackage.java0000644000175000017500000000004211656076535021633 0ustar drazzibdrazzib public class DefaultPackage { } bnd-1.50.0/biz.aQute.bndlib/src/test/0000755000175000017500000000000011656076535017113 5ustar drazzibdrazzibbnd-1.50.0/biz.aQute.bndlib/src/test/MacroTest.java0000755000175000017500000003720011656076535021664 0ustar drazzibdrazzibpackage test; import java.io.*; import java.util.*; import java.util.jar.*; import junit.framework.*; import aQute.lib.osgi.*; public class MacroTest extends TestCase { public void testEnv() { Processor proc = new Processor(); String s = proc.getReplacer().process("${env;USER}"); assertNotNull(s); } /** * Test the random macro */ public void testRandom() { Processor top = new Processor(); top.setProperty("a","${random}"); top.setProperty("a12","${random;12}"); String a = top.getProperty("a"); System.out.println(a); assertEquals(8, a.length()); String a12 = top.getProperty("a12"); System.out.println(a12); assertEquals(12, a12.length()); assertNotSame(a, a12); } /** * Testing an example with nesting that was supposd not to work */ public void testSuper() { Processor top = new Processor(); Processor middle = new Processor(top); Processor bottom = new Processor(middle); top.setProperty("a", "top.a"); top.setProperty("b", "top.b"); top.setProperty("c", "top.c"); top.setProperty("Bundle-Version", "0.0.0"); middle.setProperty("a", "middle.a"); middle.setProperty("b", "${^a}"); middle.setProperty("c", "-${^c}-"); middle.setProperty("Bundle-Version", "${^Bundle-Version}"); assertEquals("middle.a", bottom.getProperty("a")); assertEquals("top.a", bottom.getProperty("b")); assertEquals("-top.c-", bottom.getProperty("c")); assertEquals("0.0.0", bottom.getProperty("Bundle-Version")); } /** * Testing an example with nesting that was supposd not to work */ public void testNesting2() { Processor p = new Processor(); p.setProperty("groupId", "com.trivadis.tomas"); p.setProperty("artifactId", "common"); p.setProperty("bsn", "${if;${symbolicName};${symbolicName};${groupId}.${artifactId}}"); p.setProperty("Bundle-SymbolicName", "${bsn}"); p.setProperty("symbolicName", ""); // Not set, so get the maven name assertEquals("com.trivadis.tomas.common", p.getProperty("Bundle-SymbolicName")); // Set it p.setProperty("symbolicName", "testing"); assertEquals("testing", p.getProperty("Bundle-SymbolicName")); // And remove it p.setProperty("symbolicName", ""); assertEquals("com.trivadis.tomas.common", p.getProperty("Bundle-SymbolicName")); } /** * Verify system command */ public void testSystem() throws Exception { Processor p = new Processor(); Macro macro = new Macro(p); assertEquals("Hello World", macro.process("${system;echo Hello World}")); assertTrue(macro.process("${system;wc;Hello World}").matches("\\s*[0-9]+\\s+[0-9]+\\s+[0-9]+\\s*")); } public void testSystemFail() throws Exception { Processor p = new Processor(); Macro macro = new Macro(p); String cmd = "${system;mostidioticcommandthatwillsurelyfail}"; assertEquals(cmd, macro.process(cmd)); } /** * Verify system-allow-fail command */ public void testSystemAllowFail() throws Exception { Processor p = new Processor(); Macro macro = new Macro(p); assertEquals("", macro.process("${system-allow-fail;mostidioticcommandthatwillsurelyfail}")); } /** * Check that variables override macros. */ public void testPriority() { Processor p = new Processor(); p.setProperty("now", "not set"); Macro macro = new Macro(p); assertEquals("not set", macro.process("${now}")); } public void testNames() { Processor p = new Processor(); p.setProperty("a", "a"); p.setProperty("aa", "aa"); Macro macro = new Macro(p); assertEquals("aa", macro.process("${${a}${a}}")); } public void testVersion() throws Exception { Processor proc = new Processor(); Macro macro = new Macro(proc); assertEquals("1.0.0", macro.process("${version;===;1.0.0}")); assertEquals("1.0.1", macro.process("${version;==+;1.0.0}")); assertEquals("1.1.1", macro.process("${version;=++;1.0.0}")); assertEquals("2.1.1", macro.process("${version;+++;1.0.0}")); assertEquals("0.1.1", macro.process("${version;-++;1.0.0}")); assertEquals("0.1.1", macro.process("${version;-++;1.0.0}")); assertEquals("0.0.0", macro.process("${version;---;1.1.1}")); assertEquals("0.0", macro.process("${version;--;1.1.1}")); assertEquals("1", macro.process("${version;=;1.1.1}")); assertEquals("[1.1,1.2)", macro.process("[${version;==;1.1.1},${version;=+;1.1.1})")); assertEquals("1.1", macro.process("${version;==;1.1.1}")); assertEquals("0.1.0", macro.process("${version;=+0;0.0.1}")); assertEquals("1.0.0", macro.process("${version;+00;0.1.1}")); // Test implicit version proc.setProperty("@", "1.2.3"); assertEquals("[1.2,1.3)", macro.process("[${version;==},${version;=+})")); assertEquals("1.2", macro.process("${version;==}")); assertEquals("1.3.0", macro.process("${version;=+0}")); assertEquals("2.0.0", macro.process("${version;+00}")); assertEquals(0, proc.getErrors().size()); assertEquals(0, proc.getWarnings().size()); } public void testRange() throws Exception { Processor proc = new Processor(); Macro macro = new Macro(proc); assertEquals("[1.0,1.0]", macro.process("${range;[==,==];1.0.0}")); assertEquals("[1.0.0,1.0.1]", macro.process("${range;[===,==+];1.0.0}")); assertEquals("[0.1.0,0.1.2)", macro.process("${range;[=+0,=++);0.0.1}")); assertEquals("[0.0.9,0.1.2)", macro.process("${range;[==9,=++);0.0.1}")); assertEquals(0, proc.getErrors().size()); assertEquals(0, proc.getWarnings().size()); proc.setProperty("@", "1.2.3"); assertEquals("[1.0.0,2)", macro.process("${range;[=00,+)}")); proc.clear(); macro.process("${range;=+0,=++;0.0.1}"); assertEquals(1, proc.getErrors().size()); assertEquals(1, proc.getWarnings().size()); proc.clear(); macro.process("${range;[+,=)}"); assertEquals(1, proc.getErrors().size()); assertEquals(1, proc.getWarnings().size()); } /** * Test the wc function */ public void testWc() { Processor p = new Processor(); Macro macro = new Macro(p); String a = macro.process("${lsr;" + new File("src/test").getAbsolutePath() + ";*.java}"); assertTrue(a.contains("MacroTest.java")); assertTrue(a.contains("ManifestTest.java")); assertFalse(a.contains(".classpath")); assertFalse(a.contains("src/test/MacroTest.java")); assertFalse(a.contains("src/test/ManifestTest.java")); String b = macro.process("${lsa;" + new File("src/test").getAbsolutePath() + ";*.java}"); assertTrue(b.contains("src/test/MacroTest.java")); assertTrue(b.contains("src/test/ManifestTest.java")); } /** * Check the uniq command */ public void testUniq() { Builder builder = new Builder(); Properties p = new Properties(); p.setProperty("a", "${uniq;1}"); p.setProperty("b", "${uniq;1,2}"); p.setProperty("c", "${uniq;1;2}"); p.setProperty("d", "${uniq;1; 1, 2 , 3}"); p.setProperty("e", "${uniq;1; 1 , 2 ; 3;3,4,5,6}"); builder.setProperties(p); assertEquals("1,2,3", builder.getProperty("d")); assertEquals("1,2", builder.getProperty("b")); assertEquals("1", builder.getProperty("a")); assertEquals("1,2", builder.getProperty("c")); assertEquals("1,2,3", builder.getProperty("d")); assertEquals("1,2,3,4,5,6", builder.getProperty("e")); } /** * Test arguments with difficult characters like ; */ public void testEscapedArgs() { Builder builder = new Builder(); Properties p = new Properties(); p.setProperty("x", "${replace;1,2,3;.+;$0\\;version=1}"); builder.setProperties(p); assertEquals("1;version=1, 2;version=1, 3;version=1", builder.getProperty("x")); } /** * Check if variables that contain variables, ad nauseum, really wrk */ public void testNested() { Builder builder = new Builder(); Properties p = new Properties(); p.setProperty("a", "."); p.setProperty("b", "${a}"); p.setProperty("c", "${b}"); p.setProperty("d", "${tstamp;${format};${aug152008}}"); p.setProperty("format", "yyyy"); p.setProperty("aug152008", "1218810097322"); p.setProperty("f", "${d}"); p.setProperty("aug152008", "1218810097322"); builder.setProperties(p); assertEquals(".", builder.getProperty("c")); assertEquals("2008", builder.getProperty("d")); assertEquals(builder.getProperty("f"), builder.getProperty("d")); } public void testLoop() { Builder builder = new Builder(); Properties p = new Properties(); p.setProperty("a", "${b}"); p.setProperty("b", "${a}"); p.setProperty("d", "${e}"); p.setProperty("e", "${f}"); p.setProperty("f", "${g}"); p.setProperty("g", "${h}"); p.setProperty("h", "${d}"); builder.setProperties(p); assertEquals("${infinite:[a,b,${b}]}", builder.getProperty("a")); assertEquals("${infinite:[d,h,g,f,e,${e}]}", builder.getProperty("d")); } public void testTstamp() { // TODO Timezones // String aug152008 = "1218810097322"; // Processor p = new Processor(); // Macro m = new Macro(p); // assertEquals("200808151521", m.process("${tstamp;yyyyMMddHHmm;" + aug152008 + "}")); // // assertEquals( "2008", m.process("${tstamp;yyyy}")); } public void testIsfile() { Processor p = new Processor(); Macro m = new Macro(p); assertEquals("true", m.process("${isfile;.project}")); assertEquals("false", m.process("${isfile;thisfiledoesnotexist}")); } public void testParentFile() { Processor p = new Processor(); Macro m = new Macro(p); assertTrue(m.process("${dir;.project}").endsWith("biz.aQute.bndlib")); } public void testBasename() { Processor p = new Processor(); Macro m = new Macro(p); assertEquals("biz.aQute.bndlib", m.process("${basename;${dir;.project}}")); } public void testMavenVersionMacro() throws Exception { Builder builder = new Builder(); Properties p = new Properties(); p.setProperty("Export-Package", "org.objectweb.*;version=1.5-SNAPSHOT"); builder.setProperties(p); builder.setClasspath(new File[] { new File("jar/asm.jar") }); Jar jar = builder.build(); Manifest manifest = jar.getManifest(); String export = manifest.getMainAttributes().getValue("Export-Package"); assertNotNull(export); assertTrue("Test snapshot version", export.contains("1.5.0.SNAPSHOT")); } /** * Check if we can check for the defintion of a variable */ public void testDef() { Processor p = new Processor(); p.setProperty("set.1", "1"); p.setProperty("set.2", "2"); Macro m = new Macro(p); assertEquals("NO", m.process("${if;${def;set.3};YES;NO}")); assertEquals("YES", m.process("${if;${def;set.1};YES;NO}")); assertEquals("YES", m.process("${if;${def;set.2};YES;NO}")); } /** * NEW */ public void testReplace() { Processor p = new Processor(); p.setProperty("specs", "a,b, c, d"); Macro m = new Macro(p); assertEquals("xay, xby, xcy, xdy", m.process("${replace;${specs};([^\\s]+);x$1y}")); } public void testToClassName() { Processor p = new Processor(); Macro m = new Macro(p); assertEquals("com.acme.test.Test", m.process("${toclassname;com/acme/test/Test.class}")); assertEquals("Test", m.process("$")); assertEquals("Test,com.acme.test.Test", m .process("${toclassname;Test.class, com/acme/test/Test.class}")); assertEquals("", m.process("$(toclassname;Test)")); assertEquals("com/acme/test/Test.class", m.process("$[toclasspath;com.acme.test.Test]")); assertEquals("Test.class", m.process("${toclasspath;Test}")); assertEquals("Test.class,com/acme/test/Test.class", m .process("${toclasspath;Test,com.acme.test.Test}")); } public void testFindPath() throws IOException { Analyzer analyzer = new Analyzer(); analyzer.setJar(new File("jar/asm.jar")); Macro m = new Macro(analyzer); assertTrue(m.process("${findname;(.*)\\.class;$1.xyz}").indexOf("FieldVisitor.xyz,") >= 0); assertTrue(m.process("${findname;(.*)\\.class;$1.xyz}").indexOf("MethodVisitor.xyz,") >= 0); assertTrue(m.process("${findpath;(.*)\\.class}").indexOf( "org/objectweb/asm/AnnotationVisitor.class,") >= 0); assertTrue(m.process("${findpath;(.*)\\.class}").indexOf( "org/objectweb/asm/ByteVector.class, org/objectweb/asm/ClassAdapter.class,") >= 0); assertEquals("META-INF/MANIFEST.MF", m.process("${findpath;META-INF/MANIFEST.MF}")); assertEquals("Label.class", m.process("${findname;Label\\..*}")); assertEquals("Adapter, Visitor, Writer", m.process("${findname;Method(.*)\\.class;$1}")); } public void testWarning() { Processor p = new Processor(); p.setProperty("three", "333"); p.setProperty("empty", ""); p.setProperty("real", "true"); Macro m = new Macro(p); m.process(" ${warning;xw;1;2;3 ${three}}"); m.process(" ${error;xe;1;2;3 ${three}}"); m.process(" ${if;1;$}"); assertEquals("xw", p.getWarnings().get(0)); assertEquals("1", p.getWarnings().get(1)); assertEquals("2", p.getWarnings().get(2)); assertEquals("3 333", p.getWarnings().get(3)); assertEquals("xe", p.getErrors().get(0)); assertEquals("1", p.getErrors().get(1)); assertEquals("2", p.getErrors().get(2)); assertEquals("3 333", p.getErrors().get(3)); } public void testNestedReplace() { Processor p = new Processor(); Macro m = new Macro(p); String value = m.process("xx$(replace;1.2.3-SNAPSHOT;(\\d(\\.\\d)+).*;$1)xx"); System.out.println(p.getWarnings()); assertEquals("xx1.2.3xx", value); assertEquals("xx1.222.3xx", m .process("xx$(replace;1.222.3-SNAPSHOT;(\\d+(\\.\\d+)+).*;$1)xx")); p.setProperty("a", "aaaa"); assertEquals("[cac]", m.process("$[replace;acaca;a(.*)a;[$1]]")); assertEquals("xxx", m.process("$(replace;yxxxy;[^x]*(x+)[^x]*;$1)")); assertEquals("xxx", m.process("$(replace;yxxxy;([^x]*(x+)[^x]*);$2)")); } public void testParentheses() { Processor p = new Processor(); Macro m = new Macro(p); String value = m.process("$(replace;();(\\(\\));$1)"); assertEquals("()", value); } public void testSimple() { Processor p = new Processor(); p.setProperty("a", "aaaa"); Macro m = new Macro(p); assertEquals("aaaa", m.process("${a}")); assertEquals("aaaa", m.process("$")); assertEquals("aaaa", m.process("$(a)")); assertEquals("aaaa", m.process("$[a]")); assertEquals("xaaaax", m.process("x${a}x")); assertEquals("xaaaaxaaaax", m.process("x${a}x${a}x")); } public void testFilter() { Processor p = new Processor(); p.setProperty("a", "aaaa"); Macro m = new Macro(p); assertEquals("aa,cc,ee", m.process("${filter;aa,bb,cc,dd,ee,ff;[ace]+}")); assertEquals("aaaa,cc,ee", m.process("${filter;${a},bb,cc,dd,ee,ff;[ace]+}")); assertEquals("bb,dd,ff", m.process("${filter;${a},bb,cc,dd,ee,ff;[^ace]+}")); } public void testFilterOut() { Processor p = new Processor(); p.setProperty("a", "aaaa"); Macro m = new Macro(p); assertEquals("bb,dd,ff", m.process("${filterout;aa,bb,cc,dd,ee,ff;[ace]+}")); assertEquals("bb,dd,ff", m.process("${filterout;${a},bb,cc,dd,ee,ff;[ace]+}")); assertEquals("aaaa,cc,ee", m.process("${filterout;${a},bb,cc,dd,ee,ff;[^ace]+}")); } public void testSort() { Processor p = new Processor(); p.setProperty("a", "aaaa"); Macro m = new Macro(p); assertEquals("aa,bb,cc,dd,ee,ff", m.process("${sort;aa,bb,cc,dd,ee,ff}")); assertEquals("aa,bb,cc,dd,ee,ff", m.process("${sort;ff,ee,cc,bb,dd,aa}")); assertEquals("aaaa,bb,cc,dd,ee,ff", m.process("${sort;ff,ee,cc,bb,dd,$}")); } public void testJoin() { Processor p = new Processor(); p.setProperty("a", "aaaa"); Macro m = new Macro(p); assertEquals("aa,bb,cc,dd,ee,ff", m.process("${join;aa,bb,cc,dd,ee,ff}")); assertEquals("aa,bb,cc,dd,ee,ff", m.process("${join;aa,bb,cc;dd,ee,ff}")); assertEquals("aa,bb,cc,dd,ee,ff", m.process("${join;aa;bb;cc;dd;ee,ff}")); } public void testIf() { Processor p = new Processor(); p.setProperty("a", "aaaa"); Macro m = new Macro(p); assertEquals("aaaa", m.process("${if;1;$}")); assertEquals("", m.process("${if;;$}")); assertEquals("yes", m.process("${if;;$;yes}")); } public void testLiteral() { Processor p = new Processor(); p.setProperty("a", "aaaa"); Macro m = new Macro(p); assertEquals("${aaaa}", m.process("${literal;$}")); } } bnd-1.50.0/biz.aQute.bndlib/src/test/BuilderTest.java0000755000175000017500000016677011656076535022230 0ustar drazzibdrazzibpackage test; import java.io.*; import java.util.*; import java.util.jar.*; import javax.print.attribute.standard.MediaSize.*; import aQute.bnd.test.*; import aQute.lib.osgi.*; import aQute.libg.header.*; public class BuilderTest extends BndTestCase { /** * Test the name section */ public void testNamesection() throws Exception { Builder b = new Builder(); b.addClasspath( new File("jar/osgi.jar")); b.setProperty(Constants.NAMESECTION, "org/osgi/service/event/*;MD5='${md5;${@}}';SHA1='${sha1;${@}}';MD5H='${md5;${@};hex}'"); b.setProperty(Constants.PRIVATE_PACKAGE, "org.osgi.service.event"); Jar build = b.build(); assertOk(b); build.calcChecksums(new String[]{"MD5","SHA1"}); Manifest m = build.getManifest(); m.write(System.out); assertNotNull(m.getAttributes("org/osgi/service/event/EventAdmin.class").getValue("MD5")); assertNotNull(m.getAttributes("org/osgi/service/event/EventAdmin.class").getValue("SHA1")); assertEquals( m.getAttributes("org/osgi/service/event/EventAdmin.class").getValue("MD5-Digest"), m.getAttributes("org/osgi/service/event/EventAdmin.class").getValue("MD5")); } /** * Check of the use of x- directives are not skipped. bnd allows x- * directives in the import/export clauses but strips other ones. * @throws Exception */ public void testXDirectives() throws Exception { Builder b = new Builder(); b.addClasspath( new File("jar/osgi.jar")); b.setProperty("Export-Package", "org.osgi.framework;x-foo:=true;bar:=false"); Jar jar = b.build(); Manifest m = jar.getManifest(); String s = m.getMainAttributes().getValue("Export-Package"); assertTrue( s.contains("x-foo:")); assertEquals( 1, b.getWarnings().size()); assertTrue( b.getWarnings().get(0).contains("bar:")); } /** * Check of SNAPSHOT is replaced with the -snapshot instr * @throws Exception */ public void testSnapshot() throws Exception { Builder b = new Builder(); b.setProperty("-resourceonly", "true"); b.setProperty("-snapshot", "TIMESTAMP"); b.setProperty("Bundle-Version", "1.0-SNAPSHOT"); Jar jar = b.build(); Manifest m = jar.getManifest(); assertEquals("1.0.0.TIMESTAMP",m.getMainAttributes().getValue("Bundle-Version")); } /** * Check if do not copy works on files */ public void testDoNotCopy() throws Exception { Builder b = new Builder(); b.setProperty("-resourceonly", "true"); b.setProperty("-donotcopy", ".*\\.jar|\\..*"); b.setProperty("Include-Resource", "jar"); b.build(); System.out.println(Processor.join(b.getErrors(), "\n")); System.out.println(Processor.join(b.getWarnings(), "\n")); assertEquals(0, b.getErrors().size()); assertEquals(0, b.getWarnings().size()); Set names = b.getJar().getResources().keySet(); assertEquals(6, names.size()); assertTrue(names.contains("AnnotationWithJSR14.jclass")); assertTrue(names.contains("mandatorynoversion.bnd")); assertTrue(names.contains("mina.bar")); assertTrue(names.contains("minax.bnd")); assertTrue(names.contains("rox.bnd")); assertTrue(names.contains("WithAnnotations.jclass")); } /** * Check if do not copy works on files */ public void testDoNotCopyDS() throws Exception { Builder b = new Builder(); b.setProperty("-resourceonly", "true"); b.setProperty("Include-Resource", "jar/"); b.build(); System.out.println(Processor.join(b.getErrors(), "\n")); System.out.println(Processor.join(b.getWarnings(), "\n")); assertEquals(0, b.getErrors().size()); assertEquals(0, b.getWarnings().size()); Set names = b.getJar().getResources().keySet(); assertFalse(names.contains(".DS_Store")); } /** * No error is generated when a file is not found. * */ public void testFileNotFound() throws Exception { Builder b = new Builder(); b.setPedantic(true); b.setProperty("-classpath", "xyz.jar"); b.setProperty("Include-Resource", "lib=lib, jar/osgi.jar"); b.setProperty("-resourceonly", "true"); b.build(); System.out.println(Processor.join(b.getErrors(), "\n")); System.out.println("xx"); System.out.println(Processor.join(b.getWarnings(), "\n")); assertEquals(1, b.getErrors().size()); assertEquals(1, b.getWarnings().size()); } /** * bnd seems to pick the wrong version if a packageinfo is available * multiple times. * * @throws Exception */ public void testMultiplePackageInfo() throws Exception { Builder b = new Builder(); b.addClasspath(new File("jar/osgi.jar")); b.addClasspath(new File("jar/osgi.core.jar")); b.setProperty(Constants.PRIVATE_PACKAGE, "org.osgi.service.packageadmin"); b.build(); String version = b.getImports().get("org.osgi.framework").get(Constants.VERSION_ATTRIBUTE); assertEquals("[1.3,2)", version); } /** * Test the from: directive on expanding packages. */ public void testFromOSGiDirective() throws Exception { Builder b = new Builder(); b.addClasspath(new File("jar/osgi.jar")); b.addClasspath(new File("jar/org.eclipse.osgi-3.5.0.jar")); b.setProperty("Export-Package", "org.osgi.framework;from:=osgi"); b.build(); System.out.println(Processor.join(b.getErrors(), "\n")); System.out.println(Processor.join(b.getWarnings(), "\n")); assertEquals(0, b.getErrors().size()); assertEquals(0, b.getWarnings().size()); assertEquals("1.3", b.getExports().get("org.osgi.framework").get("version")); } public void testFromEclipseDirective() throws Exception { Builder b = new Builder(); b.addClasspath(new File("jar/osgi.jar")); b.addClasspath(new File("jar/org.eclipse.osgi-3.5.0.jar")); b.setProperty("Export-Package", "org.osgi.framework;from:=org.eclipse.osgi-3.5.0"); b.build(); System.out.println(Processor.join(b.getErrors(), "\n")); System.out.println(Processor.join(b.getWarnings(), "\n")); assertEquals(0, b.getErrors().size()); assertEquals(0, b.getWarnings().size()); assertEquals("1.3", b.getExports().get("org.osgi.framework").get("version")); } /** * Test the provide package */ public void testProvidedVersion() throws Exception { Builder b = new Builder(); b.addClasspath(new File("jar/osgi.jar")); b.addClasspath(new File("bin")); b.setProperty(Constants.EXPORT_PACKAGE, "org.osgi.service.event;provide:=true"); b.setProperty("Private-Package", "test.refer"); Jar jar = b.build(); String ip = jar.getManifest().getMainAttributes().getValue(Constants.IMPORT_PACKAGE); Map> map = Processor.parseHeader(ip, null); assertEquals("[1.0,1.1)", map.get("org.osgi.service.event").get("version")); } public void testUnProvidedVersion() throws Exception { Builder b = new Builder(); b.addClasspath(new File("jar/osgi.jar")); b.addClasspath(new File("bin")); b.setProperty(Constants.EXPORT_PACKAGE, "org.osgi.service.event;provide:=false"); b.setProperty("Private-Package", "test.refer"); Jar jar = b.build(); String ip = jar.getManifest().getMainAttributes().getValue(Constants.IMPORT_PACKAGE); Map> map = Processor.parseHeader(ip, null); assertEquals("[1.0,2)", map.get("org.osgi.service.event").get("version")); } /** * Complaint that exported versions were not picked up from external bundle. */ public void testExportedVersionsNotPickedUp() throws Exception { Builder b = new Builder(); b.addClasspath(new File("jar/jsr311-api-1.1.1.jar")); b.setProperty("Export-Package", "javax.ws.rs.core"); Jar jar = b.build(); String ip = jar.getManifest().getMainAttributes().getValue(Constants.EXPORT_PACKAGE); Map> map = Processor.parseHeader(ip, null); assertEquals("1.1.1", map.get("javax.ws.rs.core").get("version")); } /** * Test where the version comes from: Manifest or packageinfo * * @throws Exception */ public void testExportVersionSource() throws Exception { Manifest manifest = new Manifest(); manifest.getMainAttributes().putValue("Export-Package", "org.osgi.service.event;version=100"); // Remove packageinfo Jar manifestOnly = new Jar(new File("jar/osgi.jar")); manifestOnly.remove("org/osgi/service/event/packageinfo"); manifestOnly.setManifest(manifest); // Remove manifest Jar packageInfoOnly = new Jar(new File("jar/osgi.jar")); packageInfoOnly.setManifest(new Manifest()); Jar both = new Jar(new File("jar/osgi.jar")); both.setManifest(manifest); // Only version in manifest Builder bms = new Builder(); bms.addClasspath(manifestOnly); bms.setProperty("Export-Package", "org.osgi.service.event"); bms.build(); String s = bms.getExports().get("org.osgi.service.event").get("version"); assertEquals("100", s); // Only version in packageinfo Builder bpinfos = new Builder(); bpinfos.addClasspath(packageInfoOnly); bpinfos.setProperty("Export-Package", "org.osgi.service.event"); bpinfos.build(); s = bpinfos.getExports().get("org.osgi.service.event").get("version"); assertEquals("1.0.1", s); // // Version in manifest + packageinfo // Builder bboth = new Builder(); // bboth.addClasspath(both); // bboth.setProperty("Export-Package", "org.osgi.service.event"); // bboth.build(); // s = bboth.getExports().get("org.osgi.service.event").get("version"); // assertEquals("100", s); } /** * Test where the version comes from: Manifest or packageinfo * * @throws Exception */ public void testImportVersionSource() throws Exception { Jar ms = new Jar("manifestsource"); Jar pinfos = new Jar("packageinfosource"); Jar both = new Jar("both"); Manifest mms = new Manifest(); mms.getMainAttributes().putValue("Export-Package", "org.osgi.service.event; version=100"); ms.setManifest(mms); pinfos.putResource("org/osgi/service/event/packageinfo", new EmbeddedResource("version 99".getBytes(), 0)); Manifest mboth = new Manifest(); mboth.getMainAttributes().putValue("Export-Package", "org.osgi.service.event; version=100"); both.putResource("org/osgi/service/event/packageinfo", new EmbeddedResource("version 99".getBytes(), 0)); both.setManifest(mboth); // Only version in manifest Builder bms = new Builder(); bms.addClasspath(ms); bms.setProperty("Import-Package", "org.osgi.service.event"); bms.build(); String s = bms.getImports().get("org.osgi.service.event").get("version"); assertEquals("[100.0,101)", s); // Only version in packageinfo Builder bpinfos = new Builder(); bpinfos.addClasspath(pinfos); bpinfos.setProperty("Import-Package", "org.osgi.service.event"); bpinfos.build(); s = bpinfos.getImports().get("org.osgi.service.event").get("version"); assertEquals("[99.0,100)", s); // Version in manifest + packageinfo Builder bboth = new Builder(); bboth.addClasspath(both); bboth.setProperty("Import-Package", "org.osgi.service.event"); bboth.build(); s = bboth.getImports().get("org.osgi.service.event").get("version"); assertEquals("[100.0,101)", s); } public void testNoImportDirective() throws Exception { Builder b = new Builder(); b.setProperty("Export-Package", "org.osgi.util.measurement, org.osgi.service.http;-noimport:=true"); b.setProperty("Private-Package", "org.osgi.framework, test.refer"); b.addClasspath(new File("jar/osgi.jar")); b.addClasspath(new File("bin")); Jar jar = b.build(); Manifest m = jar.getManifest(); String imports = m.getMainAttributes().getValue("Import-Package"); assertTrue(imports.contains("org.osgi.util.measurement")); // referred // to but no // private // references // (does not // use fw). assertFalse(imports.contains("org.osgi.service.http")); // referred to // but no // private // references // (does not use // fw). } public void testNoImportDirective2() throws Exception { Builder b = new Builder(); b.setProperty("Export-Package", "org.osgi.util.measurement;-noimport:=true, org.osgi.service.http"); b.setProperty("Private-Package", "org.osgi.framework, test.refer"); b.addClasspath(new File("jar/osgi.jar")); b.addClasspath(new File("bin")); Jar jar = b.build(); Manifest m = jar.getManifest(); String imports = m.getMainAttributes().getValue("Import-Package"); assertFalse(imports.contains("org.osgi.util.measurement")); // referred // to but no // private // references // (does not // use fw). assertTrue(imports.contains("org.osgi.service.http")); // referred to // but no // private // references // (does not use // fw). } public void testAutoNoImport() throws Exception { Builder b = new Builder(); b.setProperty( "Export-Package", "org.osgi.service.event, org.osgi.service.packageadmin, org.osgi.util.measurement, org.osgi.service.http;-noimport:=true"); b.setProperty("Private-Package", "org.osgi.framework, test.refer"); b.addClasspath(new File("jar/osgi.jar")); b.addClasspath(new File("bin")); Jar jar = b.build(); Manifest m = jar.getManifest(); String imports = m.getMainAttributes().getValue("Import-Package"); assertFalse(imports.contains("org.osgi.service.packageadmin")); // no // internal // references assertFalse(imports.contains("org.osgi.util.event")); // refers to // private // framework assertTrue(imports.contains("org.osgi.util.measurement")); // referred // to but no // private // references // (does not // use fw). assertFalse(imports.contains("org.osgi.service.http")); // referred to // but no // private // references // (does not use // fw). } public void testWab() throws Exception { Builder b = new Builder(); b.setProperty("-wablib", "jar/asm.jar, jar/easymock.jar"); b.setProperty("-wab", "jar/osgi.jar"); b.setProperty("-includeresource", "OSGI-INF/xml/x.xml;literal=\"text\""); b.setProperty("Private-Package", "org.osgi.framework"); b.addClasspath(new File("jar/osgi.jar")); Jar jar = b.build(); diagnose(b); Manifest m = jar.getManifest(); assertNotNull(m); assertEquals("WEB-INF/classes,WEB-INF/lib/asm.jar,WEB-INF/lib/easymock.jar", m .getMainAttributes().getValue("Bundle-ClassPath")); assertNotNull(jar.getResource("WEB-INF/lib/asm.jar")); assertNotNull(jar.getResource("WEB-INF/classes/org/osgi/framework/BundleContext.class")); assertNotNull(jar.getResource("osgi.jar")); assertNotNull(jar.getResource("OSGI-INF/xml/x.xml")); } private void diagnose(Builder b) { System.out.println(Processor.join(b.getErrors(), "\n")); System.out.println(Processor.join(b.getWarnings(), "\n")); assertEquals(0, b.getErrors().size()); assertEquals(0, b.getWarnings().size()); } public void testRemoveHeaders() throws Exception { Builder b = new Builder(); b.setProperty("Private-Package", "org.osgi.framework"); b.setProperty("T1", "1"); b.setProperty("T2", "1"); b.setProperty("T1_2", "1"); b.setProperty("-removeheaders", "!T1_2,T1*"); b.addClasspath(new File("jar/osgi.jar")); Jar jar = b.build(); diagnose(b); Manifest m = jar.getManifest(); assertNotNull(m); assertEquals("1", m.getMainAttributes().getValue("T2")); assertEquals("1", m.getMainAttributes().getValue("T1_2")); assertEquals(null, m.getMainAttributes().getValue("T1")); } public void testNoManifest() throws Exception { Builder b = new Builder(); b.setProperty("-nomanifest", "true"); b.setProperty("Include-Resource", "WEB-INF/classes=@jar/asm.jar"); Jar jar = b.build(); diagnose(b); File f = new File("tmp.jar"); f.deleteOnExit(); jar.write(f); JarInputStream jin = new JarInputStream(new FileInputStream(f)); Manifest m = jin.getManifest(); assertNull(m); } public void testClassesonNoBCP() throws Exception { Builder b = new Builder(); b.setProperty("-resourceonly", "true"); b.setProperty("Include-Resource", "WEB-INF/classes=@jar/asm.jar"); b.setProperty("-nomanifest", "true"); b.build(); diagnose(b); } public void testClassesonBCP() throws Exception { Builder b = new Builder(); b.setProperty("-resourceonly", "true"); b.setProperty("Include-Resource", "WEB-INF/classes=@jar/asm.jar"); b.setProperty("Bundle-ClassPath", "WEB-INF/classes"); b.build(); diagnose(b); } public void testInScopeExport() throws Exception { Builder b = new Builder(); b.setProperty("Export-Package", "aQute.bnd.*"); b.addClasspath(new File("bin")); List project = Arrays.asList(b.getFile("bin/aQute/bnd/build/Project.class")); assertTrue(b.isInScope(project)); List nonexistent = Arrays.asList(b.getFile("bin/aQute/bnd/build/Abc.xyz")); assertTrue(b.isInScope(nonexistent)); List outside = Arrays.asList(b.getFile("bin/test/AnalyzerTest.class")); assertFalse(b.isInScope(outside)); } public void testInScopePrivate() throws Exception { Builder b = new Builder(); b.setProperty("Private-Package", "!aQute.bnd.build,aQute.bnd.*"); b.addClasspath(new File("bin")); List project = Arrays.asList(b.getFile("bin/aQute/bnd/build/Project.class")); assertFalse(b.isInScope(project)); List nonexistent = Arrays.asList(b.getFile("bin/aQute/bnd/acb/Def.xyz")); assertTrue(b.isInScope(nonexistent)); List outside = Arrays.asList(b.getFile("bin/test/AnalyzerTest.class")); assertFalse(b.isInScope(outside)); } public void testExtra() throws Exception { Builder b = new Builder(); b.setProperty("Include-Resource", "jar/osgi.jar;extra=itworks, www/xyz.jar=jar/osgi.jar;extra='italsoworks'"); b.setProperty("-resourceonly", "true"); Jar jar = b.build(); Resource r = jar.getResource("osgi.jar"); assertNotNull(r); assertEquals("itworks", r.getExtra()); Resource r2 = jar.getResource("www/xyz.jar"); assertNotNull(r2); assertEquals("italsoworks", r2.getExtra()); } /** * Create a jar with something in the default package. */ public void testIncludeDefaultPackage() { Builder b = new Builder(); b.setProperty("Private-Package", "."); } /** * Got a split package warning during verify when private overlaps with * export */ public void testSplitWhenPrivateOverlapsExport() throws Exception { Builder b = new Builder(); b.addClasspath(new File("jar/osgi.jar")); b.setProperty("Private-Package", "org.osgi.service.*"); b.setProperty("Export-Package", "org.osgi.service.event"); b.build(); ok(b); } static void ok(Processor p) { System.out.println("Errors " + p.getErrors()); System.out.println("Warnings " + p.getWarnings()); assertEquals(0, p.getErrors().size()); assertEquals(0, p.getWarnings().size()); } public void testMacroBasedExpansion() throws Exception { Processor proc = new Processor(); Builder builder = new Builder(proc); builder.setProperty("Export-Package", "${spec.packages}"); proc.setProperty("spec.packages", "${core.packages}, ${cmpn.packages}, ${mobile.packages}"); proc.setProperty("core.specs", "org.osgi.service.packageadmin, org.osgi.service.permissionadmin"); proc.setProperty("core.packages", "${replace;${core.specs};.+;$0.*}"); proc.setProperty("cmpn.specs", "org.osgi.service.event, org.osgi.service.cu"); proc.setProperty("cmpn.packages", "${replace;${cmpn.specs};.+;$0.*}"); proc.setProperty("mobile.specs", "org.osgi.service.wireadmin, org.osgi.service.log, org.osgi.service.cu"); proc.setProperty("mobile.packages", "${replace;${mobile.specs};.+;$0.*}"); builder.addClasspath(new File("jar/osgi.jar")); Jar jar = builder.build(); System.out.println("Warnings: " + builder.getWarnings()); System.out.println("Errors : " + builder.getErrors()); assertEquals(1, builder.getErrors().size()); assertEquals(0, builder.getWarnings().size()); assertTrue(builder.getErrors().get(0).contains("service.cu.*")); Manifest m = jar.getManifest(); String exports = m.getMainAttributes().getValue("Export-Package"); System.out.println(exports); assertTrue(exports.contains("*")); } /** * Make resolution dependent on the fact that a package is on the classpath * or not */ public void testConditionalResolution() throws Exception { Builder b = new Builder(); b.setProperty("res", "${if;${exporters;${@package}};mandatory;optional}"); b.setProperty("Import-Package", "*;resolution:=\\${res}"); b.setProperty("Export-Package", "org.osgi.service.io, org.osgi.service.log"); b.addClasspath(new File("jar/osgi.jar")); b.build(); Map ioimports = b.getImports().get("javax.microedition.io"); Map fwimports = b.getImports().get("org.osgi.framework"); assertNotNull(ioimports); assertNotNull(fwimports); assertTrue(ioimports.containsKey("resolution:")); assertTrue(fwimports.containsKey("resolution:")); assertEquals("optional", ioimports.get("resolution:")); assertEquals("mandatory", fwimports.get("resolution:")); } /** * Test private imports. We first build a jar with a import:=private packge. * Then place it * * @throws Exception */ // public void testPrivateImport() throws Exception { // Builder b = new Builder(); // b.addClasspath(new File("jar/osgi.jar")); // b // .setProperty("Export-Package", // "org.osgi.service.cm;-import:=private, // org.osgi.framework;-import:=private"); // Jar osgi = b.build(); // assertTrue(osgi.hasDirectory("org/osgi/framework")); // assertTrue(osgi.hasDirectory("org/osgi/service/cm")); // System.out.println("export " + // b.getExports().get("org.osgi.service.cm")); // assertTrue(b.getExports().get("org.osgi.service.cm").containsKey(Constants.IMPORT_DIRECTIVE)); // assertTrue(b.getExports().get("org.osgi.framework").containsKey(Constants.IMPORT_DIRECTIVE)); // // Builder c = new Builder(); // c.addClasspath(osgi); // c.addClasspath(new File("bin")); // c.setProperty("Private-Package", "test.privateimport"); // Jar pi = c.build(); // // assertTrue(pi.getDirectories().containsKey("org/osgi/framework")); // assertTrue(pi.getDirectories().containsKey("org/osgi/service/cm")); // assertEquals("no error", 0, b.getErrors().size()); // assertEquals("no error", 0, c.getErrors().size()); // assertEquals("no warning", 0, b.getWarnings().size()); // assertEquals("no warning", 0, c.getWarnings().size()); // } public void testClassnames() throws Exception { Builder b = new Builder(); b.addClasspath(new File("jar/osgi.jar")); b.addClasspath(new File("jar/ds.jar")); b.addClasspath(new File("jar/ifc112.jar")); b.setProperty("Export-Package", "*"); b.setProperty("C1", "${classes;implementing;org.osgi.service.component.*}"); b.setProperty("C2", "${classes;extending;org.xml.sax.helpers.*}"); b.setProperty("C3", "${classes;importing;org.xml.sax}"); b.setProperty("C3", "${classes;importing;org.xml.sax}"); b.setProperty("C4", "${classes;named;*Parser*}"); b.setProperty("C5", "${classes;named;*Parser*;version;45.*}"); Jar jar = b.build(); Manifest m = jar.getManifest(); Attributes main = m.getMainAttributes(); assertList( asl("org.eclipse.equinox.ds.service.ComponentContextImpl,org.eclipse.equinox.ds.service.ComponentFactoryImpl,org.eclipse.equinox.ds.service.ComponentInstanceImpl"), asl(main.getValue("C1"))); assertList(asl("org.eclipse.equinox.ds.parser.ElementHandler, " + "org.eclipse.equinox.ds.parser.IgnoredElement," + "org.eclipse.equinox.ds.parser.ImplementationElement," + "org.eclipse.equinox.ds.parser.ParserHandler, " + "org.eclipse.equinox.ds.parser.PropertiesElement," + "org.eclipse.equinox.ds.parser.PropertyElement, " + "org.eclipse.equinox.ds.parser.ProvideElement, " + "org.eclipse.equinox.ds.parser.ReferenceElement, " + "org.eclipse.equinox.ds.parser.ServiceElement," + "org.eclipse.equinox.ds.parser.ComponentElement"), asl(main.getValue("C2"))); assertList( asl("org.eclipse.equinox.ds.parser.ComponentElement,org.eclipse.equinox.ds.parser.ElementHandler,org.eclipse.equinox.ds.parser.IgnoredElement,org.eclipse.equinox.ds.parser.ImplementationElement,org.eclipse.equinox.ds.parser.Parser,org.eclipse.equinox.ds.parser.ParserHandler,org.eclipse.equinox.ds.parser.PropertiesElement,org.eclipse.equinox.ds.parser.PropertyElement,org.eclipse.equinox.ds.parser.ProvideElement,org.eclipse.equinox.ds.parser.ReferenceElement,org.eclipse.equinox.ds.parser.ServiceElement"), asl(main.getValue("C3"))); assertList( asl("org.eclipse.equinox.ds.parser.XMLParserNotAvailableException,org.eclipse.equinox.ds.parser.Parser,org.eclipse.equinox.ds.parser.ParserHandler,netscape.application.HTMLParser,org.eclipse.equinox.ds.parser.ParserConstants,org.osgi.util.xml.XMLParserActivator"), asl(main.getValue("C4"))); assertEquals("netscape.application.HTMLParser", main.getValue("C5")); } void assertList(Collection a, Collection b) { List onlyInA = new ArrayList(); onlyInA.addAll(a); onlyInA.removeAll(b); List onlyInB = new ArrayList(); onlyInB.addAll(b); onlyInB.removeAll(a); if (onlyInA.isEmpty() && onlyInB.isEmpty()) return; fail("Lists are not equal, only in A: " + onlyInA + ",\n and only in B: " + onlyInB); } Collection asl(String s) { return new TreeSet(Processor.split(s)); } public void testImportMicroNotTruncated() throws Exception { Builder b = new Builder(); b.addClasspath(new File("jar/osgi.jar")); b.setProperty("Import-Package", "org.osgi.service.event;version=${@}"); b.build(); String s = b.getImports().get("org.osgi.service.event").get("version"); assertEquals("1.0.1", s); } public void testImportMicroTruncated() throws Exception { Builder b = new Builder(); b.addClasspath(new File("jar/osgi.jar")); b.setProperty("Import-Package", "org.osgi.service.event"); b.build(); String s = b.getImports().get("org.osgi.service.event").get("version"); assertEquals("[1.0,2)", s); } /* * Bnd must expand the bnd.info file in a package. */ public void testBndInfo() throws Exception { Builder b = new Builder(); b.addClasspath(new File("bin")); b.setProperty("Export-Package", "test"); b.setProperty("a", "aaa"); Jar jar = b.build(); Resource r = jar.getResource("test/bnd.info"); Properties bndinfo = new Properties(); InputStream in = r.openInputStream(); bndinfo.load(in); in.close(); assertEquals("aaa", bndinfo.getProperty("a")); assertEquals("${b}", bndinfo.getProperty("b")); } public void testMultipleExport2() throws Exception { File cp[] = { new File("jar/asm.jar") }; Builder bmaker = new Builder(); Properties p = new Properties(); p.setProperty("Import-Package", "*"); p.setProperty("Export-Package", "org.objectweb.asm;version=1.1, org.objectweb.asm~;version=1.2, org.objectweb.asm~~;version=1.3"); bmaker.setProperties(p); bmaker.setClasspath(cp); Jar jar = bmaker.build(); System.out.println(jar.getResources()); // System.out.println(bmaker.getExports()); System.out.println("Warnings: " + bmaker.getWarnings()); System.out.println("Errors : " + bmaker.getErrors()); jar.getManifest().write(System.out); System.out.println("Warnings " + bmaker.getWarnings()); System.out.println("Errors " + bmaker.getErrors()); assertEquals(0, bmaker.getWarnings().size()); assertEquals(0, bmaker.getErrors().size()); Manifest m = jar.getManifest(); String ip = m.getMainAttributes().getValue("Export-Package"); assertTrue(ip.indexOf("org.objectweb.asm;version=\"1.1\"") >= 0); assertTrue(ip.indexOf("org.objectweb.asm;version=\"1.2\"") >= 0); assertTrue(ip.indexOf("org.objectweb.asm;version=\"1.3\"") >= 0); } public void testBsnAssignmentNoFile() throws Exception { Properties p = new Properties(); p.setProperty("Private-Package", "org.objectweb.asm"); Attributes m = setup(p, null).getMainAttributes(); // We use properties so the default BSN is then the project name // because that is the base directory assertEquals(m.getValue("Bundle-SymbolicName"), "biz.aQute.bndlib"); // The file name for the properties is not bnd.bnd, so the // name of the properties file is the default bsn m = setup(null, new File("src/test/com.acme/defaultbsn.bnd")).getMainAttributes(); assertEquals("com.acme.defaultbsn", m.getValue("Bundle-SymbolicName")); // If the file is called bnd.bnd, then we take the parent directory m = setup(null, new File("src/test/com.acme/bnd.bnd")).getMainAttributes(); assertEquals("com.acme", m.getValue("Bundle-SymbolicName")); // If the file is called bnd.bnd, then we take the parent directory m = setup(null, new File("src/test/com.acme/setsbsn.bnd")).getMainAttributes(); assertEquals("is.a.set.bsn", m.getValue("Bundle-SymbolicName")); // This sets the bsn, se we should see it back p.setProperty("Bundle-SymbolicName", "this.is.my.test"); m = setup(p, null).getMainAttributes(); assertEquals(m.getValue("Bundle-SymbolicName"), "this.is.my.test"); } public Manifest setup(Properties p, File f) throws Exception { File cp[] = { new File("jar/asm.jar") }; Builder bmaker = new Builder(); if (f != null) bmaker.setProperties(f); else bmaker.setProperties(p); bmaker.setClasspath(cp); Jar jar = bmaker.build(); System.out.println(jar.getResources()); // System.out.println(bmaker.getExports()); System.out.println("Warnings: " + bmaker.getWarnings()); System.out.println("Errors : " + bmaker.getErrors()); jar.getManifest().write(System.out); assertEquals(0, bmaker.getWarnings().size()); assertEquals(0, bmaker.getErrors().size()); Manifest m = jar.getManifest(); return m; } public void testDuplicateExport() throws Exception { File cp[] = { new File("jar/asm.jar") }; Builder bmaker = new Builder(); Properties p = new Properties(); p.setProperty("Import-Package", "*"); p.setProperty("Export-Package", "org.*;version=1.2,org.objectweb.asm~;version=1.3"); bmaker.setProperties(p); bmaker.setClasspath(cp); Jar jar = bmaker.build(); System.out.println(jar.getResources()); // System.out.println(bmaker.getExports()); System.out.println("Warnings: " + bmaker.getWarnings()); System.out.println("Errors : " + bmaker.getErrors()); jar.getManifest().write(System.out); assertEquals(0, bmaker.getWarnings().size()); assertEquals(0, bmaker.getErrors().size()); Manifest m = jar.getManifest(); String ip = m.getMainAttributes().getValue("Export-Package"); assertTrue(ip.indexOf("org.objectweb.asm;version=\"1.2\"") >= 0); } public void testNoExport() throws Exception { File cp[] = { new File("jar/asm.jar") }; Builder bmaker = new Builder(); Properties p = new Properties(); p.setProperty("Import-Package", "*"); p.setProperty("Export-Package", "org.*'"); bmaker.setProperties(p); bmaker.setClasspath(cp); Jar jar = bmaker.build(); System.out.println(jar.getResources()); // System.out.println(bmaker.getExports()); System.out.println("Warnings: " + bmaker.getWarnings()); System.out.println("Errors : " + bmaker.getErrors()); jar.getManifest().write(System.out); assertEquals(0, bmaker.getWarnings().size()); assertEquals(0, bmaker.getErrors().size()); Manifest m = jar.getManifest(); String ip = m.getMainAttributes().getValue("Export-Package"); assertTrue(ip.indexOf("org.objectweb.asm") >= 0); } public void testHardcodedImport() throws Exception { File cp[] = { new File("jar/asm.jar") }; Builder bmaker = new Builder(); Properties p = new Properties(); p.setProperty("Import-Package", "whatever,*"); p.setProperty("Export-Package", "org.*"); bmaker.setProperties(p); bmaker.setClasspath(cp); Jar jar = bmaker.build(); System.out.println(jar.getResources()); // System.out.println(bmaker.getExports()); System.out.println("Warnings: " + bmaker.getWarnings()); System.out.println("Errors : " + bmaker.getErrors()); jar.getManifest().write(System.out); assertEquals(0, bmaker.getWarnings().size()); assertEquals(0, bmaker.getErrors().size()); Manifest m = jar.getManifest(); String ip = m.getMainAttributes().getValue("Import-Package"); assertTrue(ip.indexOf("whatever") >= 0); } public void testCopyDirectory() throws Exception { Builder bmaker = new Builder(); Properties p = new Properties(); p.setProperty("-resourceonly", "true"); p.setProperty("Include-Resource", "bnd=bnd"); bmaker.setProperties(p); Jar jar = bmaker.build(); Map map = jar.getDirectories().get("bnd"); assertNotNull(map); assertEquals(2, map.size()); assertEquals(0, bmaker.getErrors().size()); assertEquals(0, bmaker.getWarnings().size()); } /** * There is an error that gives a split package when you export a package * that is also private I think. * * @throws Exception */ public void testSplitOnExportAndPrivate() throws Exception { File cp[] = { new File("jar/asm.jar") }; Builder bmaker = new Builder(); Properties p = new Properties(); p.setProperty("Export-Package", "org.objectweb.asm.signature"); p.setProperty("Private-Package", "org.objectweb.asm"); bmaker.setProperties(p); bmaker.setClasspath(cp); bmaker.build(); System.out.println("Warnings: " + bmaker.getWarnings()); System.out.println("Errors : " + bmaker.getErrors()); assertEquals(0, bmaker.getWarnings().size()); assertEquals(0, bmaker.getErrors().size()); } public void testConduit() throws Exception { Properties p = new Properties(); p.setProperty("-conduit", "jar/asm.jar"); Builder b = new Builder(); b.setProperties(p); Jar jars[] = b.builds(); assertNotNull(jars); assertEquals(1, jars.length); assertEquals("ASM", jars[0].getManifest().getMainAttributes().getValue("Implementation-Title")); } /** * Export a package that was loaded with resources * * @throws Exception */ public void testExportSyntheticPackage() throws Exception { Builder bmaker = new Builder(); Properties p = new Properties(); p.setProperty("-resourceonly", "true"); p.setProperty("Include-Resource", "resources=jar"); p.setProperty("-exportcontents", "resources"); bmaker.setProperties(p); Jar jar = bmaker.build(); System.out.println(jar.getResources()); // System.out.println(bmaker.getExports()); System.out.println("Errors : " + bmaker.getErrors()); System.out.println("Warnings : " + bmaker.getWarnings()); assertEquals("Warnings: ", 0, bmaker.getWarnings().size()); assertEquals("Errors : ", 0, bmaker.getErrors().size()); Manifest manifest = jar.getManifest(); String header = manifest.getMainAttributes().getValue("Export-Package"); System.out.println(header); assertTrue(header.indexOf("resources") >= 0); } /** * Exporting packages in META-INF * * @throws Exception */ public void testMETAINF() throws Exception { File cp[] = { new File("src"), new File("jar/asm.jar") }; Builder bmaker = new Builder(); Properties p = new Properties(); p.setProperty("Include-Resource", "META-INF/xyz/asm.jar=jar/asm.jar"); p.setProperty("Export-Package", "META-INF/xyz, org.*"); bmaker.setProperties(p); bmaker.setClasspath(cp); Jar jar = bmaker.build(); System.out.println(jar.getResources()); // System.out.println(bmaker.getExports()); System.out.println("Warnings: " + bmaker.getWarnings()); System.out.println("Errors : " + bmaker.getErrors()); jar.getManifest().write(System.out); Manifest manifest = jar.getManifest(); String header = manifest.getMainAttributes().getValue("Export-Package"); assertTrue(header.indexOf("META-INF") > 0); } /** * Bnd cleans up versions if they do not follow the OSGi rule. Check a * number of those versions. * * @throws Exception */ public void testVersionCleanup() throws Exception { assertVersion("000001.0003.00000-SNAPSHOT", "1.3.0.SNAPSHOT"); assertVersion("000000.0000.00000-SNAPSHOT", "0.0.0.SNAPSHOT"); assertVersion("0-SNAPSHOT", "0.0.0.SNAPSHOT"); assertVersion("1.3.0.0-0-01-0-SNAPSHOT", "1.3.0.0-0-01-0-SNAPSHOT"); assertVersion("1.3.0.0-0-01-0", "1.3.0.0-0-01-0"); assertVersion("0.9.0.1.2.3.4.5-incubator-SNAPSHOT", "0.9.0.incubator-SNAPSHOT"); assertVersion("0.4aug123", "0.0.0.4aug123"); assertVersion("0.9.4aug123", "0.9.0.4aug123"); assertVersion("0.9.0.4aug123", "0.9.0.4aug123"); assertVersion("1.2.3", "1.2.3"); assertVersion("1.2.3-123", "1.2.3.123"); assertVersion("1.2.3.123", "1.2.3.123"); assertVersion("1.2.3.123x", "1.2.3.123x"); assertVersion("1.123x", "1.0.0.123x"); assertVersion("0.9.0.4.3.2.1.0.4aug123", "0.9.0.4aug123"); assertVersion("0.9.0.4aug123", "0.9.0.4aug123"); assertVersion("0.9.0.4.3.4.5.6.6", "0.9.0.6"); assertVersion("0.9.0-incubator-SNAPSHOT", "0.9.0.incubator-SNAPSHOT"); assertVersion("1.2.3.x", "1.2.3.x"); assertVersion("1.2.3", "1.2.3"); assertVersion("1.2", "1.2"); assertVersion("1", "1"); assertVersion("1.2.x", "1.2.0.x"); assertVersion("1.x", "1.0.0.x"); assertVersion("1.2.3-x", "1.2.3.x"); assertVersion("1.2:x", "1.2.0.x"); assertVersion("1.2-snapshot", "1.2.0.snapshot"); assertVersion("1#x", "1.0.0.x"); assertVersion("1.&^%$#date2007/03/04", "1.0.0.date20070304"); } void assertVersion(String input, String expected) { assertEquals(expected, Builder.cleanupVersion(input)); } /** * -exportcontents provides a header that is only relevant in the analyze * phase, it augments the Export-Package header. */ public void testExportContents() throws Exception { Builder builder = new Builder(); builder.setProperty(Analyzer.INCLUDE_RESOURCE, "test/activator/inherits=src/test/activator/inherits"); builder.setProperty("-exportcontents", "*;x=true;version=1"); builder.build(); Manifest manifest = builder.calcManifest(); Attributes main = manifest.getMainAttributes(); Map> map = OSGiHeader.parseHeader(main .getValue("Export-Package")); Map export = map.get("test.activator.inherits"); assertNotNull(export); assertEquals("1", export.get("version")); assertEquals("true", export.get("x")); } /** * I am having some problems with split packages in 170. I get this output: * * [java] 1 : There are split packages, use directive split-package:=merge * on instruction to get rid of this warning: my.package * * First of all, this warning is falsely occurring. The classpath to the bnd * task contains something like: * * my/package/foo.class my/package/sub/bar.class * * and the export is: * * Export-Package: my.package*;version=${version} * * so my.package and my.package.sub are being incorrectly considered as the * same package by bnd. * */ public void testSplitOverlappingPackages() throws Exception { Builder b = new Builder(); b.setClasspath(new File[] { new File("bin") }); Properties p = new Properties(); p.put("build", "xyz"); p.put("Export-Package", "test*;version=3.1"); b.setProperties(p); b.setPedantic(true); b.build(); System.out.println("Errors :" + b.getErrors()); System.out.println("Warnings :" + b.getWarnings()); assertEquals(0, b.getErrors().size()); assertEquals(0, b.getWarnings().size()); } /** * Check Conditional package. First import a subpackage then let the * subpackage import a super package. This went wrong in the OSGi build. We * see such a pattern in the Spring jar. The package * org.springframework.beans.factory.access refers to * org.springframework.beans.factory and org.springframework.beans. The */ public void testConditionalBaseSuper() throws Exception { Builder b = new Builder(); b.setProperty(Constants.CONDITIONAL_PACKAGE, "test.top.*"); b.setProperty(Constants.PRIVATE_PACKAGE, "test.top.middle.bottom"); b.addClasspath(new File("bin")); Jar dot = b.build(); System.out.println("Errors: " + b.getErrors()); System.out.println("Warnings: " + b.getWarnings()); assertEquals(0, b.getErrors().size()); assertEquals(0, b.getWarnings().size()); assertNotNull(dot.getResource("test/top/middle/bottom/Bottom.class")); assertNotNull(dot.getResource("test/top/middle/Middle.class")); assertNotNull(dot.getResource("test/top/Top.class")); assertFalse(b.getImports().containsKey("test.top")); assertFalse(b.getImports().containsKey("test.top.middle")); assertFalse(b.getImports().containsKey("test.top.middle.bottom")); } /** * It looks like Conditional-Package can add the same package multiple * times. So lets test this. */ public void testConditional2() throws Exception { Properties base = new Properties(); base.put(Analyzer.EXPORT_PACKAGE, "org.osgi.service.log"); base.put(Analyzer.CONDITIONAL_PACKAGE, "org.osgi.*"); Builder analyzer = new Builder(); analyzer.setProperties(base); analyzer.setClasspath(new File[] { new File("jar/osgi.jar") }); analyzer.build(); Jar jar = analyzer.getJar(); assertNotNull(jar.getDirectories().get("org/osgi/framework")); System.out.println("Errors: " + analyzer.getErrors()); System.out.println("Warnings: " + analyzer.getWarnings()); assertEquals(0, analyzer.getErrors().size()); assertEquals(0, analyzer.getWarnings().size()); } /** * Test the strategy: error */ public void testStrategyError() throws Exception { Properties base = new Properties(); base.put(Analyzer.EXPORT_PACKAGE, "*;-split-package:=error"); Builder analyzer = new Builder(); analyzer.setClasspath(new File[] { new File("jar/asm.jar"), new File("jar/asm.jar") }); analyzer.setProperties(base); analyzer.build(); System.out.println("Errors: " + analyzer.getErrors()); assertEquals(3, analyzer.getErrors().size()); assertEquals(0, analyzer.getWarnings().size()); assertTrue(((String) analyzer.getErrors().get(0)).indexOf("Split package") >= 0); } /** * Test the strategy: default */ public void testStrategyDefault() throws Exception { Properties base = new Properties(); base.put(Analyzer.EXPORT_PACKAGE, "*"); Builder analyzer = new Builder(); analyzer.setClasspath(new File[] { new File("jar/asm.jar"), new File("jar/asm.jar") }); analyzer.setProperties(base); analyzer.build(); System.out.println("Warnings: " + analyzer.getWarnings()); assertEquals(0, analyzer.getErrors().size()); assertEquals(3, analyzer.getWarnings().size()); assertTrue(((String) analyzer.getWarnings().get(0)).indexOf("split-package") >= 0); } /** * Test the strategy: merge-first */ public void testStrategyMergeFirst() throws Exception { Properties base = new Properties(); base.put(Analyzer.EXPORT_PACKAGE, "*;-split-package:=merge-first"); Builder analyzer = new Builder(); analyzer.setClasspath(new File[] { new File("jar/asm.jar"), new File("jar/asm.jar") }); analyzer.setProperties(base); analyzer.build(); System.out.println("Errors: " + analyzer.getErrors()); assertEquals(0, analyzer.getErrors().size()); assertEquals(0, analyzer.getWarnings().size()); // assertTrue( ((String)analyzer.getErrors().get(0)).contains("file does // not exist")); } /** * Test the strategy: merge-last */ public void testStrategyMergeLast() throws Exception { Properties base = new Properties(); base.put(Analyzer.EXPORT_PACKAGE, "*;-split-package:=merge-last"); Builder analyzer = new Builder(); analyzer.setClasspath(new File[] { new File("jar/asm.jar"), new File("jar/asm.jar") }); analyzer.setProperties(base); analyzer.build(); System.out.println("Errors: " + analyzer.getErrors()); assertEquals(0, analyzer.getErrors().size()); assertEquals(0, analyzer.getWarnings().size()); // assertTrue( ((String)analyzer.getErrors().get(0)).contains("file does // not exist")); } /** * Test Resource inclusion that do not exist * * @throws Exception */ public void testResourceNotFound() throws Exception { Properties base = new Properties(); base.put(Analyzer.EXPORT_PACKAGE, "*;test:=true"); base.put(Analyzer.INCLUDE_RESOURCE, "does_not_exist"); Builder analyzer = new Builder(); analyzer.setClasspath(new File[] { new File("jar/asm.jar") }); analyzer.setProperties(base); analyzer.build(); System.out.println("Errors: " + analyzer.getErrors()); assertEquals(1, analyzer.getErrors().size()); assertTrue(((String) analyzer.getErrors().get(0)).indexOf("file does not exist") >= 0); } /** * Spaces at the end of a clause cause the preprocess to fail. * * @throws Exception */ public void testPreProcess() throws Exception { Properties base = new Properties(); base.put(Analyzer.INCLUDE_RESOURCE, "{src/test/top.mf} "); Builder analyzer = new Builder(); analyzer.setProperties(base); analyzer.build(); Jar jar = analyzer.getJar(); assertTrue(jar.getResource("top.mf") != null); } /** * Check if we can use findpath to build the Bundle-Classpath. */ public void testFindPathInBundleClasspath() throws Exception { Properties base = new Properties(); base.put(Analyzer.INCLUDE_RESOURCE, "jar=jar"); base.put(Analyzer.BUNDLE_CLASSPATH, "${findpath;jar/.{1,4}\\.jar}"); Builder analyzer = new Builder(); analyzer.setProperties(base); analyzer.build(); Manifest manifest = analyzer.getJar().getManifest(); String bcp = manifest.getMainAttributes().getValue("Bundle-Classpath"); assertTrue(bcp.indexOf("ds.jar") >= 0); assertTrue(bcp.indexOf("asm.jar") >= 0); assertTrue(bcp.indexOf("bcel.jar") >= 0); assertTrue(bcp.indexOf("mina.jar") >= 0); assertTrue(bcp.indexOf("rox.jar") >= 0); assertTrue(bcp.indexOf("osgi.jar") >= 0); } /** * Check if we export META-INF when we export the complete classpath. */ public void testVersionCleanupAll() throws Exception { Properties base = new Properties(); base.put(Analyzer.EXPORT_PACKAGE, "*"); base.put(Analyzer.BUNDLE_VERSION, "0.9.0-incubator-SNAPSHOT"); Builder analyzer = new Builder(); analyzer.setClasspath(new File[] { new File("jar/asm.jar") }); analyzer.setProperties(base); analyzer.build(); Manifest manifest = analyzer.getJar().getManifest(); String version = manifest.getMainAttributes().getValue(Analyzer.BUNDLE_VERSION); assertEquals("0.9.0.incubator-SNAPSHOT", version); } /** * We are only adding privately the core equinox ds package. We then add * conditionally all packages that should belong to this as well as any OSGi * interfaces. * * @throws Exception */ public void testConditional() throws Exception { File cp[] = { new File("jar/osgi.jar"), new File("jar/ds.jar") }; Builder bmaker = new Builder(); Properties p = new Properties(); p.put("Import-Package", "*"); p.put("Private-Package", "org.eclipse.equinox.ds"); p.put("Conditional-Package", "org.eclipse.equinox.ds.*, org.osgi.service.*"); bmaker.setProperties(p); bmaker.setClasspath(cp); bmaker.build(); assertTrue(bmaker.getContained().containsKey("org.eclipse.equinox.ds.instance")); assertTrue(bmaker.getContained().containsKey("org.eclipse.equinox.ds.model")); assertTrue(bmaker.getContained().containsKey("org.eclipse.equinox.ds.parser")); assertTrue(bmaker.getContained().containsKey("org.osgi.service.cm")); assertTrue(bmaker.getContained().containsKey("org.osgi.service.component")); assertFalse(bmaker.getContained().containsKey("org.osgi.service.wireadmin")); } /** * Check if we export META-INF when we export the complete classpath. */ public void testMetaInfExport() throws Exception { Properties base = new Properties(); base.put(Analyzer.EXPORT_PACKAGE, "*"); Builder analyzer = new Builder(); analyzer.setClasspath(new File[] { new File("jar/asm.jar") }); analyzer.setProperties(base); analyzer.build(); assertFalse(analyzer.getExports().containsKey("META-INF")); assertTrue(analyzer.getExports().containsKey("org.objectweb.asm")); } /** * Check that the activator is found. * * @throws Exception */ public void testFindActivator() throws Exception { Builder bmaker = new Builder(); Properties p = new Properties(); p.put("Bundle-Activator", "test.activator.Activator"); p.put("build", "xyz"); // for @Version annotation p.put("Private-Package", "test.*"); bmaker.setProperties(p); bmaker.setClasspath(new File[] { new File("bin") }); Jar jar = bmaker.build(); report("testFindActivator", bmaker, jar); assertEquals(0, bmaker.getErrors().size()); assertEquals(0, bmaker.getWarnings().size()); } public void testImportVersionRange() throws Exception { assertVersionEquals("[1.1,2.0)", "[1.1,2.0)"); assertVersionEquals("[${@},2.0)", "[1.3,2.0)"); assertVersionEquals("[${@},${@}]", "[1.3,1.3]"); } void assertVersionEquals(String input, String output) throws Exception { File cp[] = { new File("jar/osgi.jar") }; Builder bmaker = new Builder(); bmaker.setClasspath(cp); Properties p = new Properties(); p.put(Analyzer.EXPORT_PACKAGE, "test.activator"); p.put(Analyzer.IMPORT_PACKAGE, "org.osgi.framework;version=\"" + input + "\""); bmaker.setProperties(p); bmaker.build(); Map> imports = bmaker.getImports(); Map framework = imports.get("org.osgi.framework"); assertEquals(output, framework.get("version")); } public void testImportExportBadVersion() throws Exception { File cp[] = { new File("jar/asm.jar") }; Builder bmaker = new Builder(); bmaker.setClasspath(cp); Properties p = new Properties(); p.put(Analyzer.BUNDLE_VERSION, "0.9.5-@#SNAPSHOT"); p.put(Analyzer.EXPORT_PACKAGE, "*;version=0.9.5-@#SNAPSHOT"); p.put(Analyzer.IMPORT_PACKAGE, "*;version=0.9.5-@#SNAPSHOT"); bmaker.setProperties(p); Jar jar = bmaker.build(); assertEquals(jar.getManifest().getMainAttributes().getValue("Bundle-Version"), "0.9.5.SNAPSHOT"); Map map = bmaker.getExports().get("org.objectweb.asm"); assertEquals(map.get("version"), "0.9.5.SNAPSHOT"); map = bmaker.getImports().get("java.lang.reflect"); assertEquals(map.get("version"), "0.9.5.SNAPSHOT"); } /** * Check if can find an activator in the bundle while using a complex bundle * classpath. * * @throws Exception */ public void testBundleClasspath3() throws Exception { Builder bmaker = new Builder(); Properties p = new Properties(); p.put("Export-Package", "test.activator;-split-package:=merge-first"); p.put("Bundle-Activator", "test.activator.Activator"); p.put("Import-Package", "*"); p.put("Include-Resource", "ds.jar=jar/ds.jar"); p.put("Bundle-ClassPath", ".,ds.jar"); bmaker.setProperties(p); bmaker.setClasspath(new File[] { new File("bin"), new File("src") }); Jar jar = bmaker.build(); report("testBundleClasspath3", bmaker, jar); assertEquals(0, bmaker.getErrors().size()); assertEquals(0, bmaker.getWarnings().size()); } /** * Check if can find an activator in a embedded jar while using a complex * bundle classpath. * * @throws Exception */ public void testBundleClasspath2() throws Exception { Builder bmaker = new Builder(); Properties p = new Properties(); p.put("Bundle-Activator", "org.eclipse.equinox.ds.Activator"); p.put("Private-Package", "test.activator;-split-package:=merge-first"); p.put("Import-Package", "*"); p.put("Include-Resource", "ds.jar=jar/ds.jar"); p.put("Bundle-ClassPath", ".,ds.jar"); bmaker.setProperties(p); bmaker.setClasspath(new File[] { new File("bin"), new File("src") }); Jar jar = bmaker.build(); report("testBundleClasspath2", bmaker, jar); assertEquals(bmaker.getErrors().size(), 0); assertEquals(bmaker.getWarnings().size(), 0); } public void testBundleClasspath() throws Exception { Builder bmaker = new Builder(); Properties p = new Properties(); p.put("Export-Package", "test.activator;-split-package:=merge-first"); p.put("Bundle-Activator", "test.activator.Activator"); p.put("Import-Package", "*"); p.put("Bundle-ClassPath", "."); bmaker.setProperties(p); bmaker.setClasspath(new File[] { new File("bin"), new File("src") }); Jar jar = bmaker.build(); report("testBundleClasspath", bmaker, jar); jar.exists("test/activator/Activator.class"); assertEquals(bmaker.getErrors().size(), 0); assertEquals(bmaker.getWarnings().size(), 0); } public void testUnreferredImport() throws Exception { Builder bmaker = new Builder(); Properties p = new Properties(); p.put("-classpath", "jar/mina.jar"); p.put("Export-Package", "!META-INF.*,*"); p.put("Import-Package", "org.apache.commons.collections.map,*"); bmaker.setProperties(p); Jar jar = bmaker.build(); report("testUnreferredImport", bmaker, jar); } public void testIncludeResourceResourcesOnlyJar2() throws Exception { Builder bmaker = new Builder(); Properties p = new Properties(); p.put("-classpath", "jar/ro.jar"); p.put("Export-Package", "*"); p.put("Import-Package", ""); bmaker.setProperties(p); Jar jar = bmaker.build(); report("testIncludeResourceResourcesOnlyJar2", bmaker, jar); assertTrue(bmaker.getExports().containsKey("ro")); assertFalse(bmaker.getExports().containsKey("META-INF")); assertEquals(0, bmaker.getWarnings().size()); assertEquals(0, bmaker.getErrors().size()); assertEquals(3, jar.getResources().size()); } public void testClasspathFileNotExist() throws Exception { Builder bmaker = new Builder(); Properties p = new Properties(); File cp[] = new File[] { new File("jar/idonotexist.jar") }; bmaker.setProperties(p); bmaker.setClasspath(cp); bmaker.build(); assertEquals(2, bmaker.getErrors().size()); } public void testExpandWithNegate() throws Exception { Builder bmaker = new Builder(); Properties p = new Properties(); File cp[] = new File[] { new File("jar/asm.jar") }; p.put("Export-Package", "!org.objectweb.asm,*"); bmaker.setProperties(p); bmaker.setClasspath(cp); Jar jar = bmaker.build(); assertNull(jar.getDirectories().get("org/objectweb/asm")); assertNotNull(jar.getDirectories().get("org/objectweb/asm/signature")); assertEquals(0, bmaker.getWarnings().size()); assertEquals(0, bmaker.getErrors().size()); assertEquals(3, jar.getResources().size()); } public void testIncludeResourceResourcesOnlyJar() throws Exception { Builder bmaker = new Builder(); Properties p = new Properties(); File cp[] = new File[] { new File("jar/ro.jar") }; p.put("Export-Package", "*"); p.put("Import-Package", ""); bmaker.setProperties(p); bmaker.setClasspath(cp); Jar jar = bmaker.build(); assertEquals(0, bmaker.getWarnings().size()); assertEquals(0, bmaker.getErrors().size()); assertEquals(3, jar.getResources().size()); } public void testIncludeResourceResourcesOnly() throws Exception { Builder bmaker = new Builder(); Properties p = new Properties(); File cp[] = new File[] { new File("src") }; p.put("Import-Package", ""); p.put("Private-Package", "test.resourcesonly"); bmaker.setProperties(p); bmaker.setClasspath(cp); Jar jar = bmaker.build(); assertEquals(0, bmaker.getWarnings().size()); assertEquals(0, bmaker.getErrors().size()); assertEquals(4, jar.getResources().size()); } public void testIncludeResourceFromZipDefault() throws Exception { Builder bmaker = new Builder(); Properties p = new Properties(); p.put("Include-Resource", "@jar/easymock.jar"); bmaker.setProperties(p); Jar jar = bmaker.build(); assertEquals(1, bmaker.getWarnings().size()); assertEquals(0, bmaker.getErrors().size()); assertEquals(59, jar.getResources().size()); } public void testIncludeResourceFromZipDeep() throws Exception { Builder bmaker = new Builder(); Properties p = new Properties(); p.put("Include-Resource", "@jar/easymock.jar!/**"); bmaker.setProperties(p); Jar jar = bmaker.build(); assertEquals(1, bmaker.getWarnings().size()); assertEquals(0, bmaker.getErrors().size()); assertEquals(59, jar.getResources().size()); } public void testIncludeResourceFromZipOneDirectory() throws Exception { Builder bmaker = new Builder(); Properties p = new Properties(); p.put("Import-Package", "!*"); p.put("Include-Resource", "@jar/easymock.jar!/org/easymock/**"); bmaker.setProperties(p); Jar jar = bmaker.build(); assertEquals(1, bmaker.getWarnings().size()); assertEquals(0, bmaker.getErrors().size()); assertEquals(59, jar.getResources().size()); assertNotNull(jar.getResource("org/easymock/AbstractMatcher.class")); } public void testIncludeResourceFromZipOneDirectoryOther() throws Exception { Builder bmaker = new Builder(); Properties p = new Properties(); p.put("Import-Package", "!*"); p.put("-resourceonly", "true"); p.put("Include-Resource", "OPT-INF/test=@jar/osgi.jar!/org/osgi/service/event/**"); bmaker.setProperties(p); Jar jar = bmaker.build(); System.out.println("warnings: " + Processor.join(bmaker.getWarnings(), "\n")); System.out.println("errors: " + Processor.join(bmaker.getErrors(), "\n")); assertEquals(0, bmaker.getWarnings().size()); assertEquals(0, bmaker.getErrors().size()); assertEquals(7, jar.getResources().size()); System.out.println(jar.getResources().keySet()); assertNotNull(jar.getResource("OPT-INF/test/org/osgi/service/event/EventAdmin.class")); } public void testIncludeResourceFromZipRecurseDirectory() throws Exception { Builder bmaker = new Builder(); Properties p = new Properties(); p.put("Import-Package", "!*"); p.put("Include-Resource", "@jar/easymock.jar!/org/easymock/**"); bmaker.setProperties(p); Jar jar = bmaker.build(); assertEquals(1, bmaker.getWarnings().size()); assertEquals(0, bmaker.getErrors().size()); assertEquals(59, jar.getResources().size()); } public void testIncludeLicenseFromZip() throws Exception { Builder bmaker = new Builder(); Properties p = new Properties(); p.put("Import-Package", ""); p.put("Include-Resource", "@jar/osgi.jar!/LICENSE"); bmaker.setProperties(p); Jar jar = bmaker.build(); assertEquals(1, jar.getResources().size()); assertNotNull(jar.getResource("LICENSE")); assertEquals(1, bmaker.getWarnings().size()); assertEquals(0, bmaker.getErrors().size()); } public void testEasymock() throws Exception { File cp[] = { new File("jar/easymock.jar") }; Builder bmaker = new Builder(); Properties p = new Properties(); p.put("Import-Package", "*"); p.put("Export-Package", "*"); p.put("Bundle-SymbolicName", "easymock"); p.put("Bundle-Version", "2.2"); bmaker.setProperties(p); bmaker.setClasspath(cp); Jar jar = bmaker.build(); jar.getManifest().write(System.out); } public void testSources() throws Exception { File cp[] = { new File("src"), new File("jar/asm.jar") }; Builder bmaker = new Builder(); bmaker.setClasspath(cp); bmaker.setSourcepath(new File[] { new File("src") }); Properties properties = new Properties(); properties.put("-sources", "true"); properties.put("Export-Package", "*"); bmaker.setProperties(properties); Jar jar = bmaker.build(); System.out.println(jar.getResources()); // System.out.println(bmaker.getExports()); System.out.println("Warnings: " + bmaker.getWarnings()); System.out.println("Errors : " + bmaker.getErrors()); jar.getManifest().write(System.out); } public void testSimple() throws Exception { File cp[] = { new File("src"), new File("jar/asm.jar") }; Builder bmaker = new Builder(); bmaker.setProperties(new File("src/test/simple.mf")); bmaker.setClasspath(cp); Jar jar = bmaker.build(); System.out.println(jar.getResources()); // System.out.println(bmaker.getExports()); System.out.println("Warnings: " + bmaker.getWarnings()); System.out.println("Errors : " + bmaker.getErrors()); jar.getManifest().write(System.out); } public void testVerifyResult() throws Exception { System.out.println("Verify what we just built: test.jar"); Jar jar = new Jar("test", getClass().getResourceAsStream("test.jar")); Verifier verifier = new Verifier(jar); verifier.verify(); System.out.println("Warnings: " + verifier.getWarnings()); System.out.println("Errors : " + verifier.getErrors()); } public void testVerify() throws Exception { System.out.println("Erroneous bundle: tb1.jar"); Jar jar = new Jar("test", getClass().getResourceAsStream("tb1.jar")); Verifier verifier = new Verifier(jar); verifier.verify(); System.out.println("Warnings: " + verifier.getWarnings()); System.out.println("Errors : " + verifier.getErrors()); verifier.info(); } public void report(String title, Analyzer builder, Jar jar) { System.out.println("Directories " + jar.getDirectories().keySet()); System.out.println("Warnings " + builder.getWarnings()); System.out.println("Errors " + builder.getErrors()); System.out.println("Exports " + builder.getExports()); System.out.println("Imports " + builder.getImports()); } } bnd-1.50.0/biz.aQute.bndlib/src/test/make/0000755000175000017500000000000011656076535020030 5ustar drazzibdrazzibbnd-1.50.0/biz.aQute.bndlib/src/test/make/MD5.java0000644000175000017500000000231011656076535021254 0ustar drazzibdrazzibpackage test.make; import java.io.*; import java.security.*; import java.util.*; import aQute.bnd.service.*; import aQute.lib.osgi.*; public class MD5 implements MakePlugin { public Resource make(Builder builder, String source, Map arguments) throws Exception { if (!arguments.get("type").equals("md5")) return null; source = source.substring(0,source.length()-4); final File f = builder.getFile(source); if (f.isFile()) { return new AbstractResource(f.lastModified()) { public byte[] getBytes() throws Exception { return md5(f); } }; } else throw new FileNotFoundException("No such file: " + source); } private byte [] md5(File f) throws Exception { MessageDigest md5 = MessageDigest.getInstance("MD5"); InputStream in = new FileInputStream(f); try { byte[] b = new byte[1000]; int size; while ((size = in.read()) > 0) { md5.update(b, 0, size); } return md5.digest(); } finally { in.close(); } } } bnd-1.50.0/biz.aQute.bndlib/src/test/CalltreeTest.java0000644000175000017500000001214011656076535022347 0ustar drazzibdrazzibpackage test; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.io.StringWriter; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Map; import junit.framework.TestCase; import aQute.bnd.make.calltree.CalltreeResource; import aQute.bnd.make.coverage.Coverage; import aQute.bnd.make.coverage.CoverageResource; import aQute.lib.osgi.Analyzer; import aQute.lib.osgi.Builder; import aQute.lib.osgi.Clazz; import aQute.lib.osgi.Processor; import aQute.lib.osgi.Resource; import aQute.lib.osgi.Clazz.MethodDef; import aQute.lib.tag.Tag; public class CalltreeTest extends TestCase { public void testCalltree() throws Exception { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); Builder b = new Builder(); b.addClasspath(new File("bin")); b.setProperty("Private-Package", "test"); b.build(); Collection clazzes = b.getClassspace().values(); assertTrue(clazzes.size() > 10); CalltreeResource.writeCalltree(pw, clazzes); pw.close(); System.out.println(sw.toString()); } static class Implements implements Resource { public String getExtra() { // TODO Auto-generated method stub return null; } public long lastModified() { // TODO Auto-generated method stub return 0; } public InputStream openInputStream() throws IOException { // TODO Auto-generated method stub return null; } public void setExtra(String extra) { // TODO Auto-generated method stub } public void write(OutputStream out) throws IOException { // TODO Auto-generated method stub } } public void testCoverage() throws Exception { Builder b = new Builder(); b.addClasspath(new File("bin")); b.setProperty("Private-Package", "test"); b.build(); Collection testsuite = b.getClassspace().values(); Builder c = new Builder(); c.addClasspath(new File("bin")); c.setProperty("Private-Package", "aQute.lib.osgi"); c.build(); Collection target = c.getClassspace().values(); Map> xref = Coverage.getCrossRef(testsuite, target); System.out.println(xref); List refs = xref.get(new Clazz.MethodDef(0, Resource.class.getName(), "write", "(Ljava/io/OutputStream;)V")); assertNotNull("The write(OutputStream) method is implemented by Resource", xref); assertTrue("We must have at least one reference", refs.size() > 0); // MethodDef md = refs.get(0); boolean found = false; for (MethodDef md : refs) { if (md.clazz.equals("test.CalltreeTest$Implements")) { found = true; assertEquals(md.name, ""); assertEquals(md.descriptor, "()V"); } } assertTrue( found); assertTrue(xref.containsKey(new Clazz.MethodDef(0, Analyzer.class.getName(), "analyze", "()V"))); assertTrue(xref.containsKey(new Clazz.MethodDef(0, Builder.class.getName(), "build", "()LaQute/lib/osgi/Jar;"))); assertTrue(xref .get( new Clazz.MethodDef(0, "aQute.lib.osgi.Builder", "build", "()LaQute/lib/osgi/Jar;")).contains( new Clazz.MethodDef(0, "test.CalltreeTest", "testCoverage", "()V"))); Tag tag = CoverageResource.toTag(xref); PrintWriter pw = new PrintWriter(new OutputStreamWriter(System.out)); tag.print(0, pw); pw.close(); } public void testCatalog() throws Exception { Builder b = new Builder(); b.addClasspath(new File("jar/osgi.jar")); b.setProperty("Private-Package", "org.osgi.framework"); b.build(); Collection target = b.getClassspace().values(); Map> xref = Coverage.getCrossRef(new ArrayList(), target); System.out.println(Processor.join(xref.keySet(), "\n")); assertTrue(xref.containsKey(new Clazz.MethodDef(0, "org.osgi.framework.AdminPermission", "", "()V"))); assertTrue(xref.containsKey(new Clazz.MethodDef(0, "org.osgi.framework.AdminPermission", "", "(Lorg/osgi/framework/Bundle;Ljava/lang/String;)V"))); assertTrue(xref.containsKey(new Clazz.MethodDef(0, "org.osgi.framework.AdminPermission", "", "(Ljava/lang/String;Ljava/lang/String;)V"))); assertFalse(xref.containsKey(new Clazz.MethodDef(0, "org.osgi.framework.AdminPermission$1", "run", "()Ljava/lang/Object;"))); assertFalse(xref.containsKey(new Clazz.MethodDef(0, "org.osgi.framework.AdminPermission", "createName", "(Lorg/osgi/framework/Bundle;)Ljava/lang/String;"))); } public void testResource() throws Exception { Builder b = new Builder(); b.addClasspath(new File("jar/osgi.jar")); b.setProperty("Private-Package", "org.osgi.framework"); b.build(); Collection target = b.getClassspace().values(); Resource r = new CoverageResource(target, target); InputStream in = r.openInputStream(); ByteArrayOutputStream out = new ByteArrayOutputStream(); byte[] buffer = new byte[1000]; int size = in.read(buffer); while (size > 0) { out.write(buffer, 0, size); size = in.read(buffer); } out.close(); assertTrue(out.toByteArray().length > 1000); } } bnd-1.50.0/biz.aQute.bndlib/src/test/ExportHeaderTest.java0000644000175000017500000000434511656076535023216 0ustar drazzibdrazzibpackage test; import java.io.*; import java.util.*; import java.util.jar.*; import junit.framework.*; import aQute.lib.osgi.*; public class ExportHeaderTest extends TestCase { /** * If you import a range then the maven guys can have the silly -SNAPSHOT in the * version. This tests if ranges are correcly cleaned up. * @throws Exception */ public void testImportHeaderWithMessedUpRange() throws Exception { Builder builder = new Builder(); Jar bin = new Jar( new File("bin") ); builder.setClasspath( new Jar[]{bin}); Properties p = new Properties(); p.setProperty("Private-Package", "test.packageinfo.ref"); p.setProperty("Import-Package", "test.packageinfo;version=\"[1.1.1-SNAPSHOT,1.1.1-SNAPSHOT]"); builder.setProperties(p); Jar jar = builder.build(); Manifest manifest = jar.getManifest(); String imph = manifest.getMainAttributes().getValue("Import-Package"); assertEquals("test.packageinfo;version=\"[1.1.1.SNAPSHOT,1.1.1.SNAPSHOT]\"", imph); } public void testPickupExportVersion() throws Exception { Builder builder = new Builder(); Jar bin = new Jar( new File("bin") ); builder.setClasspath( new Jar[]{bin}); Properties p = new Properties(); p.setProperty("Private-Package", "test.packageinfo.ref"); builder.setProperties(p); Jar jar = builder.build(); Manifest manifest = jar.getManifest(); String imph = manifest.getMainAttributes().getValue("Import-Package"); assertEquals("test.packageinfo;version=\"[1.0,2)\"", imph); } public void testExportVersionWithPackageInfo() throws Exception { Builder builder = new Builder(); Jar bin = new Jar( new File("bin") ); builder.setClasspath( new Jar[]{bin}); Properties p = new Properties(); p.setProperty("Export-Package", "test.packageinfo"); builder.setProperties(p); Jar jar = builder.build(); Manifest manifest = jar.getManifest(); String exph = manifest.getMainAttributes().getValue("Export-Package"); assertEquals("test.packageinfo;version=\"1.0.0.SNAPSHOT\"", exph); } } bnd-1.50.0/biz.aQute.bndlib/src/test/TestSelfBuild.java0000644000175000017500000000137211656076535022472 0ustar drazzibdrazzibpackage test; import java.io.File; import junit.framework.TestCase; import aQute.bnd.build.Project; import aQute.bnd.build.Workspace; import aQute.lib.osgi.*; public class TestSelfBuild extends TestCase { public void testSelfBuild() throws Throwable { Project project = Workspace.getWorkspace( new File("").getAbsoluteFile().getParentFile() ).getProject("biz.aQute.bndlib"); project.setPedantic(true); project.action("build"); File files[] = project.build(); System.out.println(Processor.join(project.getErrors(),"\n")); System.out.println(Processor.join(project.getWarnings(),"\n")); assertEquals(0, project.getErrors().size()); assertEquals(0, project.getWarnings().size()); assertNotNull(files); assertEquals(1,files.length); } } bnd-1.50.0/biz.aQute.bndlib/src/test/refer/0000755000175000017500000000000011656076535020216 5ustar drazzibdrazzibbnd-1.50.0/biz.aQute.bndlib/src/test/refer/RefersToMeasurement.java0000644000175000017500000000016311656076535025020 0ustar drazzibdrazzibpackage test.refer; import org.osgi.util.measurement.*; public class RefersToMeasurement { Measurement acmin; } bnd-1.50.0/biz.aQute.bndlib/src/test/refer/RefersToEventAdmin.java0000644000175000017500000000015611656076535024567 0ustar drazzibdrazzibpackage test.refer; import org.osgi.service.event.*; public class RefersToEventAdmin { EventAdmin acmin; } bnd-1.50.0/biz.aQute.bndlib/src/test/refer/RefersToHttp.java0000644000175000017500000000015011656076535023446 0ustar drazzibdrazzibpackage test.refer; import org.osgi.service.http.*; public class RefersToHttp { HttpService acmin; } bnd-1.50.0/biz.aQute.bndlib/src/test/top/0000755000175000017500000000000011656076535017715 5ustar drazzibdrazzibbnd-1.50.0/biz.aQute.bndlib/src/test/top/middle/0000755000175000017500000000000011656076535021153 5ustar drazzibdrazzibbnd-1.50.0/biz.aQute.bndlib/src/test/top/middle/Middle.java0000644000175000017500000000013111656076535023207 0ustar drazzibdrazzibpackage test.top.middle; import test.top.*; public class Middle { { new Top(); } } bnd-1.50.0/biz.aQute.bndlib/src/test/top/middle/bottom/0000755000175000017500000000000011656076535022457 5ustar drazzibdrazzibbnd-1.50.0/biz.aQute.bndlib/src/test/top/middle/bottom/Bottom.java0000644000175000017500000000015211656076535024564 0ustar drazzibdrazzibpackage test.top.middle.bottom; import test.top.middle.*; public class Bottom { { new Middle(); } } bnd-1.50.0/biz.aQute.bndlib/src/test/top/Top.java0000644000175000017500000000005011656076535021315 0ustar drazzibdrazzibpackage test.top; public class Top { } bnd-1.50.0/biz.aQute.bndlib/src/test/FilterTest.java0000644000175000017500000000067011656076535022046 0ustar drazzibdrazzibpackage test; import junit.framework.*; import aQute.lib.osgi.*; public class FilterTest extends TestCase { public void testFilter() { Verifier v = new Verifier(); v.verifyFilter("(org.osgi.framework.windowing.system=xyz)"); System.out.println(v.getErrors()); System.out.println(v.getWarnings()); assertEquals(0, v.getErrors().size()); assertEquals(0, v.getWarnings().size()); } } bnd-1.50.0/biz.aQute.bndlib/src/test/CompareTest.java0000644000175000017500000000727711656076535022221 0ustar drazzibdrazzibpackage test; import java.io.*; import java.lang.reflect.*; import java.util.*; import junit.framework.*; public class CompareTest extends TestCase { interface I {} class B { class C {} } class A0 {} // Declarations class A1 { // } class A2 { // } class A3 { // } public String foo0() { return null; } public T foo1() { return null; } public T foo2() {return null; } public > T foo3() {return null;} public T foo4() { return null; } public void testGenericDeclaration() throws Exception { assertTrue( A0.class.getTypeParameters().length == 0 ); assertTrue( A1.class.getTypeParameters().length == 1 ); assertEquals( "T", A1.class.getTypeParameters()[0].getName() ); assertEquals( 1, A1.class.getTypeParameters()[0].getBounds().length); assertEquals( Object.class, A1.class.getTypeParameters()[0].getBounds()[0]); assertTrue( A2.class.getTypeParameters().length == 1 ); assertEquals( "T", A2.class.getTypeParameters()[0].getName() ); assertEquals( 1, A2.class.getTypeParameters()[0].getBounds().length); assertEquals( Serializable.class, A2.class.getTypeParameters()[0].getBounds()[0]); assertTrue( A3.class.getTypeParameters().length == 1 ); assertEquals( "T", A3.class.getTypeParameters()[0].getName() ); assertEquals( 2, A3.class.getTypeParameters()[0].getBounds().length); assertEquals( Exception.class, A3.class.getTypeParameters()[0].getBounds()[0]); assertEquals( Serializable.class, A3.class.getTypeParameters()[0].getBounds()[1]); Method m = getClass().getMethod("foo0"); assertEquals( 0, m.getTypeParameters().length); m = getClass().getMethod("foo1"); assertEquals( 1, m.getTypeParameters().length); assertEquals( "T", m.getTypeParameters()[0].getName() ); assertEquals( 1, m.getTypeParameters()[0].getBounds().length); assertEquals( Object.class, m.getTypeParameters()[0].getBounds()[0]); m = getClass().getMethod("foo3"); assertEquals( 1, m.getTypeParameters().length); assertEquals( "T", m.getTypeParameters()[0].getName() ); assertEquals( 2, m.getTypeParameters()[0].getBounds().length); assertEquals( Exception.class, m.getTypeParameters()[0].getBounds()[0]); m = getClass().getMethod("foo4"); assertEquals( 1, m.getTypeParameters().length); assertEquals( "T", m.getTypeParameters()[0].getName() ); assertEquals( 1, m.getTypeParameters()[0].getBounds().length); assertTrue( m.getTypeParameters()[0].getBounds()[0] instanceof TypeVariable ); assertEquals( getClass(), ((TypeVariable)m.getTypeParameters()[0].getBounds()[0]).getGenericDeclaration()); } public A1[]> a1; A1 bar() { return null; } public void testSimple() throws IOException { // Scope root = new Scope(Access.PUBLIC, Kind.ROOT, "."); // RuntimeSignatureBuilder pc = new RuntimeSignatureBuilder(root); // pc.add(CompareTest.class); // pc.add(A.class); // pc.add(A.B.class); // // A a = new A(); // // pc.add(a.bar().getClass()); // pc.add(a.bar().foo().getClass()); // // // ParseSignatureBuilder pb = new ParseSignatureBuilder(root); // // pb.parse(new FileInputStream("bin/test/CompareTest$A$B$1.class")); // // pb.parse(new FileInputStream("bin/test/CompareTest$A$1.class")); // // pb.parse(new FileInputStream("bin/test/CompareTest$Z.class")); // // root.cleanRoot(); // PrintWriter pw = new PrintWriter(System.out); // root.report(pw, 0); // pw.flush(); // // root.prune(EnumSet.of(Access.PUBLIC, Access.PROTECTED)); // root.report(pw, 0); // pw.flush(); } } bnd-1.50.0/biz.aQute.bndlib/src/test/IncludeHeaderTest.java0000755000175000017500000001105611656076535023320 0ustar drazzibdrazzibpackage test; import java.io.*; import java.util.*; import junit.framework.*; import aQute.lib.osgi.*; public class IncludeHeaderTest extends TestCase { // public void testMavenInclude() throws Exception { // String b = "pom.modelVersion=b\n"; // File bb = new File("b.props"); // write(bb, b ); // bb.deleteOnExit(); // // Analyzer analyzer = new Analyzer(); // Properties x = new Properties(); // x.put("pom.modelVersion", "set"); // x.put("pom.scope.test", "set"); // x.put("-include", "~maven/pom.xml,b.props"); // analyzer.setProperties(x); // System.out.println(analyzer.getErrors()); // System.out.println(analyzer.getWarnings()); // assertEquals("b", analyzer.getProperty("pom.modelVersion")); // from b // assertEquals("org.apache.felix.metatype", analyzer.getProperty("pom.artifactId")); // from pom // assertEquals("org.apache.felix", analyzer.getProperty("pom.groupId")); // from parent pom // assertEquals("set", analyzer.getProperty("pom.scope.test")); // Set // } public void testTopBottom() throws Exception { Analyzer analyzer = new Analyzer(); analyzer.setProperties(new File("src/test/include.bnd/top.bnd")); assertEquals("0.0.257", analyzer.getProperty("Bundle-Version")); } public void testPrecedence() throws Exception { File base = new File("src/test"); String a = "a=a.props\n"; String b = "a=b.props\n"; File aa = new File(base,"a.props"); File bb = new File(base,"b.props"); write(aa, a); write(bb, b ); Analyzer analyzer = new Analyzer(); analyzer.setBase(base); Properties x = new Properties(); x.put("a", "x"); x.put("-include", "a.props, b.props"); analyzer.setProperties(x); assertEquals("b.props", analyzer.getProperty("a")); // from org analyzer = new Analyzer(); analyzer.setBase(base); x = new Properties(); x.put("a", "x"); x.put("-include", "~a.props, b.props"); analyzer.setProperties(x); assertEquals("b.props", analyzer.getProperty("a")); // from org analyzer = new Analyzer(); analyzer.setBase(base); x = new Properties(); x.put("a", "x"); x.put("-include", "a.props, ~b.props"); analyzer.setProperties(x); assertEquals("a.props", analyzer.getProperty("a")); // from org analyzer = new Analyzer(); analyzer.setBase(base); x = new Properties(); x.put("a", "x"); x.put("-include", "~a.props, ~b.props"); analyzer.setProperties(x); assertEquals("x", analyzer.getProperty("a")); // from org aa.delete(); bb.delete(); } private void write(File file, String b) throws Exception { FileOutputStream out = new FileOutputStream( file); out.write( b.getBytes()); out.close(); } public void testAbsentIncludes() throws IOException { Analyzer analyzer = new Analyzer(); analyzer.setBase(new File("src/test")); Properties p = new Properties(); p.put("-include", "-iamnotthere.txt"); analyzer.setProperties(p); System.out.println(analyzer.getErrors()); assertEquals(0, analyzer.getErrors().size()); } public void testIncludeWithProperty() throws IOException { File home = new File(System.getProperty("user.home")); File include = new File(home, "includeheadertest.txt"); try { FileOutputStream fw = new FileOutputStream(include); fw.write("IncludeHeaderTest: yes\n\r".getBytes()); fw.write("a: 2\n\r".getBytes()); fw.write("b: ${a}\n\r".getBytes()); fw.close(); Analyzer analyzer = new Analyzer(); analyzer.setBase(new File("src/test")); Properties p = new Properties(); p.put("a", "1"); p .put("-include", "-iamnotthere.txt, ${user.home}/includeheadertest.txt"); analyzer.setProperties(p); String value = analyzer.getProperty("IncludeHeaderTest"); assertEquals("yes", value); assertEquals("2", analyzer.getProperty("a")); assertEquals("2", analyzer.getProperty("b")); assertEquals(0, analyzer.getErrors().size()); } finally { include.delete(); } } public void testIncludeHeader() throws IOException { Analyzer analyzer = new Analyzer(); analyzer.setBase(new File("src/test")); Properties p = new Properties(); p.put("a", "1"); p.put("-include", "includeheadertest.mf, includeheadertest.prop"); analyzer.setProperties(p); System.out.println(analyzer.getProperties()); assertEquals("1", analyzer.getProperty("a")); assertEquals("end", analyzer.getProperty("last-props")); assertEquals("end", analyzer.getProperty("last-manifest")); assertEquals("abcd", analyzer.getProperty("manifest")); assertEquals("abcd", analyzer.getProperty("props")); assertEquals("1", analyzer.getProperty("test")); } } bnd-1.50.0/biz.aQute.bndlib/src/test/ProjectTest.java0000755000175000017500000001566211656076535022241 0ustar drazzibdrazzibpackage test; import java.io.File; import java.util.Collection; import java.util.HashSet; import java.util.Set; import java.util.jar.Manifest; import junit.framework.TestCase; import aQute.bnd.build.Project; import aQute.bnd.build.Workspace; import aQute.bnd.service.RepositoryPlugin.*; import aQute.lib.deployer.FileRepo; import aQute.lib.io.*; import aQute.lib.osgi.Builder; import aQute.lib.osgi.Jar; import aQute.lib.osgi.Processor; import aQute.lib.osgi.eclipse.EclipseClasspath; import aQute.libg.version.Version; public class ProjectTest extends TestCase { /** * Check multiple repos * * @throws Exception */ public void testMultipleRepos() throws Exception { Workspace ws = Workspace.getWorkspace(new File("test/ws")); Project project = ws.getProject("p1"); System.out.println(project.getBundle("org.apache.felix.configadmin", "1.1.0", Strategy.EXACT, null)); System.out.println(project.getBundle("org.apache.felix.configadmin", "1.1.0", Strategy.HIGHEST, null)); System.out.println(project.getBundle("org.apache.felix.configadmin", "1.1.0", Strategy.LOWEST, null)); } /** * Check if the getSubBuilders properly predicts the output. */ public void testSubBuilders() throws Exception { Workspace ws = Workspace.getWorkspace(new File("test/ws")); Project project = ws.getProject("p4-sub"); Collection bs = project.getSubBuilders(); assertNotNull(bs); assertEquals(3, bs.size()); Set names = new HashSet(); for (Builder b : bs) { names.add(b.getBsn()); } assertTrue(names.contains("p4-sub.a")); assertTrue(names.contains("p4-sub.b")); assertTrue(names.contains("p4-sub.c")); File[] files = project.build(); System.out.println(Processor.join(project.getErrors(), "\n")); System.out.println(Processor.join(project.getWarnings(), "\n")); assertEquals(0, project.getErrors().size()); assertEquals(0, project.getWarnings().size()); assertNotNull(files); assertEquals(3, files.length); for (File file : files) { Jar jar = new Jar(file); Manifest m = jar.getManifest(); assertTrue(names.contains(m.getMainAttributes().getValue("Bundle-SymbolicName"))); } } /** * Tests the handling of the -sub facility * * @throws Exception */ public void testSub() throws Exception { Workspace ws = Workspace.getWorkspace(new File("test/ws")); Project project = ws.getProject("p4-sub"); File[] files = project.build(); System.out.println(Processor.join(project.getErrors(), "\n")); System.out.println(Processor.join(project.getWarnings(), "\n")); assertEquals(0, project.getErrors().size()); assertEquals(0, project.getWarnings().size()); assertNotNull(files); assertEquals(3, files.length); Jar a = new Jar(files[0]); Jar b = new Jar(files[1]); Manifest ma = a.getManifest(); Manifest mb = b.getManifest(); assertEquals("base", ma.getMainAttributes().getValue("Base-Header")); assertEquals("base", mb.getMainAttributes().getValue("Base-Header")); assertEquals("a", ma.getMainAttributes().getValue("Sub-Header")); assertEquals("b", mb.getMainAttributes().getValue("Sub-Header")); } public void testOutofDate() throws Exception { Workspace ws = Workspace.getWorkspace(new File("test/ws")); Project project = ws.getProject("p3"); File bnd = new File("test/ws/p3/bnd.bnd"); assertTrue(bnd.exists()); project.clean(); project.getTarget().mkdirs(); try { // Now we build it. File[] files = project.build(); System.out.println(project.getErrors()); System.out.println(project.getWarnings()); assertTrue(project.isOk()); assertNotNull(files); assertEquals(1, files.length); // Now we should not rebuild it long lastTime = files[0].lastModified(); files = project.build(); assertEquals(1, files.length); assertTrue(files[0].lastModified() == lastTime); Thread.sleep(2000); project.updateModified(System.currentTimeMillis(), "Testing"); files = project.build(); assertEquals(1, files.length); assertTrue("Must have newer files now", files[0].lastModified() > lastTime); } finally { project.clean(); } } public void testRepoMacro() throws Exception { Workspace ws = Workspace.getWorkspace(new File("test/ws")); Project project = ws.getProject("p2"); System.out.println(project.getPlugins(FileRepo.class)); String s = project.getReplacer().process(("${repo;libtest}")); System.out.println(s); assertTrue(s.contains("org.apache.felix.configadmin/org.apache.felix.configadmin-1.2.0")); assertTrue(s.contains("org.apache.felix.ipojo/org.apache.felix.ipojo-1.0.0.jar")); s = project.getReplacer().process(("${repo;libtestxyz}")); assertTrue(s.matches("<<[^>]+>>")); s = project.getReplacer().process("${repo;org.apache.felix.configadmin;1.0.0;highest}"); s.endsWith("org.apache.felix.configadmin-1.1.0.jar"); s = project.getReplacer().process("${repo;org.apache.felix.configadmin;1.0.0;lowest}"); s.endsWith("org.apache.felix.configadmin-1.0.1.jar"); } public void testClasspath() throws Exception { File project = new File("").getAbsoluteFile(); File workspace = project.getParentFile(); Processor processor = new Processor(); EclipseClasspath p = new EclipseClasspath(processor, workspace, project); System.out.println(p.getDependents()); System.out.println(p.getClasspath()); System.out.println(p.getSourcepath()); System.out.println(p.getOutput()); } public void testBump() throws Exception { File tmp = new File("tmp-ws"); if (tmp.exists()) IO.delete(tmp); tmp.mkdir(); assertTrue(tmp.isDirectory()); try { IO.copy(new File("test/ws"), tmp); Workspace ws = Workspace.getWorkspace(tmp); Project project = ws.getProject("p1"); int size = project.getProperties().size(); Version old = new Version(project.getProperty("Bundle-Version")); System.out.println("Old version " + old); project.bump("=+0"); Version newv = new Version(project.getProperty("Bundle-Version")); System.out.println("New version " + newv); assertEquals(old.getMajor(), newv.getMajor()); assertEquals(old.getMinor() + 1, newv.getMinor()); assertEquals(0, newv.getMicro()); assertEquals(size, project.getProperties().size()); assertEquals("sometime", newv.getQualifier()); } finally { IO.delete(tmp); } } public void testRunBuilds() throws Exception { Workspace ws = Workspace.getWorkspace(new File("test/ws")); // Running a .bnd includes built bundles by default Project p1 = ws.getProject("p1"); assertTrue(p1.getRunBuilds()); // Can override the default by specifying -runbuilds: false Project p2 = ws.getProject("p2"); assertFalse(p2.getRunBuilds()); // Running a .bndrun DOES NOT include built bundles by default Project p1a = new Project(ws, new File("test/ws/p1"), new File("test/ws/p1/p1a.bndrun")); assertFalse(p1a.getRunBuilds()); // ... unless we override the default by specifying -runbuilds: true Project p1b = new Project(ws, new File("test/ws/p1"), new File("test/ws/p1/p1b.bndrun")); assertTrue(p1b.getRunBuilds()); } } bnd-1.50.0/biz.aQute.bndlib/src/test/privateimport/0000755000175000017500000000000011656076535022020 5ustar drazzibdrazzibbnd-1.50.0/biz.aQute.bndlib/src/test/privateimport/PrivateImport.java0000644000175000017500000000202711656076535025471 0ustar drazzibdrazzibpackage test.privateimport; import java.io.*; import org.osgi.framework.*; import org.osgi.service.cm.*; public class PrivateImport implements ConfigurationAdmin { public Configuration createFactoryConfiguration(String factoryPid) throws IOException { // TODO Auto-generated method stub return null; } public Configuration createFactoryConfiguration(String factoryPid, String location) throws IOException { // TODO Auto-generated method stub return null; } public Configuration getConfiguration(String pid) throws IOException { // TODO Auto-generated method stub return null; } public Configuration getConfiguration(String pid, String location) throws IOException { // TODO Auto-generated method stub return null; } public Configuration[] listConfigurations(String filter) throws IOException, InvalidSyntaxException { // TODO Auto-generated method stub return null; } } bnd-1.50.0/biz.aQute.bndlib/src/test/AttributesTest.java0000644000175000017500000001163511656076535022752 0ustar drazzibdrazzibpackage test; import java.io.*; import java.util.*; import java.util.jar.*; import junit.framework.*; import aQute.lib.osgi.*; public class AttributesTest extends TestCase { /** * Remove a version attribute * * A mandatory attribute adds the common and tst properties to the * import. We remove them using remove:=* * @throws Exception */ public void testRemoveDirective() throws Exception { Jar javax = new Jar("test"); Manifest m = new Manifest(); m.getMainAttributes().putValue("Export-Package", "javax.microedition.io;a1=exp-1;a2=exp-2;a3=exp-3;x1=x1;x2=x2;x3=x3;mandatory:=\"a1,a2,a3,x1,x2,x3\""); javax.setManifest(m); Jar cp[] = { javax, new Jar(new File("jar/osgi.jar")) }; Builder bmaker = new Builder(); Properties p = new Properties(); p.put("Import-Package", "javax.microedition.io;-remove-attribute:=a1|x?;a2=imp-2,*"); p.put("Export-Package", "org.osgi.service.io"); bmaker.setClasspath(cp); bmaker.setProperties(p); Jar jar = bmaker.build(); // System.out.println(bmaker.getExports()); System.out.println("Warnings: " + bmaker.getWarnings()); System.out.println("Errors : " + bmaker.getErrors()); jar.getManifest().write(System.out); Manifest manifest = jar.getManifest(); Attributes main = manifest.getMainAttributes(); String imprt = main.getValue("Import-Package"); assertNotNull("Import package header", imprt ); Map> map = Processor.parseHeader(imprt, null); Map attrs = map.get("javax.microedition.io"); assertNotNull(attrs); assertNull(attrs.get("a1")); assertNull(attrs.get("x1")); assertNull(attrs.get("x2")); assertNull(attrs.get("x3")); assertEquals("imp-2", attrs.get("a2")); assertEquals("exp-3", attrs.get("a3")); } /** * Remove a version attribute * * @throws Exception */ public void testRemoveAttribute() throws Exception { Jar javax = new Jar("test"); Manifest m = new Manifest(); m.getMainAttributes().putValue("Export-Package", "javax.microedition.io;common=split;test=abc;mandatory:=\"common,test\""); javax.setManifest(m); Jar cp[] = { javax, new Jar(new File("jar/osgi.jar")) }; Builder bmaker = new Builder(); Properties p = new Properties(); p.put("Import-Package", "javax.microedition.io;common=!;test=abc,*"); p.put("Export-Package", "org.osgi.service.io"); bmaker.setClasspath(cp); bmaker.setProperties(p); Jar jar = bmaker.build(); System.out.println(jar.getResources()); // System.out.println(bmaker.getExports()); System.out.println("Warnings: " + bmaker.getWarnings()); System.out.println("Errors : " + bmaker.getErrors()); jar.getManifest().write(System.out); Manifest manifest = jar.getManifest(); Attributes main = manifest.getMainAttributes(); String imprt = main.getValue("Import-Package"); assertNotNull("Import package header", imprt ); Map> map = Processor.parseHeader(imprt, null); Map attrs = map.get("javax.microedition.io"); assertNotNull(attrs); assertNull(attrs.get("common")); } /** * Override a version attribute * * @throws Exception */ public void testOverrideAttribute() throws Exception { File cp[] = { new File("jar/osgi.jar") }; Builder bmaker = new Builder(); Properties p = new Properties(); p.put("Export-Package", "org.osgi.framework;version=1.1"); bmaker.setClasspath(cp); bmaker.setProperties(p); Jar jar = bmaker.build(); System.out.println(jar.getResources()); // System.out.println(bmaker.getExports()); System.out.println("Warnings: " + bmaker.getWarnings()); System.out.println("Errors : " + bmaker.getErrors()); jar.getManifest().write(System.out); Manifest manifest = jar.getManifest(); Attributes main = manifest.getMainAttributes(); String export = main.getValue("Export-Package"); assertNotNull("Export package header", export ); Map> map = Processor.parseHeader(export, null); assertEquals( "1.1", map.get("org.osgi.framework").get("version")); } /** * See if we inherit the version from the osgi.jar file. * * @throws Exception */ public void testSimple() throws Exception { File cp[] = { new File("jar/osgi.jar") }; Builder bmaker = new Builder(); Properties p = new Properties(); p.put("Export-Package", "org.osgi.framework"); bmaker.setClasspath(cp); bmaker.setProperties(p); Jar jar = bmaker.build(); System.out.println(jar.getResources()); // System.out.println(bmaker.getExports()); System.out.println("Warnings: " + bmaker.getWarnings()); System.out.println("Errors : " + bmaker.getErrors()); jar.getManifest().write(System.out); Manifest manifest = jar.getManifest(); Attributes main = manifest.getMainAttributes(); String export = main.getValue("Export-Package"); assertNotNull("Export package header", export ); Map> map = Processor.parseHeader(export, null); assertEquals( "1.3", map.get("org.osgi.framework").get("version")); } } bnd-1.50.0/biz.aQute.bndlib/src/test/simple.mf0000755000175000017500000000026511656076535020736 0ustar drazzibdrazzibExport-Package=aQute.bean;special=true, org.objectweb.asm.util, *xml2mif Import-Package=* Bundle-Includes=../../jar, simple.mf, @../../jar/thinlet.jar Private-Package=aQute.lib.aim bnd-1.50.0/biz.aQute.bndlib/src/test/ManifestTest.java0000755000175000017500000002022011656076535022363 0ustar drazzibdrazzibpackage test; import java.io.*; import java.util.*; import java.util.jar.*; import java.util.regex.*; import java.util.zip.*; import junit.framework.*; import aQute.lib.io.*; import aQute.lib.osgi.*; public class ManifestTest extends TestCase { public void testNameSection() throws Exception { Builder b = new Builder(); b.setProperty("Export-Package", "org.osgi.framework"); b.addClasspath( new File("jar/osgi.jar")); Jar jar = b.build(); jar.calcChecksums(null); File f = File.createTempFile("abc", ".jar"); f.deleteOnExit(); jar.write(f); jar = new Jar(f); f.delete(); assertEquals(0, b.getErrors().size()); assertEquals(0, b.getWarnings().size()); Resource r = jar.getResource("META-INF/MANIFEST.MF"); assertNotNull( r ); // String ms = IO.collect( r.openInputStream()); Manifest m = new Manifest( r.openInputStream()); assertEquals( 31, m.getEntries().size()); Attributes ba = m.getAttributes("org/osgi/framework/BundleActivator.class"); assertNotNull(ba); assertEquals( "RTRhr3kadnulINegRhpmog==", ba.getValue("MD5-Digest")); Attributes bundle = m.getAttributes("org/osgi/framework/Bundle.class"); assertNotNull(bundle); assertEquals( "fpQdL60w3CQK+7xlXtM6oA==", bundle.getValue("MD5-Digest")); Attributes sl = m.getAttributes("org/osgi/framework/ServiceListener.class"); assertNotNull(sl); assertEquals( "nzDRN19MrTJG+LP8ayKZITZ653g=", sl.getValue("SHA-Digest")); } public void testUnicode() throws Exception { Builder b = new Builder(); String longSentence = "\u1401\u1402\u1403\u1404\u1405\u1406\u1407\u1408\u1409\u140A\u140B\u140C\u140D\u140E\u140F\u1410\u1411\u1412\u1413\u1414\u1415\u1416\u1417\u1418\u1419\u141A\u141B\u141C\u141D\u141E\u141F\u1420\u1421\u1422\u1422\u1423\u1424\u1425\u1426\u1427\u1428\u1429\u1429\u142A\u142B\u142C\u142D\u142E\u142F\u1430\u1431\u1432\u1433\u1434\u1435\u1436\u1437\u1438\u1439\u143A\u143B\u143C\u143D\u143E\u143F\u1440\u1441\u1442\u1443\u1444\u1444\u1445\u1446\u1447\u1448\u1449\u144A\u144B\u144C\u144D"; String shortSentence = "\u1401\u1402\u1403\u1404\u1405\u1406\u1407\u1408\u1409\u140A\u140B\u140C\u140D\u140E\u140F\u1410\u1411\u1412\u1413\u1414\u1415\u1416"; assertEquals( 66, shortSentence.getBytes("UTF8").length); assertEquals( 22, shortSentence.length()); b.setProperty("A1", shortSentence); b.setProperty("A11", shortSentence); b.setProperty("A111", shortSentence); b.setProperty("A1111", shortSentence); b.setProperty("Long", longSentence); b.setProperty( "-resourceonly", "true"); b.setProperty( "Include-Resource", "jar/osgi.jar"); Jar jar = b.build(); File f = File.createTempFile("abc", ".jar"); f.deleteOnExit(); jar.write(f); jar = new Jar(f); f.delete(); assertEquals(0, b.getErrors().size()); assertEquals(0, b.getWarnings().size()); Resource r = jar.getResource("META-INF/MANIFEST.MF"); assertNotNull( r ); Manifest m = new Manifest( r.openInputStream()); // String ms = IO.collect(r.openInputStream()); assertEquals( shortSentence, m.getMainAttributes().getValue("A1")); assertEquals( shortSentence, m.getMainAttributes().getValue("A11")); assertEquals( shortSentence, m.getMainAttributes().getValue("A111")); assertEquals( shortSentence, m.getMainAttributes().getValue("A1111")); assertEquals( longSentence, m.getMainAttributes().getValue("Long")); } public void test72() throws Exception { Builder b = new Builder(); b.setProperty("H65","01234567890123456789012345678901234567890123456789012345678901234"); b.setProperty("H66","012345678901234567890123456789012345678901234567890123456789012345"); b.setProperty("H67","0123456789012345678901234567890123456789012345678901234567890123456"); b.setProperty("H68","01234567890123456789012345678901234567890123456789012345678901234567"); b.setProperty("H69","012345678901234567890123456789012345678901234567890123456789012345678"); b.setProperty( "-resourceonly", "true"); b.setProperty( "Include-Resource", "jar/osgi.jar"); Jar jar = b.build(); File f = File.createTempFile("abc", ".jar"); f.deleteOnExit(); jar.write(f); jar = new Jar(f); f.delete(); assertEquals(0, b.getErrors().size()); assertEquals(0, b.getWarnings().size()); Resource r = jar.getResource("META-INF/MANIFEST.MF"); assertNotNull( r ); Manifest m = new Manifest( r.openInputStream()); String ms = IO.collect( r.openInputStream()); assertEquals( 65, m.getMainAttributes().getValue("H65").length()); assertEquals( 66, m.getMainAttributes().getValue("H66").length()); assertEquals( 67, m.getMainAttributes().getValue("H67").length()); assertEquals( 68, m.getMainAttributes().getValue("H68").length()); assertEquals( 69, m.getMainAttributes().getValue("H69").length()); assertTrue( Pattern.compile("H65: \\d{65}\r\n").matcher(ms).find()); assertTrue( Pattern.compile("H66: \\d{66}\r\n").matcher(ms).find()); assertTrue( Pattern.compile("H67: \\d{67}\r\n").matcher(ms).find()); assertTrue( Pattern.compile("H68: \\d{67}\r\n 7\r\n").matcher(ms).find()); assertTrue( Pattern.compile("H69: \\d{67}\r\n 78\r\n").matcher(ms).find()); } public void testNoManifest() throws Exception { Builder b = new Builder(); b.setProperty("-nomanifest","true"); b.setProperty("Export-Package","org.osgi.service.event.*"); b.addClasspath(new File("jar/osgi.jar")); Jar jar = b.build(); assertNull( jar.getResource("META-INF/MANIFEST.MF")); ByteArrayOutputStream bout = new ByteArrayOutputStream(); jar.write(bout); ByteArrayInputStream bin = new ByteArrayInputStream(bout.toByteArray()); JarInputStream in = new JarInputStream(bin); ZipEntry entry = in.getNextEntry(); assertNotNull(entry); assertNull( entry.getExtra()); } public void testNames() throws Exception { Manifest m = new Manifest(); m.getMainAttributes().putValue("Manifest-Version", "1.0"); m.getMainAttributes().putValue("x", "Loïc Cotonéa"); m.getMainAttributes().putValue("y", "Loïc Cotonéa"); m.getMainAttributes().putValue("z", "Loïc Cotonéa"); ByteArrayOutputStream bout = new ByteArrayOutputStream(); Jar.writeManifest(m,bout); byte [] result = bout.toByteArray(); System.out.println( new String(result)); } public void testUTF8() throws Exception { Manifest m = new Manifest(); m.getMainAttributes().putValue("Manifest-Version", "1.0"); m.getMainAttributes().putValue("x", "Loïc Cotonéa"); m.getMainAttributes().putValue("y", "Loïc Cotonéa"); m.getMainAttributes().putValue("z", "Loïc Cotonéa"); ByteArrayOutputStream bout = new ByteArrayOutputStream(); Jar.writeManifest(m,bout); byte [] result = bout.toByteArray(); System.out.println( new String(result)); } public void testQuotes() { Map> map = new HashMap>(); Map clause = new HashMap(); clause.put("version1", "0"); clause.put("version2", "0.0"); clause.put("version3", "\"0.0\""); clause.put("version4", " \"0.0\" "); clause.put("version5", " 0.0 "); map.put("alpha", clause); String s = Processor.printClauses(map); assertTrue( s.indexOf("version1=0")>=0); assertTrue( s.indexOf("version2=\"0.0\"")>=0); assertTrue( s.indexOf("version3=\"0.0\"")>=0); assertTrue( s.indexOf("version4=\"0.0\"")>=0); assertTrue( s.indexOf("version5=\"0.0\"")>=0); } } bnd-1.50.0/biz.aQute.bndlib/src/test/signatures/0000755000175000017500000000000011656076535021277 5ustar drazzibdrazzibbnd-1.50.0/biz.aQute.bndlib/src/test/signatures/Z.java0000644000175000017500000000336211656076535022357 0ustar drazzibdrazzibpackage test.signatures; import java.io.*; import java.util.*; class X { } interface Y { } public class Z extends X implements Y { public class V { public void fooLCO(E e, C c, D d) { } } public abstract class U extends Z implements Cloneable, Serializable {} // Constructors public Z() { } public Z(C c) { } // Fields public X> field; public Z.V referenceToNestedClass; public V vc = new V(); // Methods public void method() { } // Test all possible declarations public void foo(E e) { } public void fooCI(E e) { } public void fooCII(E e) { } public void fooII(E e) { } public void fooI(E e) { } public void fooC(E e) { } public void fooP(E e) { } public void foo(E e, F f) { } // test with variable in signature public void fooLC(E e, C f) { } // test wildcards public Collection< ? > wildcard_001; public Collection< ? extends Cloneable> wildcard_002; public Collection< ? super Cloneable> wildcard_003; public Collection< ? extends C> wildcard_004; public Collection< ? super C> wildcard_005; public Collection< ? extends Z.V> wildcard_006; public Collection< ? super Z.V> wildcard_007; // test compatibility public Collection compatibility_001() {return null; } public Collection compatibility_002() {return null; } public Collection compatibility_003() {return null; } public C[] typevarArray; } bnd-1.50.0/biz.aQute.bndlib/src/test/SpringTest.java0000644000175000017500000000606411656076535022066 0ustar drazzibdrazzibpackage test; import junit.framework.*; import aQute.lib.osgi.*; public class SpringTest extends TestCase { /** * Basic test to see if the analzyer works. We read the sprint-test1.xml and * see if we can detect all the different packages. * * @throws Exception */ public void testSimple() throws Exception { // InputStream in = getClass().getResourceAsStream("spring-test1.xml"); // Set set = SpringComponent.analyze(in); // System.out.println(set); // assertTrue(set.contains("com.foo.one")); // assertTrue(set.contains("com.foo.one.one")); // assertTrue(set.contains("com.foo.one.two")); // assertTrue(set.contains("value_type")); // assertTrue(set.contains("a.b")); // assertTrue(set.contains("c.d")); // assertTrue(set.contains("e.f")); // assertTrue(set.contains("interfaces_1")); // assertTrue(set.contains("interfaces_2")); // assertFalse(set.contains("interfaces_3")); // assertFalse(set.contains("I-am-not-here")); } /** * Now check if the plugin works, we create a dummy bundle and put the * spring-test1.xml in the appropriate place. This means that the * import-header contains all the the packages. * * @throws Exception public void testPlugin() throws Exception { Builder b = new Builder(); b.setProperty(Analyzer.INCLUDE_RESOURCE, "META-INF/spring/one.xml=src/test/spring-test1.xml"); b.setProperty(Analyzer.IMPORT_PACKAGE, "*"); b.setProperty(Analyzer.EXPORT_PACKAGE, "*"); b.setClasspath(new File[] { new File("jar/asm.jar") }); Jar jar = b.build(); checkMessages(b,0,0); test(jar); } */ /** * See what happens if we put the spring file in the wrong place. * We should have no import packages. * * @throws Exception */ // public void testPluginWrongPlace() throws Exception { // Builder b = new Builder(); // b.setProperty(Analyzer.INCLUDE_RESOURCE, // "META-INF/not-spring/one.xml=src/test/spring-test1.xml"); // Jar jar = b.build(); // checkMessages(b,0,2); // Manifest m = jar.getManifest(); // assertNull(m.getMainAttributes().getValue(Analyzer.IMPORT_PACKAGE)); // } // // void test(Jar jar) throws Exception { // Manifest m = jar.getManifest(); // String header = m.getMainAttributes().getValue("Import-Package"); // assertTrue(header.indexOf("com.foo.one") >= 0); // assertTrue(header.indexOf("com.foo.one.one") >= 0); // assertTrue(header.indexOf("com.foo.one.two") >= 0); // assertTrue(header.indexOf("value_type") >= 0); // assertTrue(header.indexOf("a.b") >= 0); // assertTrue(header.indexOf("c.d") >= 0); // assertTrue(header.indexOf("e.f") >= 0); // assertTrue(header.indexOf("interfaces_1") >= 0); // assertTrue(header.indexOf("interfaces_2") >= 0); // assertFalse(header.indexOf("interfaces_3") >= 0); // assertFalse(header.indexOf("I-am-not-here") >= 0); // // } public void checkMessages(Processor processor, int errors, int warnings) { System.out.println("Errors: " + processor.getErrors()); System.out.println("Warnings: " + processor.getWarnings()); assertEquals(errors, processor.getErrors().size()); assertEquals(warnings, processor.getWarnings().size()); } } bnd-1.50.0/biz.aQute.bndlib/src/test/include.bnd/0000755000175000017500000000000011656076535021300 5ustar drazzibdrazzibbnd-1.50.0/biz.aQute.bndlib/src/test/include.bnd/bottom.bnd0000644000175000017500000000003011656076535023262 0ustar drazzibdrazzibBundle-Version: 0.0.257 bnd-1.50.0/biz.aQute.bndlib/src/test/include.bnd/top.bnd0000644000175000017500000000002511656076535022564 0ustar drazzibdrazzib-include: bottom.bnd bnd-1.50.0/biz.aQute.bndlib/src/test/PropertiesTest.java0000755000175000017500000001064711656076535022765 0ustar drazzibdrazzibpackage test; import java.io.*; import java.util.*; import java.util.jar.*; import junit.framework.*; import aQute.lib.osgi.*; public class PropertiesTest extends TestCase { static T notNull(T t) { assertNotNull(t); return t; } public void testFlattening() throws Exception { Processor p = new Processor(); p.setProperty("-versionpolicy", "${version;===;${@}}"); p.setProperty("x", "x"); p.setProperty("_x", "_x"); Properties flattened = notNull(p.getFlattenedProperties()); String x = notNull(flattened.getProperty("-versionpolicy")); assertTrue( x.contains("@")); notNull( flattened.getProperty("x")); assertNull( flattened.getProperty("_x")); assertEquals( 2,flattened.size()); } public void testFilter() { Processor p1 = new Processor(); p1.setProperty("dan", "bandera"); p1.setProperty("susan", "sarandon"); p1.setProperty("jon", "bostrom"); Processor p2 = new Processor(p1); p2.setForceLocal( Arrays.asList("dan")); p2.setProperty("susan", "schwarze"); assertNull( p2.getProperty("dan")); assertEquals("schwarze", p2.getProperty("susan")); assertEquals("bostrom", p2.getProperty("jon")); } public void testUnicode() { StringBuffer sb = new StringBuffer(); String s = "Loïc Cotonéa"; for ( int i=0; i 0x7F ) { sb.append("\\u"); sb.append(String.format("%04x",(int)c)); } else { sb.append(c); } } System.out.println(sb); } public void testSpacesAround() throws Exception { String test="#comment\n" + " abc = abc\r\n" + "def = def\n\r" + " ghi = ghi\r" + " jkl = jkl" ; byte [] bytes = test.getBytes("ISO8859-1"); ByteArrayInputStream bin = new ByteArrayInputStream(bytes); Properties p = new Properties(); p.load(bin); assertEquals("abc", p.get("abc")); assertEquals("def", p.get("def")); assertEquals("ghi", p.get("ghi")); assertEquals("jkl", p.get("jkl")); } public void testInternationalCharacters() throws Exception { String test="#comment\n" + "Namex=Lo\u00EFc Coton\u00E9a\n" + "Export-Package: *\n" + "Unicode=\\u0040\n" + "NameAgain=Loïc Cotonéa"; byte [] bytes = test.getBytes("ISO8859-1"); ByteArrayInputStream bin = new ByteArrayInputStream(bytes); Properties p = new Properties(); p.load(bin); assertEquals("@", p.get("Unicode")); assertEquals("Lo\u00EFc Coton\u00E9a", p.get("Namex")); // Now test if we can make the round trip Builder b = new Builder(); b.setProperties(p); b.addClasspath( new File("jar/asm.jar")); Jar jar = b.build(); ByteArrayOutputStream bout = new ByteArrayOutputStream(); jar.getManifest().write(bout); bin = new ByteArrayInputStream(bout.toByteArray()); Manifest m = new Manifest( bin ); assertEquals("Lo\u00EFc Coton\u00E9a", m.getMainAttributes().getValue("Namex")); } public void testBadProperties() throws Exception { Analyzer analyzer = new Analyzer(); analyzer.setPedantic(true); analyzer.setProperties(new File("src/test/badproperties.prop")); String s = analyzer.getProperty(Analyzer.IMPORT_PACKAGE); Map> map = analyzer.parseHeader(s); assertEquals(2,map.size()); assertTrue(map.containsKey("org.osgi.service.cm")); assertTrue(map.containsKey("org.osgi.util.tracker")); assertEquals(1,analyzer.getWarnings().size()); System.out.println(analyzer.getWarnings()); assertTrue(analyzer.getWarnings().get(0).indexOf("Empty clause, usually caused by repeating a comma without")>=0); System.out.println(analyzer.getWarnings()); } public void testProperties() throws Exception { Analyzer analyzer = new Analyzer(); analyzer.setProperties(new File("src/test/variables.mf")); assertEquals("aQute.test", analyzer.getProperty("Header")); System.out.println("property " + analyzer.getProperty("Header")); } } bnd-1.50.0/biz.aQute.bndlib/src/test/LauncherTest.java0000644000175000017500000000401011656076535022352 0ustar drazzibdrazzibpackage test; import java.io.*; import java.util.concurrent.*; import junit.framework.*; import aQute.bnd.build.*; import aQute.lib.osgi.*; public class LauncherTest extends TestCase { public void testSimple() throws Exception{ Project project = Workspace.getProject(Processor.getFile(new File("").getAbsoluteFile().getParentFile(), "demo")); project.clear(); ProjectLauncher l = project.getProjectLauncher(); l.setTrace(true); l.getRunProperties().put("test.cmd", "exit"); assertEquals(42,l.launch()); } public void testTester() throws Exception { Project project = Workspace.getProject(Processor.getFile(new File("").getAbsoluteFile().getParentFile(), "demo")); project.clear(); project.build(); ProjectTester pt = project.getProjectTester(); pt.addTest("test.TestCase1"); assertEquals(2,pt.test()); } public void testTimeoutActivator() throws Exception { Project project = Workspace.getProject(Processor.getFile(new File("").getAbsoluteFile().getParentFile(), "demo")); project.clear(); ProjectLauncher l = project.getProjectLauncher(); l.setTimeout(100, TimeUnit.MILLISECONDS); l.setTrace(false); assertEquals(ProjectLauncher.TIMEDOUT,l.launch()); } public void testTimeout() throws Exception { Project project = Workspace.getProject(Processor.getFile(new File("").getAbsoluteFile().getParentFile(), "demo")); project.clear(); ProjectLauncher l = project.getProjectLauncher(); l.setTimeout(100, TimeUnit.MILLISECONDS); l.setTrace(false); l.getRunProperties().put("test.cmd", "timeout"); assertEquals(ProjectLauncher.TIMEDOUT,l.launch()); } public void testMainThread() throws Exception { Project project = Workspace.getProject(Processor.getFile(new File("").getAbsoluteFile().getParentFile(), "demo")); project.clear(); ProjectLauncher l = project.getProjectLauncher(); l.setTimeout(10000, TimeUnit.MILLISECONDS); l.setTrace(false); l.getRunProperties().put("test.cmd", "main.thread"); assertEquals(ProjectLauncher.OK,l.launch()); } } bnd-1.50.0/biz.aQute.bndlib/src/test/MavenTest.java0000644000175000017500000003054611656076535021674 0ustar drazzibdrazzibpackage test; import java.io.*; import java.net.*; import java.util.*; import java.util.concurrent.*; import java.util.regex.*; import junit.framework.*; import aQute.bnd.build.*; import aQute.bnd.maven.*; import aQute.bnd.maven.support.*; import aQute.bnd.maven.support.Pom.*; import aQute.bnd.service.RepositoryPlugin.Strategy; import aQute.lib.io.*; import aQute.lib.osgi.*; import aQute.libg.map.*; import aQute.libg.version.*; public class MavenTest extends TestCase { Processor processor = new Processor(); final static File cwd = new File("").getAbsoluteFile(); static ExecutorService executor = Executors.newCachedThreadPool(); Maven maven = new Maven(executor); /** * A test against maven 2 * @throws Exception * @throws URISyntaxException */ public void testRemote() throws URISyntaxException, Exception { URI repo = new URI("http://repo1.maven.org/maven2"); MavenEntry entry = maven.getEntry("org.springframework", "spring-aspects" , "3.0.5.RELEASE"); entry.remove(); CachedPom pom = maven.getPom("org.springframework", "spring-aspects" , "3.0.5.RELEASE", repo); Set dependencies = pom.getDependencies(Scope.compile, repo); for ( Pom dep : dependencies ) { System.out.printf( "%20s %-20s %10s\n", dep.getGroupId(), dep.getArtifactId(), dep.getVersion()); } } /** * Test reading a pom for the buildpath * @throws Exception */ public void testPom() throws Exception{ Project project = getProject("maven2"); Collection containers = project.getBuildpath(); List files = new ArrayList(); for ( Container c : containers ) { files.add( c.getFile().getName()); } assertTrue(files.remove("bin")); System.out.println(files); assertTrue( files.contains("com.springsource.org.apache.commons.beanutils-1.6.1.jar")); assertTrue( files.contains("com.springsource.org.apache.commons.collections-2.1.1.jar")); assertTrue( files.contains("com.springsource.org.apache.commons.logging-1.0.4.jar")); } /** * Check if we get the correct bundles for a project * * @throws Exception */ public void testProjectBundles() throws Exception { // Project project = getProject("maven1"); // // Collection containers = project.getBuildpath(); // List files = new ArrayList(); // for ( Container c : containers ) { // files.add( c.getFile().getName()); // } // assertTrue(files.remove("bin")); // System.out.println(files); // assertTrue( files.contains("com.springsource.org.apache.commons.beanutils-1.6.1.jar")); } /** * @return * @throws Exception */ protected Project getProject(String name) throws Exception { File wsf = IO.getFile(cwd, "test/ws"); Workspace ws = Workspace.getWorkspace( wsf ); assertNotNull(ws); Project project = ws.getProject(name); assertNotNull(project); return project; } /** * See if we can create a maven repostory as a plugin * * @throws Exception */ public void testMavenRepo() throws Exception { Workspace ws = Workspace.getWorkspace( cwd.getParentFile()); Maven maven = ws.getMaven(); Processor processor = new Processor(ws); processor.setProperty(Constants.PLUGIN, "aQute.bnd.maven.support.MavenRemoteRepository;repositories=test/ws/maven1/m2"); MavenRemoteRepository mr = processor.getPlugin(MavenRemoteRepository.class); assertNotNull(mr); assertEquals( maven, mr.getMaven()); // Cleanup the maven cache so we do not get random results MavenEntry me = maven.getEntry("org.apache.commons", "com.springsource.org.apache.commons.beanutils", "1.6.1"); assertNotNull(me); me.remove(); Map map = MAP.$("groupId","org.apache.commons"); File file = mr.get("com.springsource.org.apache.commons.beanutils", "1.6.1", Strategy.LOWEST, map); assertNotNull(file); assertEquals("com.springsource.org.apache.commons.beanutils-1.6.1.jar", file.getName()); assertTrue( file.isFile()); Map map2 = MAP.$("groupId","org.apache.commons").$("scope","compile"); file = mr.get("com.springsource.org.apache.commons.beanutils", "1.6.1", Strategy.LOWEST, map2); assertNotNull(file); assertTrue( file.isFile()); assertEquals("compile.lib", file.getName()); String lib = IO.collect(file); System.out.println(lib); lib = lib.replaceAll("org.apache.commons\\+com.springsource.org.apache.commons.beanutils;version=\"1.6.1\"","1"); lib = lib.replaceAll("org.apache.commons\\+com.springsource.org.apache.commons.collections;version=\"2.1.1\"", "2"); lib = lib.replaceAll("org.apache.commons\\+com.springsource.org.apache.commons.logging;version=\"1.0.4\"", "3"); assertEquals( "1\n2\n3\n", lib); } /** * Test parsing a project pom * @throws Exception */ public void testProjectPom() throws Exception { Maven maven = new Maven(null); ProjectPom pom = maven.createProjectModel( IO.getFile( cwd, "test/ws/maven1/testpom.xml")); assertEquals( "artifact", pom.getArtifactId()); assertEquals( "group-parent", pom.getGroupId()); assertEquals( "1.0.0", pom.getVersion()); assertEquals( "Artifact", pom.getName()); assertEquals( "Parent Description\n\nDescription artifact", pom.getDescription()); List dependencies = pom.getDependencies(); boolean dep1=false; // dep1 boolean dep2=false; // artifact (after macro) boolean dep3=false; // junit boolean dep4=false; // easymock for ( Dependency dep : dependencies ) { String artifactId = dep.getArtifactId(); if ( "dep1".equals(artifactId)) { assertFalse( dep1); dep1=true; assertEquals( "xyz", dep.getGroupId()); assertEquals( "1.0.1", dep.getVersion()); assertEquals( Pom.Scope.valueOf("compile"), dep.getScope()); } else if ( "artifact".equals(artifactId)) { assertFalse( dep2); dep2=true; assertEquals( "group-parent", dep.getGroupId()); assertEquals( "1.0.2", dep.getVersion()); assertEquals( Pom.Scope.valueOf("compile"), dep.getScope()); } else if ( "junit".equals(artifactId)) { assertFalse( dep3); dep3=true; assertEquals( "junit", dep.getGroupId()); assertEquals( "4.0", dep.getVersion()); assertEquals( Pom.Scope.valueOf("test"), dep.getScope()); } else if ( "easymock".equals(artifactId)) { assertFalse( dep4); dep4=true; assertEquals( "org.easymock", dep.getGroupId()); assertEquals( "2.4", dep.getVersion()); assertEquals( Pom.Scope.valueOf("compile"), dep.getScope()); } else fail("'"+artifactId+"'"); } assertTrue(dep1 && dep2 && dep3 && dep4); assertEquals( "aa", pom.getProperty("a")); assertEquals( "b from parent", pom.getProperty("b")); assertEquals( "aab from parentartifact", pom.getProperty("c")); } /** * Test the maven remote repository */ public void testMavenRepo1() throws Exception { Maven maven = new Maven(null); MavenRemoteRepository mr = new MavenRemoteRepository(); mr.setMaven(maven); MavenEntry me = maven.getEntry("org.apache.commons", "com.springsource.org.apache.commons.beanutils", "1.6.1"); me.remove(); me = maven.getEntry("org.apache.commons", "com.springsource.org.apache.commons.collections", "2.1.1"); me.remove(); me = maven.getEntry("org.apache.commons", "com.springsource.org.apache.commons.logging", "1.0.4"); me.remove(); mr.setRepositories(new URI[] { IO.getFile(new File("").getAbsoluteFile(), "test/ws/maven1/m2").toURI() }); Map map = new HashMap(); map.put("scope", "compile"); File file = mr.get("org.apache.commons+com.springsource.org.apache.commons.beanutils", "1.6.1", Strategy.LOWEST, map); assertNotNull(file); assertTrue( file.isFile()); assertEquals( "org.apache.commons+com.springsource.org.apache.commons.beanutils;version=\"1.6.1\"\n" + "org.apache.commons+com.springsource.org.apache.commons.collections;version=\"2.1.1\"\n" + "org.apache.commons+com.springsource.org.apache.commons.logging;version=\"1.0.4\"\n", IO.collect(file)); file = mr.get("org.apache.commons+com.springsource.org.apache.commons.beanutils", "1.6.1", Strategy.LOWEST, null); assertEquals( "com.springsource.org.apache.commons.beanutils-1.6.1.jar", file.getName()); } public void testMavenx() throws Exception { Maven maven = new Maven(null); CachedPom pom = maven.getPom("javax.xml.bind", "com.springsource.javax.xml.bind", "2.2.0", new URI("http://repository.springsource.com/maven/bundles/release"), new URI( "http://repository.springsource.com/maven/bundles/external")); // Pom pom = maven.getPom("javax.xml.ws", // "com.springsource.javax.xml.ws", "2.1.1", new // URL("http://repository.springsource.com/maven/bundles/release"), new // URL("http://repository.springsource.com/maven/bundles/external")); System.out.println(pom.getGroupId() + " + " + pom.getArtifactId() + "-" + pom.getVersion()); System.out.println(pom.getDependencies(Pom.Scope.compile)); File artifact = pom.getArtifact(); System.out.println(artifact); } /** * Test the pom parser which will turn the pom into a set of properties, * which will make it actually readable according to some. * * @throws Exception */ public void testPomParser() throws Exception { PomParser parser = new PomParser(); Properties p = parser.getProperties(new File("test/ws/maven1/pom.xml")); p.store(System.out, "testing"); assertEquals("Apache Felix Metatype Service", p.get("pom.name")); assertEquals("org.apache.felix", p.get("pom.groupId")); // is from // parent assertEquals("org.apache.felix.metatype", p.get("pom.artifactId")); assertEquals("bundle", p.get("pom.packaging")); Map> map = parser.parseHeader(p.getProperty("pom.scope.test")); Map junit = map.get("junit.junit"); assertNotNull(junit); assertEquals("4.0", junit.get("version")); Map easymock = map.get("org.easymock.easymock"); assertNotNull(easymock); assertEquals("2.4", easymock.get("version")); } // public void testDependencies() throws Exception { // MavenDependencyGraph graph; // // graph = new MavenDependencyGraph(); // File home = new File( System.getProperty("user.home")); // File m2 = new File( home, ".m2"); // File m2Repo = new File( m2, "repository"); // if ( m2Repo.isDirectory()) // graph.addRepository( m2Repo.toURI().toURL()); // // graph.addRepository( new URL("http://repo1.maven.org/maven2/")); // graph.addRepository( new // URL("http://repository.springsource.com/maven/bundles/external")); // // graph.root.add( new File("test/poms/pom-1.xml").toURI().toURL()); // // } // public void testMaven() throws Exception { // MavenRepository maven = new MavenRepository(); // maven.setReporter(processor); // maven.setProperties(new HashMap()); // maven.setRoot(processor.getFile("test/maven-repo")); // // File files[] = maven.get("activation.activation", null); // assertNotNull(files); // assertEquals("activation-1.0.2.jar", files[0].getName()); // // files = maven.get("biz.aQute.bndlib", null); // assertNotNull(files); // assertEquals(5, files.length); // assertEquals("bndlib-0.0.145.jar", files[0].getName()); // assertEquals("bndlib-0.0.255.jar", files[4].getName()); // // List names = maven.list(null); // System.out.println(names); // assertEquals(13, names.size()); // assertTrue(names.contains("biz.aQute.bndlib")); // assertTrue(names.contains("org.apache.felix.javax.servlet")); // assertTrue(names.contains("org.apache.felix.org.osgi.core")); // // List versions = maven.versions("org.apache.felix.javax.servlet"); // assertEquals(1, versions.size()); // versions.contains(new Version("1.0.0")); // // versions = maven.versions("biz.aQute.bndlib"); // assertEquals(5, versions.size()); // versions.contains(new Version("0.0.148")); // versions.contains(new Version("0.0.255")); // } // public void testMavenBsnMapping() throws Exception { // Processor processor = new Processor(); // processor // .setProperty("-plugin", // "aQute.bnd.maven.MavenGroup; groupId=org.apache.felix, aQute.bnd.maven.MavenRepository"); // MavenRepository maven = new MavenRepository(); // maven.setReporter(processor); // Map map = new HashMap(); // map.put("root", IO.getFile(cwd,"test/maven-repo").getAbsolutePath()); // maven.setProperties(map); // // File files[] = maven.get("org.apache.felix.framework", null); // assertNotNull(files); // ; // assertEquals(1, files.length); // } } bnd-1.50.0/biz.aQute.bndlib/src/test/com.acme/0000755000175000017500000000000011656076535020575 5ustar drazzibdrazzibbnd-1.50.0/biz.aQute.bndlib/src/test/com.acme/bnd.bnd0000644000175000017500000000004211656076535022021 0ustar drazzibdrazzibExport-Package: org.objectweb.asm bnd-1.50.0/biz.aQute.bndlib/src/test/com.acme/setsbsn.bnd0000644000175000017500000000010511656076535022737 0ustar drazzibdrazzibExport-Package: org.objectweb.asm Bundle-SymbolicName: is.a.set.bsn bnd-1.50.0/biz.aQute.bndlib/src/test/com.acme/defaultbsn.bnd0000644000175000017500000000004211656076535023405 0ustar drazzibdrazzibExport-Package: org.objectweb.asm bnd-1.50.0/biz.aQute.bndlib/src/test/ClazzTest.java0000644000175000017500000000072611656076535021706 0ustar drazzibdrazzibpackage test; import aQute.lib.osgi.*; import junit.framework.*; public class ClazzTest extends TestCase { /** * Test the uncamel */ public void testUncamel() throws Exception { assertEquals("New", Clazz.unCamel("_new")); assertEquals("An XMLMessage", Clazz.unCamel("anXMLMessage")); assertEquals("A message", Clazz.unCamel("aMessage")); assertEquals("URL", Clazz.unCamel("URL")); assertEquals("A nice party", Clazz.unCamel("aNiceParty")); } } bnd-1.50.0/biz.aQute.bndlib/src/test/TestSignatures.java0000644000175000017500000001112511656076535022742 0ustar drazzibdrazzibpackage test; import java.io.*; import java.lang.reflect.*; import test.signatures.*; import junit.framework.*; import aQute.bnd.compatibility.*; public class TestSignatures extends TestCase { Signatures s = new Signatures(); public void testScopes() throws Exception { assertEquals( "(TE;TC;TD;)V", s.getSignature( Z.V.class.getMethod("fooLCO", Object.class, Object.class, Object.class))); } public void testClass() throws Exception { assertEquals( "Ltest/signatures/X;Ltest/signatures/Y;", s.getSignature(Z.class)); assertEquals( "Ljava/lang/Object;", s.getSignature(Z.V.class)); } public void testMethodDeclarations() throws Exception { assertEquals( "(TE;)V", s.getSignature( Z.class.getMethod("foo", Object.class))); assertEquals( "(TE;)V", s.getSignature( Z.class.getMethod("fooC", InputStream.class))); assertEquals( "(TE;)V", s.getSignature( Z.class.getMethod("fooCI", InputStream.class))); assertEquals( "(TE;)V", s.getSignature( Z.class.getMethod("fooCII", InputStream.class))); assertEquals( "(TE;)V", s.getSignature( Z.class.getMethod("fooII", Serializable.class))); assertEquals( "(TE;)V", s.getSignature( Z.class.getMethod("fooI", Cloneable.class))); assertEquals( "(TE;)V", s.getSignature( Z.class.getMethod("fooP", Object.class))); assertEquals( "(TE;TF;)V", s.getSignature( Z.class.getMethod("foo", Object.class, Object.class))); } public void testFields() throws Exception { // Z.V assertEquals( "Ltest/signatures/Z.V;", s.getSignature(Z.class.getField("referenceToNestedClass"))); // assertEquals( "Ltest/signatures/Z.V;", s.getSignature(Z.class.getField("vc"))); assertEquals( "Ltest/signatures/X;Ltest/signatures/Y;", s.getSignature(Z.class)); assertEquals( "Ljava/lang/Object;", s.getSignature(Z.V.class)); assertEquals( "Ltest/signatures/X;>;", s.getSignature( Z.class.getField("field"))); } public void testWildcards() throws Exception { assertEquals( "Ljava/util/Collection<*>;", s.getSignature( Z.class.getField("wildcard_001"))); assertEquals( "Ljava/util/Collection<+Ljava/lang/Cloneable;>;", s.getSignature( Z.class.getField("wildcard_002"))); assertEquals( "Ljava/util/Collection<-Ljava/lang/Cloneable;>;", s.getSignature( Z.class.getField("wildcard_003"))); assertEquals( "Ljava/util/Collection<+TC;>;", s.getSignature( Z.class.getField("wildcard_004"))); assertEquals( "Ljava/util/Collection<-TC;>;", s.getSignature( Z.class.getField("wildcard_005"))); assertEquals( "Ljava/util/Collection<+Ltest/signatures/Z.V;>;", s.getSignature( Z.class.getField("wildcard_006"))); assertEquals( "Ljava/util/Collection<-Ltest/signatures/Z.V;>;", s.getSignature( Z.class.getField("wildcard_007"))); } public void testNormalize() { assertEquals( "Ltest/signatures/Z.V;", s.normalize("Ltest/signatures/Z.V;")); assertEquals( s.normalize("(TA;)V"), s.normalize("(TE;)V")); assertEquals( s.normalize("(TA;TB;)V"), s.normalize("(TE;TC;)V")); // we use (A,A) and test against (A,B) assertFalse( s.normalize("(TA;TA;)V").equals(s.normalize("(TE;TC;)V"))); assertEquals( "<_0:Ljava/lang/Object;>(T_0;)V", s.normalize("(TE;)V")); assertEquals( "<_0:Ljava/lang/Object;>(T_0;T_1;T_2;)V", s.normalize("(TE;TC;TD;)V")); assertEquals( "<_0:Ljava/lang/Object;>Ljava/lang/Object;", s.normalize("<_0:Ljava/lang/Object;>Ljava/lang/Object;")); } public void testCompatibility() throws Exception { String _001 =ns(Z.class.getMethod("compatibility_001")); String _002 =ns(Z.class.getMethod("compatibility_002")); String _003 =ns(Z.class.getMethod("compatibility_003")); assertEquals( _001, _002); assertTrue( _001.equals(_002)); assertFalse( _001.equals(_003)); } private String ns(Method method) throws Exception { String sig = s.getSignature(method); return s.normalize(sig); } } bnd-1.50.0/biz.aQute.bndlib/src/test/NoUsesTest.java0000644000175000017500000001056211656076535022036 0ustar drazzibdrazzibpackage test; import java.io.*; import java.util.*; import junit.framework.*; import aQute.lib.osgi.*; public class NoUsesTest extends TestCase { /* * Check if we explicitly set a uses directive, prepend the calculated * but the calculated is empty. This should remove the extraneuous comma */ public void testExplicitUsesWithPrependZeroUses() throws Exception { Builder bmaker = new Builder(); bmaker.setProperty("Private-Package", "org.osgi.framework"); bmaker.setProperty("Export-Package", "org.osgi.util.tracker;uses:=\"<>,not.used\""); String uses = findUses(bmaker, "org.osgi.util.tracker"); assertEquals("not.used", uses); } /* * Check if we explicitly set a uses directive, but append it * with the calculated directive */ public void testExplicitUsesWithAppend() throws Exception { Builder bmaker = new Builder(); bmaker.setProperty("Export-Package", "org.osgi.util.tracker;uses:=\"not.used,<>\""); String uses = findUses(bmaker, "org.osgi.util.tracker"); assertTrue("not.used", uses.indexOf("not.used")>=0); assertTrue("org.osgi.framework", uses.indexOf("org.osgi.framework")>=0); } /* * Check if we explicitly set a uses directive, append the calculated * but the calculated is empty. This should remove the extraneuous comma */ public void testExplicitUsesWithAppendZeroUses() throws Exception { Builder bmaker = new Builder(); bmaker.setProperty("Private-Package", "org.osgi.framework"); bmaker.setProperty("Export-Package", "org.osgi.util.tracker;uses:=\"not.used,<>\""); String uses = findUses(bmaker, "org.osgi.util.tracker"); assertEquals("not.used", uses); } /* * Check if we explicitly set a uses directive, but append it * with the calculated directive */ public void testExplicitUsesWithPrepend() throws Exception { Builder bmaker = new Builder(); bmaker.setProperty("Export-Package", "org.osgi.util.tracker;uses:=\"<>,not.used\""); String uses = findUses(bmaker, "org.osgi.util.tracker"); assertTrue("not.used", uses.indexOf("not.used")>=0); assertTrue("org.osgi.framework", uses.indexOf("org.osgi.framework")>=0); } /* * Check if we explicitly set a uses directive */ public void testExplicitUses() throws Exception { Builder bmaker = new Builder(); bmaker.setProperty("Export-Package", "org.osgi.util.tracker;uses:=\"not.used\""); String uses = findUses(bmaker, "org.osgi.util.tracker"); assertEquals("not.used", uses); } public void testExportedUses() throws Exception { Builder bmaker = new Builder(); bmaker.setProperty("Export-Package", "org.osgi.util.tracker, org.osgi.framework"); String uses = findUses(bmaker, "org.osgi.util.tracker"); assertEquals("org.osgi.framework", uses); } public void testPrivateUses() throws Exception { Builder bmaker = new Builder(); bmaker.setProperty("Private-Package", "org.osgi.framework"); bmaker.setProperty("Export-Package", "org.osgi.util.tracker"); String uses = findUses(bmaker, "org.osgi.util.tracker"); assertNull("org.osgi.framework", uses); } public void testHasUses() throws Exception { Builder bmaker = new Builder(); bmaker.setProperty("Export-Package", "test.activator"); String uses = findUses(bmaker, "test.activator"); assertEquals("org.osgi.framework", uses); } public void testNoUses() throws Exception { Builder bmaker = new Builder(); bmaker.setProperty("Export-Package", "test.activator"); bmaker.setProperty("-nouses", "true"); String uses = findUses(bmaker, "test.activator"); assertNull("org.osgi.framework", uses); } String findUses(Builder bmaker, String pack ) throws Exception { File cp[] = { new File("bin"), new File("jar/osgi.jar") }; bmaker.setClasspath(cp); Jar jar = bmaker.build(); assertOk(bmaker); String exports = jar.getManifest().getMainAttributes().getValue("Export-Package"); assertNotNull("exports", exports ); Map> map = Processor.parseHeader(exports, null); if ( map == null ) return null; Map clause = map.get(pack); if ( clause == null ) return null; return (String) clause.get("uses:"); } void assertOk(Analyzer bmaker) throws Exception { System.out.println(bmaker.getErrors()); System.out.println(bmaker.getWarnings()); bmaker.getJar().getManifest().write(System.out); assertEquals(0,bmaker.getErrors().size()); assertEquals(0,bmaker.getWarnings().size()); } } bnd-1.50.0/biz.aQute.bndlib/src/test/top.mf0000755000175000017500000000031111656076535020237 0ustar drazzibdrazzib-include=include.mf Export-Package=aQute.bean;special=true, org.objectweb.asm.util, *xml2mif Import-Package=* Bundle-Includes=../../jar, simple.mf, @../../jar/thinlet.jar Private-Package=aQute.lib.aim bnd-1.50.0/biz.aQute.bndlib/src/test/InlineTest.java0000644000175000017500000000134111656076535022033 0ustar drazzibdrazzibpackage test; import java.util.jar.*; import aQute.lib.osgi.*; import junit.framework.*; public class InlineTest extends TestCase { public void testSimple() throws Exception { Builder builder = new Builder(); builder.setProperty("Include-Resource", "@jar/osgi.jar"); Jar jar = builder.build(); Manifest manifest = jar.getManifest(); // See if the version is the default and not copied from the inline // bundle. String version = manifest.getMainAttributes().getValue("Bundle-Version"); assertEquals("0", version ); // Check if we got some relevant directories assertTrue(jar.getDirectories().containsKey("org/osgi/framework")); assertTrue(jar.getDirectories().containsKey("org/osgi/util/tracker")); } } bnd-1.50.0/biz.aQute.bndlib/src/test/versionpolicy/0000755000175000017500000000000011656076535022020 5ustar drazzibdrazzibbnd-1.50.0/biz.aQute.bndlib/src/test/versionpolicy/implmajor/0000755000175000017500000000000011656076535024012 5ustar drazzibdrazzibbnd-1.50.0/biz.aQute.bndlib/src/test/versionpolicy/implmajor/MajorImplemented.java0000644000175000017500000000027111656076535030111 0ustar drazzibdrazzibpackage test.versionpolicy.implmajor; import test.versionpolicy.api.EventHandler; public class MajorImplemented implements EventHandler { public void listen(Object o) { } } bnd-1.50.0/biz.aQute.bndlib/src/test/versionpolicy/implemented/0000755000175000017500000000000011656076535024323 5ustar drazzibdrazzibbnd-1.50.0/biz.aQute.bndlib/src/test/versionpolicy/implemented/Implemented.java0000644000175000017500000000024511656076535027432 0ustar drazzibdrazzibpackage test.versionpolicy.implemented; import test.versionpolicy.api.*; public class Implemented implements EventAdmin { public void post(Object o) { } } bnd-1.50.0/biz.aQute.bndlib/src/test/versionpolicy/uses/0000755000175000017500000000000011656076535022777 5ustar drazzibdrazzibbnd-1.50.0/biz.aQute.bndlib/src/test/versionpolicy/uses/Uses.java0000644000175000017500000000016011656076535024556 0ustar drazzibdrazzibpackage test.versionpolicy.uses; import test.versionpolicy.api.*; public class Uses { EventAdmin admin; } bnd-1.50.0/biz.aQute.bndlib/src/test/versionpolicy/api/0000755000175000017500000000000011656076535022571 5ustar drazzibdrazzibbnd-1.50.0/biz.aQute.bndlib/src/test/versionpolicy/api/package-info.java0000644000175000017500000000022011656076535025752 0ustar drazzibdrazzib@Version("1.2.0.${build}") @Export(exclude=PrivateImpl.class, mandatory="a=b") package test.versionpolicy.api; import aQute.bnd.annotation.*; bnd-1.50.0/biz.aQute.bndlib/src/test/versionpolicy/api/EventHandler.java0000644000175000017500000000027011656076535026012 0ustar drazzibdrazzibpackage test.versionpolicy.api; import aQute.bnd.annotation.*; @SuppressWarnings("deprecation") @UsePolicy @ConsumerType public interface EventHandler { void listen(Object o); } bnd-1.50.0/biz.aQute.bndlib/src/test/versionpolicy/api/PrivateImpl.java0000644000175000017500000000007711656076535025674 0ustar drazzibdrazzibpackage test.versionpolicy.api; public class PrivateImpl { } bnd-1.50.0/biz.aQute.bndlib/src/test/versionpolicy/api/EventAdmin.java0000644000175000017500000000021011656076535025457 0ustar drazzibdrazzibpackage test.versionpolicy.api; import aQute.bnd.annotation.*; @ProviderType public interface EventAdmin { void post(Object o); } bnd-1.50.0/biz.aQute.bndlib/src/test/ResourcesTest.java0000644000175000017500000002050111656076535022566 0ustar drazzibdrazzibpackage test; import java.util.*; import junit.framework.*; import aQute.lib.osgi.*; public class ResourcesTest extends TestCase { public void testNegativeFilter() throws Exception { Builder b = new Builder(); b.setProperty("Include-Resource", "TargetFolder=test/ws/p2/Resources;filter:=!*.txt"); b.setProperty("-resourceonly", "true"); Jar jar = b.build(); Resource r = jar.getResource("TargetFolder/resource1.res"); assertNotNull(r); r = jar.getResource("TargetFolder/resource2.res"); assertNotNull(r); r = jar.getResource("TargetFolder/resource5.asc"); assertNotNull(r); } public void testCopyToRoot() throws Exception { Builder bmaker = new Builder(); Properties p = new Properties(); p.setProperty("-resourceonly", "true"); p.setProperty("Include-Resource", "/=src/test/activator"); bmaker.setProperties(p); Jar jar = bmaker.build(); for ( String s : jar.getResources().keySet() ) System.out.println( s); assertNotNull(jar.getResource("Activator.java")); assertEquals( 0, bmaker.getErrors().size() ); assertEquals( 0, bmaker.getWarnings().size() ); } public void testIncludeResourceDirectivesDefault() throws Exception { Builder b = new Builder(); b.setProperty("Include-Resource", "TargetFolder=test/ws/p2/Resources"); b.setProperty("-resourceonly", "true"); Jar jar = b.build(); Resource r = jar.getResource("TargetFolder/resource3.txt"); assertNotNull(r); r = jar.getResource("TargetFolder/resource4.txt"); assertNotNull(r); r = jar.getResource("TargetFolder/more/resource6.txt"); assertNotNull(r); r = jar.getResource("TargetFolder/more/resource7.txt"); assertNotNull(r); r = jar.getResource("TargetFolder/stuff/resource9.res"); assertNotNull(r); r = jar.getResource("TargetFolder/text.txt"); assertNotNull(r); } public void testIncludeResourceDoNotCopy() throws Exception { Builder b = new Builder(); // Use Properties file otherwise -donotcopy is not picked up Properties p = new Properties(); p.put("-donotcopy", "CVS|.svn|stuff"); p.put("Include-Resource", "TargetFolder=test/ws/p2/Resources"); p.put("-resourceonly", "true"); b.setProperties(p); Jar jar = b.build(); Resource r = jar.getResource("TargetFolder/resource3.txt"); assertNotNull(r); r = jar.getResource("TargetFolder/resource4.txt"); assertNotNull(r); r = jar.getResource("TargetFolder/more/resource6.txt"); assertNotNull(r); r = jar.getResource("TargetFolder/more/resource7.txt"); assertNotNull(r); r = jar.getResource("TargetFolder/stuff/resource9.res"); assertNull(r); r = jar.getResource("TargetFolder/text.txt"); assertNotNull(r); } public void testIncludeResourceDirectivesFilterRecursive() throws Exception { Builder b = new Builder(); b.setProperty("Include-Resource", "TargetFolder=test/ws/p2/Resources;filter:=re*.txt"); b.setProperty("-resourceonly", "true"); Jar jar = b.build(); Resource r = jar.getResource("TargetFolder/resource3.txt"); assertNotNull(r); r = jar.getResource("TargetFolder/resource4.txt"); assertNotNull(r); r = jar.getResource("TargetFolder/more/resource6.txt"); assertNotNull(r); r = jar.getResource("TargetFolder/more/resource7.txt"); assertNotNull(r); r = jar.getResource("TargetFolder/text.txt"); assertNull(r); } public void testIncludeResourceDirectivesFilterRecursive2() throws Exception { Builder b = new Builder(); b.setProperty("Include-Resource", "test/ws/p2/Resources;filter:=re*.txt"); b.setProperty("-resourceonly", "true"); Jar jar = b.build(); Resource r = jar.getResource("resource3.txt"); assertNotNull(r); r = jar.getResource("resource4.txt"); assertNotNull(r); r = jar.getResource("more/resource6.txt"); assertNotNull(r); r = jar.getResource("more/resource7.txt"); assertNotNull(r); r = jar.getResource("text.txt"); assertNull(r); } public void testIncludeResourceDirectivesFilterNonRecursive() throws Exception { Builder b = new Builder(); b.setProperty("Include-Resource", "TargetFolder=test/ws/p2/Resources;filter:=re*.txt;recursive:=false"); b.setProperty("-resourceonly", "true"); Jar jar = b.build(); Resource r = jar.getResource("TargetFolder/resource3.txt"); assertNotNull(r); r = jar.getResource("TargetFolder/resource4.txt"); assertNotNull(r); r = jar.getResource("TargetFolder/more/resource6.txt"); assertNull(r); r = jar.getResource("TargetFolder/more/resource7.txt"); assertNull(r); } public void testIncludeResourceDirectivesFilterRecursiveFlatten() throws Exception { Builder b = new Builder(); b.setProperty("Include-Resource", "TargetFolder=test/ws/p2/Resources;filter:=re*.txt;flatten:=true"); b.setProperty("-resourceonly", "true"); Jar jar = b.build(); Resource r = jar.getResource("TargetFolder/resource3.txt"); assertNotNull(r); r = jar.getResource("TargetFolder/resource4.txt"); assertNotNull(r); r = jar.getResource("TargetFolder/resource6.txt"); assertNotNull(r); r = jar.getResource("TargetFolder/resource7.txt"); assertNotNull(r); r = jar.getResource("TargetFolder/resource1.res"); assertNull(r); } public void testEmpty() throws Exception { Builder bmaker = new Builder(); Properties p = new Properties(); p.setProperty("-resourceonly", "true"); p.setProperty("Include-Resource", " "); bmaker.setProperties(p); Jar jar = bmaker.build(); assertEquals( 0, jar.getResources().size()); assertEquals( 1, bmaker.getErrors().size() ); System.out.println(bmaker.getErrors()); assertTrue( bmaker.getErrors().get(0).indexOf("The JAR is empty") >= 0); assertEquals( 0, bmaker.getWarnings().size() ); } public void testLiteral() throws Exception { Builder bmaker = new Builder(); Properties p = new Properties(); p.setProperty("-resourceonly","true"); p.setProperty("Include-Resource", "text;literal=TEXT;extra='hello/world;charset=UTF-8'"); bmaker.setProperties(p); bmaker.setClasspath( new String[] {"src"}); Jar jar = bmaker.build(); Resource resource =jar.getResource("text"); assertNotNull(resource); byte buffer[] = new byte[1000]; int size = resource.openInputStream().read(buffer); String s= new String(buffer,0,size); assertEquals("TEXT",s); assertEquals("hello/world;charset=UTF-8", resource.getExtra()); report(bmaker); } /** * Check if we can create a jar on demand through the make * facility. * * @throws Exception */ public void testOnDemandResource() throws Exception { Builder bmaker = new Builder(); Properties p = new Properties(); p.setProperty("-resourceonly","true"); p.setProperty("-plugin", "aQute.bnd.make.MakeBnd, aQute.bnd.make.MakeCopy"); p.setProperty("-make", "(*).jar;type=bnd;recipe=bnd/$1.bnd"); p.setProperty("Include-Resource", "ondemand.jar"); bmaker.setProperties(p); bmaker.setClasspath( new String[] {"bin"}); Jar jar = bmaker.build(); Resource resource =jar.getResource("ondemand.jar"); assertNotNull(resource); assertTrue( resource instanceof JarResource ); report(bmaker); } void report(Processor processor) { System.out.println(); for ( int i=0; i p = OSGiHeader.parseProperties("a=1, b=\"3 3\", c=c"); assertEquals("1", p.get("a")); assertEquals("3 3", p.get("b")); assertEquals("c", p.get("c")); } public void testClauseName() { assertNames("a,b,c;", new String[] {"a","b","c"}); assertNames("a,b,c", new String[] {"a","b","c"}); assertNames("a;x=0,b;x=0,c;x=0", new String[] {"a","b","c"}); assertNames("a;b;c;x=0", new String[] {"a","b","c"}); assertNames(",", new String[] {}, null, "Empty clause, usually caused" ); assertNames("a;a,b", new String[] { "a", "a~", "b"}, null, "Duplicate name a used in header"); assertNames("a;x=0;b", new String[] { "a", "b"}, "Header contains name field after attribute or directive", null); assertNames("a;x=0;x=0,b", new String[] { "a", "b"}, null, "Duplicate attribute/directive name"); assertNames("a;;;,b", new String[] { "a", "b"}); assertNames(",,a,,", new String[] { "a"}, null, "Empty clause, usually caused by repeating"); assertNames(",a", new String[] { "a"}, null, "Empty clause, usually caused"); assertNames(",a,b,c,", new String[] { "a", "b", "c" },null, "Empty clause, usually caused"); assertNames("a,b,c,", new String[] { "a", "b", "c" }, null, "Empty clause, usually caused"); assertNames("a,b,,c", new String[] { "a", "b", "c" }, null, "Empty clause, usually caused"); } void assertNames(String header, String[] keys) { assertNames(header,keys, null, null); } void assertNames(String header, String[] keys, String expectedError, String expectedWarning) { Processor p = new Processor(); p.setPedantic(true); Map> map = Processor.parseHeader(header, p); for (String key : keys ) assertTrue(map.containsKey(key)); assertEquals(keys.length, map.size()); if (expectedError != null) { System.out.println(p.getErrors()); assertTrue(p.getErrors().size()>0); assertTrue(((String) p.getErrors().get(0)).indexOf(expectedError) >= 0); } else assertEquals(0, p.getErrors().size()); if (expectedWarning != null) { System.out.println(p.getWarnings()); assertTrue(p.getWarnings().size()>0); String w = (String) p.getWarnings().get(0); assertTrue(w.startsWith(expectedWarning)); } else assertEquals(0, p.getWarnings().size()); } public void testSimple() { String s = "a;a=a1;b=a2;c=a3, b;a=b1;b=b2;c=b3, c;d;e;a=x1"; Map> map = Processor.parseHeader(s, null); assertEquals(5, map.size()); Map a = map.get("a"); assertEquals("a1", a.get("a")); assertEquals("a2", a.get("b")); assertEquals("a3", a.get("c")); Map d = map.get("d"); assertEquals("x1", d.get("a")); Map e = map.get("e"); assertEquals(e, d); System.out.println(map); } } bnd-1.50.0/biz.aQute.bndlib/src/test/iht/0000755000175000017500000000000011656076535017677 5ustar drazzibdrazzibbnd-1.50.0/biz.aQute.bndlib/src/test/iht/test.prop0000755000175000017500000000001011656076535021552 0ustar drazzibdrazzibtest: 1 bnd-1.50.0/biz.aQute.bndlib/src/test/CorruptManifest.java0000755000175000017500000000353111656076535023110 0ustar drazzibdrazzibpackage test; import java.io.*; import java.util.jar.*; import junit.framework.*; import aQute.lib.osgi.*; public class CorruptManifest extends TestCase { static String ltext= "bla bla \nbla bla bla bla \nbla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla "; public void testCorruptJar() throws Exception { Builder b = new Builder(); b.setProperty("NL1", "\n"); b.setProperty("NL2", "\r\n"); b.setProperty("NL3", "."); b.setProperty("NL4", ".\n.\n"); b.setProperty("NL5", ltext); b.setProperty("Export-Package", "*"); b.setClasspath( new File[] {new File("jar/asm.jar")}); Jar jar = b.build(); Manifest manifest = jar.getManifest(); jar.writeManifest(System.out); Attributes main = manifest.getMainAttributes(); assertNull(main.getValue("NL1")); assertNull(main.getValue("NL2")); assertEquals(".", main.getValue("NL3")); assertEquals(".\n.\n", main.getValue("NL4")); assertEquals(ltext, main.getValue("NL5")); ByteArrayOutputStream bout = new ByteArrayOutputStream(); jar.writeManifest(bout); bout.flush(); System.out.println("-----"); System.out.write(bout.toByteArray()); System.out.println("-----"); ByteArrayInputStream bin = new ByteArrayInputStream( bout.toByteArray()); manifest = new Manifest(bin); main = manifest.getMainAttributes(); assertNull(main.getValue("NL1")); assertNull(main.getValue("NL2")); assertEquals(".", main.getValue("NL3")); assertEquals("..", main.getValue("NL4")); } } bnd-1.50.0/biz.aQute.bndlib/src/test/TestQuotedTokenizer.java0000755000175000017500000000336311656076535023762 0ustar drazzibdrazzibpackage test; import junit.framework.*; import aQute.libg.qtokens.*; public class TestQuotedTokenizer extends TestCase { public void testNativeSeps() { String s[] = new QuotedTokenizer("x;c;d=4", ";,=", true).getTokens(); assertEquals("Length", 7, s.length); assertEquals("x", s[0]); assertEquals(";", s[1]); assertEquals("c", s[2]); assertEquals(";", s[3]); assertEquals("d", s[4]); assertEquals("=", s[5]); assertEquals("4", s[6]); } public void testSimple() { String s[] = new QuotedTokenizer("1.jar, 2.jar, \t 3.jar", ",").getTokens(); assertEquals("Length", 3, s.length); assertEquals("1.jar", s[0]); assertEquals("2.jar", s[1]); assertEquals("3.jar", s[2]); } public void testQuoted() { String s[] = new QuotedTokenizer("'1 ,\t.jar'", ",").getTokens(); assertEquals("Length", 1, s.length); assertEquals("1 ,\t.jar", s[0]); } public void testWhiteSpace() { String s[] = new QuotedTokenizer(" 1.jar, 2.jar ", ",").getTokens(); assertEquals("Length", 2, s.length); assertEquals("1.jar", s[0]); assertEquals("2.jar", s[1]); } public void testMultipleSeps() { String s[] = new QuotedTokenizer("1.jar,,,,,,,,,,, , ,2.jar", ",").getTokens(); assertEquals("Length", 14, s.length); assertEquals("1.jar", s[0]); assertEquals("2.jar", s[13]); } public void testNative() { String s[] = new QuotedTokenizer("x.dll;y.dll;abc=3;def=5;version=\"1.2.34,123\"", ";,=").getTokens(); assertEquals("Length", 8, s.length); assertEquals("x.dll", s[0]); assertEquals("y.dll", s[1]); assertEquals("abc", s[2]); assertEquals("3", s[3]); assertEquals("def", s[4]); assertEquals("5", s[5]); assertEquals("version", s[6]); assertEquals("1.2.34,123", s[7]); } } bnd-1.50.0/biz.aQute.bndlib/src/test/beasymock.bnd0000755000175000017500000000000111656076535021547 0ustar drazzibdrazzib bnd-1.50.0/biz.aQute.bndlib/src/test/variables.mf0000755000175000017500000000003111656076535021404 0ustar drazzibdrazzibp=aQute.test Header=${p} bnd-1.50.0/biz.aQute.bndlib/src/test/ClassReferenceTest.java0000755000175000017500000000314211656076535023505 0ustar drazzibdrazzibpackage test; import java.util.*; import java.util.jar.*; import junit.framework.*; import aQute.lib.osgi.*; public class ClassReferenceTest extends TestCase { class Inner { } static { System.out.println(Inner.class); } /** * We create a JAR with the test.classreferenc.ClassReference class. This * class contains a javax.swing.Box.class reference Prior to Java 1.5, this * was done in a silly way that is handled specially. After 1.5 it is a * normal reference. * * @throws Exception */ public void testReference() throws Exception { Properties properties = new Properties(); properties.put("-classpath", "compilerversions/compilerversions.jar"); String[] packages = { "sun_1_1", "sun_1_6", "eclipse_1_1", "sun_1_2", "sun_1_3", "sun_1_4", "sun_1_5", "sun_jsr14", "eclipse_1_5", "eclipse_1_6", "eclipse_1_2", "eclipse_1_3", "eclipse_1_4", "eclipse_jsr14" }; for ( int i =0; i=0); assertFalse("Package " + packages[i] + "should not contain ClassRef", imports.indexOf("ClassRef")>=0); } } } bnd-1.50.0/biz.aQute.bndlib/src/test/WorkspaceTest.java0000644000175000017500000000134611656076535022560 0ustar drazzibdrazzibpackage test; import java.io.*; import junit.framework.*; import aQute.bnd.build.*; public class WorkspaceTest extends TestCase { public void testWorkspace() throws Exception { Workspace ws = Workspace.getWorkspace( new File("test/w o r k s p a c e")); assertEquals( "parent", ws.getProperty("override")); assertEquals( "true", ws.getProperty("ext")); assertEquals( "abcdef", ws.getProperty("test")); } public void testNestedWorkspace() throws Exception { Workspace ws = Workspace.getWorkspace( new File("test/redirectws/wss/ws")); assertEquals( "true", ws.getProperty("testcnf")); assertEquals( "true", ws.getProperty("ext")); } } bnd-1.50.0/biz.aQute.bndlib/src/test/lib/0000755000175000017500000000000011656076535017661 5ustar drazzibdrazzibbnd-1.50.0/biz.aQute.bndlib/src/test/lib/deployer/0000755000175000017500000000000011656076535021504 5ustar drazzibdrazzibbnd-1.50.0/biz.aQute.bndlib/src/test/lib/deployer/obr/0000755000175000017500000000000011656076535022266 5ustar drazzibdrazzibbnd-1.50.0/biz.aQute.bndlib/src/test/lib/deployer/obr/OBRTest.java0000644000175000017500000001414211656076535024415 0ustar drazzibdrazzibpackage test.lib.deployer.obr; import java.io.File; import java.net.MalformedURLException; import java.net.URL; import java.util.HashMap; import java.util.List; import java.util.Map; import junit.framework.TestCase; import aQute.bnd.service.RepositoryPlugin.Strategy; import aQute.lib.deployer.obr.OBR; import aQute.libg.version.Version; public class OBRTest extends TestCase { private OBR obr; private NanoHTTPD httpd; @Override protected void setUp() throws Exception { obr = new OBR(); obr.setLocations(new URL[] { OBRTest.class.getResource("fullobr.xml") }); File tmpFile = File.createTempFile("cache", ".tmp"); tmpFile.deleteOnExit(); obr.setCacheDirectory(new File(tmpFile.getAbsolutePath() + ".dir")); httpd = new NanoHTTPD(new File("test/http"), 18080); } @Override protected void tearDown() throws Exception { httpd.stop(); File[] cachedFiles = obr.getCacheDirectory().listFiles(); if (cachedFiles != null) { for (File file : cachedFiles) { file.delete(); } } obr.getCacheDirectory().delete(); } public void testSetProperties() { OBR obr2 = new OBR(); Map props = new HashMap(); props.put("location", OBRTest.class.getResource("fullobr.xml").toString()); props.put("cache", this.obr.getCacheDirectory().getAbsolutePath()); obr2.setProperties(props); assertEquals(1, obr2.getOBRIndexes().size()); assertEquals(OBRTest.class.getResource("fullobr.xml").toString(), obr2.getOBRIndexes().get(0).toString()); assertEquals(this.obr.getCacheDirectory(), obr2.getCacheDirectory()); } public void testInvalidProperties() { OBR obr2 = new OBR(); try { obr2.setProperties(new HashMap()); fail("Should throw IllegalArgumentException"); } catch (IllegalArgumentException e) { // Expected } } public void testCacheDirectoryNotSpecified() { OBR obr2 = new OBR(); Map props = new HashMap(); props.put("location", OBRTest.class.getResource("fullobr.xml").toString()); obr2.setProperties(props); } public void testGetLatest() throws Exception { File[] files = obr.get("name.njbartlett.osgi.emf.minimal", "latest"); assertNotNull(files); assertEquals(1, files.length); assertEquals("name.njbartlett.osgi.emf.minimal-2.7.0.jar", files[0].getName()); } public void testGetAll() throws Exception { File[] files = obr.get("name.njbartlett.osgi.emf.xmi", null); assertNotNull(files); assertEquals(2, files.length); assertEquals("name.njbartlett.osgi.emf.xmi-2.5.0.jar", files[0].getName()); assertEquals("name.njbartlett.osgi.emf.xmi-2.7.0.jar", files[1].getName()); } public void testGetHttp() throws Exception { File[] files = obr.get("org.example.dummy", "latest"); assertNotNull(files); assertEquals(1, files.length); assertNotNull(files[0]); assertEquals("bundles_dummybundle.jar", files[0].getName()); } public void testGetBsnLowest() throws Exception { File result = obr.get("name.njbartlett.osgi.emf.xmi", null, Strategy.LOWEST, null); assertNotNull(result); assertEquals("name.njbartlett.osgi.emf.xmi-2.5.0.jar", result.getName()); } public void testGetBsnHighest() throws Exception { File result = obr.get("name.njbartlett.osgi.emf.xmi", null, Strategy.HIGHEST, null); assertNotNull(result); assertEquals("name.njbartlett.osgi.emf.xmi-2.7.0.jar", result.getName()); } public void testGetBsnLowestWithRange() throws Exception { File result = obr.get("name.njbartlett.osgi.emf.xmi", "2.5.1", Strategy.LOWEST, null); assertNotNull(result); assertEquals("name.njbartlett.osgi.emf.xmi-2.7.0.jar", result.getName()); } public void testGetBsnHighestWithRange() throws Exception { File result = obr.get("name.njbartlett.osgi.emf.xmi", "[2.5,2.7)", Strategy.HIGHEST, null); assertNotNull(result); assertEquals("name.njbartlett.osgi.emf.xmi-2.5.0.jar", result.getName()); } public void testGetPackageLowest() throws Exception { Map props = new HashMap(); props.put("package", "org.eclipse.emf.common"); File result = obr.get(null, null, Strategy.LOWEST, props); assertNotNull(result); assertEquals("name.njbartlett.osgi.emf.minimal-2.6.1.jar", result.getName()); } public void testGetPackageLowestWithRange() throws Exception { Map props = new HashMap(); props.put("package", "org.eclipse.emf.common"); File result = obr.get(null, "2.6.2", Strategy.LOWEST, props); assertNotNull(result); assertEquals("name.njbartlett.osgi.emf.minimal-2.7.0.jar", result.getName()); } public void testGetPackageHighest() throws Exception { Map props = new HashMap(); props.put("package", "org.eclipse.emf.common"); File result = obr.get(null, null, Strategy.HIGHEST, props); assertNotNull(result); assertEquals("name.njbartlett.osgi.emf.minimal-2.7.0.jar", result.getName()); } public void testGetPackageHighestWithRange() throws Exception { Map props = new HashMap(); props.put("package", "org.eclipse.emf.common"); File result = obr.get(null, "[2.6,2.7)", Strategy.HIGHEST, props); assertNotNull(result); assertEquals("name.njbartlett.osgi.emf.minimal-2.6.1.jar", result.getName()); } public void testList() throws Exception { List result = obr.list("name\\.njbartlett\\..*"); assertNotNull(result); assertEquals(2, result.size()); } public void testVersions() throws Exception { List result = obr.versions("name.njbartlett.osgi.emf.minimal"); assertEquals(2, result.size()); assertEquals(new Version("2.6.1.v20100914-1218"), result.get(0)); assertEquals(new Version("2.7.0.201104130744"), result.get(1)); } public void testName() throws MalformedURLException { assertEquals(OBRTest.class.getResource("fullobr.xml").toString(), obr.getName()); OBR obr2 = new OBR(); obr2.setLocations(new URL[] { new URL("http://www.example.com/bundles/dummybundle.jar"), new URL("file:/Users/neil/bundles/dummy.jar") }); assertEquals("http://www.example.com/bundles/dummybundle.jar,file:/Users/neil/bundles/dummy.jar", obr2.getName()); } } bnd-1.50.0/biz.aQute.bndlib/src/test/lib/deployer/obr/OBRParseTest.java0000644000175000017500000001067711656076535025421 0ustar drazzibdrazzibpackage test.lib.deployer.obr; import java.util.*; import java.util.concurrent.atomic.*; import javax.xml.parsers.*; import junit.framework.*; import aQute.lib.deployer.obr.*; public class OBRParseTest extends TestCase { public void testParseOBR() throws Exception { final List resources = new ArrayList(); IRepositoryListener listener = new IRepositoryListener() { public boolean processResource(Resource resource) { resources.add(resource); return true; } public boolean processReferral(String fromUrl, Referral referral, int maxDepth, int currentDepth) { fail("Method processReferral should not be called from this test!"); return true; } }; SAXParserFactory parserFactory = SAXParserFactory.newInstance(); SAXParser parser = parserFactory.newSAXParser(); parser.parse(OBRParseTest.class.getResourceAsStream("testobr.xml"), new OBRSAXHandler("file:sample/testobr.xml", listener)); assertEquals(2, resources.size()); Resource firstResource = resources.get(0); assertEquals("org.apache.felix.shell", firstResource.getSymbolicName()); assertEquals("file:sample/testobr.xml", firstResource.getBaseUrl()); assertEquals(6, firstResource.getCapabilities().size()); Capability lastCapability = firstResource.getCapabilities().get(5); assertEquals("package", lastCapability.getName()); assertEquals(3, lastCapability.getProperties().size()); assertEquals(new Property("package", null, "org.apache.felix.shell"), lastCapability.getProperties().get(0)); assertEquals(new Property("uses", null, "org.osgi.framework"), lastCapability.getProperties().get(1)); assertEquals(new Property("version", "version", "1.0.0"), lastCapability.getProperties().get(2)); } public void testParseOBRReferral() throws Exception { final SAXParserFactory parserFactory = SAXParserFactory.newInstance(); final List resources = new ArrayList(); IRepositoryListener listener = new IRepositoryListener() { public boolean processResource(Resource resource) { resources.add(resource); return true; } public boolean processReferral(String fromUrl, Referral referral, int maxDepth, int currentDepth) { if ("file:sample/testobr.xml".equals(referral.getUrl())) { try { SAXParser parser = parserFactory.newSAXParser(); parser.parse(OBRParseTest.class.getResourceAsStream("testobr.xml"), new OBRSAXHandler("file:sample/testobr.xml", this, maxDepth, currentDepth)); } catch (Exception e) { throw new RuntimeException(e); } } return true; } }; SAXParser parser = parserFactory.newSAXParser(); parser.parse(OBRParseTest.class.getResourceAsStream("referralobr.xml"), new OBRSAXHandler("file:sample/referral.xml", listener)); assertEquals(2, resources.size()); Resource firstResource = resources.get(0); assertEquals("org.apache.felix.shell", firstResource.getSymbolicName()); assertEquals("file:sample/testobr.xml", firstResource.getBaseUrl()); assertEquals(6, firstResource.getCapabilities().size()); Capability lastCapability = firstResource.getCapabilities().get(5); assertEquals("package", lastCapability.getName()); assertEquals(3, lastCapability.getProperties().size()); assertEquals(new Property("package", null, "org.apache.felix.shell"), lastCapability.getProperties().get(0)); assertEquals(new Property("uses", null, "org.osgi.framework"), lastCapability.getProperties().get(1)); assertEquals(new Property("version", "version", "1.0.0"), lastCapability.getProperties().get(2)); } public void testEarlyTermination() throws Exception { SAXParserFactory parserFactory = SAXParserFactory.newInstance(); SAXParser parser = parserFactory.newSAXParser(); final AtomicInteger counter = new AtomicInteger(0); IRepositoryListener listener = new IRepositoryListener() { public boolean processResource(Resource resource) { counter.incrementAndGet(); return false; } public boolean processReferral(String fromUrl, Referral referral, int maxDepth, int currentDepth) { fail("Method processReferral should not be called from this test!"); return false; } }; boolean parseStopped = false; try { parser.parse(OBRParseTest.class.getResourceAsStream("unparseable.xml"), new OBRSAXHandler("", listener)); fail("Parser not stopped"); } catch (StopParseException e) { // Expected parseStopped = true; } assertEquals(1, counter.get()); assertTrue(parseStopped); } } bnd-1.50.0/biz.aQute.bndlib/src/test/lib/deployer/obr/unparseable.xml0000644000175000017500000000667111656076535025323 0ustar drazzibdrazzib A simple OSGi command shell service. 62719 http://www.apache.org/licenses/LICENSE-2.0.txt http://www.apache.org/

Import Service org.osgi.service.startlevel.StartLevel Import Service org.osgi.service.packageadmin.PackageAdmin Import package org.apache.felix.shell ;version=1.0.0 Import package org.osgi.framework ;version=1.4.0 Import package org.osgi.service.log ;version=1.3.0 Import package org.osgi.service.packageadmin ;version=1.2.0 Import package org.osgi.service.startlevel ;version=1.1.0 Import package org.ungoverned.osgi.service.shell ;version=1.0.0 bnd-1.50.0/biz.aQute.bndlib/src/test/lib/deployer/obr/NanoHTTPD.java0000644000175000017500000007210211656076535024632 0ustar drazzibdrazzibpackage test.lib.deployer.obr; import java.io.BufferedReader; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.PrintWriter; import java.net.ServerSocket; import java.net.Socket; import java.net.URLEncoder; import java.util.Date; import java.util.Enumeration; import java.util.Hashtable; import java.util.Locale; import java.util.Properties; import java.util.StringTokenizer; import java.util.TimeZone; import java.util.Vector; /** * A simple, tiny, nicely embeddable HTTP 1.0 server in Java * *

Modified from the original as follows: removed main method; added base directory parameter * for use when serving files.

* *

NanoHTTPD version 1.21, * Copyright © 2001,2005-2011 Jarno Elonen (elonen@iki.fi, http://iki.fi/elonen/) * and Copyright © 2010 Konstantinos Togias (info@ktogias.gr, http://ktogias.gr) * *

Features + limitations:

    * *
  • Only one Java file
  • *
  • Java 1.1 compatible
  • *
  • Released as open source, Modified BSD licence
  • *
  • No fixed config files, logging, authorization etc. (Implement yourself if you need them.)
  • *
  • Supports parameter parsing of GET and POST methods
  • *
  • Supports both dynamic content and file serving
  • *
  • Supports file upload (since version 1.2, 2010)
  • *
  • Never caches anything
  • *
  • Doesn't limit bandwidth, request time or simultaneous connections
  • *
  • Default code serves files and shows all HTTP parameters and headers
  • *
  • File server supports directory listing, index.html and index.htm
  • *
  • File server does the 301 redirection trick for directories without '/'
  • *
  • File server supports simple skipping for files (continue download)
  • *
  • File server uses current directory as a web root
  • *
  • File server serves also very long files without memory overhead
  • *
  • Contains a built-in list of most common mime types
  • *
  • All header names are converted lowercase so they don't vary between browsers/clients
  • * *
* *

Ways to use:

    * *
  • Run as a standalone app, serves files from current directory and shows requests
  • *
  • Subclass serve() and embed to your own program
  • *
  • Call serveFile() from serve() with your own base directory
  • * *
* * See the end of the source file for distribution license * (Modified BSD licence) */ public class NanoHTTPD { // ================================================== // API parts // ================================================== /** * Override this to customize the server.

* * (By default, this delegates to serveFile() and allows directory listing.) * * @param uri Percent-decoded URI without parameters, for example "/index.cgi" * @param method "GET", "POST" etc. * @param parms Parsed, percent decoded parameters from URI and, in case of POST, data. * @param header Header entries, percent decoded * @return HTTP response, see class Response for details */ public Response serve( String uri, String method, Properties header, Properties parms, Properties files ) { System.out.println( method + " '" + uri + "' " ); Enumeration e = header.propertyNames(); while ( e.hasMoreElements()) { String value = (String)e.nextElement(); System.out.println( " HDR: '" + value + "' = '" + header.getProperty( value ) + "'" ); } e = parms.propertyNames(); while ( e.hasMoreElements()) { String value = (String)e.nextElement(); System.out.println( " PRM: '" + value + "' = '" + parms.getProperty( value ) + "'" ); } e = files.propertyNames(); while ( e.hasMoreElements()) { String value = (String)e.nextElement(); System.out.println( " UPLOADED: '" + value + "' = '" + files.getProperty( value ) + "'" ); } return serveFile( uri, header, baseDir, true ); } /** * HTTP response. * Return one of these from serve(). */ public class Response { /** * Default constructor: response = HTTP_OK, data = mime = 'null' */ public Response() { this.status = HTTP_OK; } /** * Basic constructor. */ public Response( String status, String mimeType, InputStream data ) { this.status = status; this.mimeType = mimeType; this.data = data; } /** * Convenience method that makes an InputStream out of * given text. */ public Response( String status, String mimeType, String txt ) { this.status = status; this.mimeType = mimeType; try { this.data = new ByteArrayInputStream( txt.getBytes("UTF-8")); } catch ( java.io.UnsupportedEncodingException uee ) { uee.printStackTrace(); } } /** * Adds given line to the header. */ public void addHeader( String name, String value ) { header.put( name, value ); } /** * HTTP status code after processing, e.g. "200 OK", HTTP_OK */ public String status; /** * MIME type of content, e.g. "text/html" */ public String mimeType; /** * Data of the response, may be null. */ public InputStream data; /** * Headers for the HTTP response. Use addHeader() * to add lines. */ public Properties header = new Properties(); } /** * Some HTTP response status codes */ public static final String HTTP_OK = "200 OK", HTTP_REDIRECT = "301 Moved Permanently", HTTP_FORBIDDEN = "403 Forbidden", HTTP_NOTFOUND = "404 Not Found", HTTP_BADREQUEST = "400 Bad Request", HTTP_INTERNALERROR = "500 Internal Server Error", HTTP_NOTIMPLEMENTED = "501 Not Implemented"; /** * Common mime types for dynamic content */ public static final String MIME_PLAINTEXT = "text/plain", MIME_HTML = "text/html", MIME_DEFAULT_BINARY = "application/octet-stream", MIME_XML = "text/xml"; // ================================================== // Socket & server code // ================================================== /** * Starts a HTTP server to given port.

Directory " + uri + "


"; if ( uri.length() > 1 ) { String u = uri.substring( 0, uri.length()-1 ); int slash = u.lastIndexOf( '/' ); if ( slash >= 0 && slash < u.length()) msg += "..
"; } for ( int i=0; i" + files[i] + ""; // Show file size if ( curFile.isFile()) { long len = curFile.length(); msg += "  ("; if ( len < 1024 ) msg += len + " bytes"; else if ( len < 1024 * 1024 ) msg += len/1024 + "." + (len%1024/10%100) + " KB"; else msg += len/(1024*1024) + "." + len%(1024*1024)/10%100 + " MB"; msg += ")"; } msg += "
"; if ( dir ) msg += ""; } msg += ""; return new Response( HTTP_OK, MIME_HTML, msg ); } else { return new Response( HTTP_FORBIDDEN, MIME_PLAINTEXT, "FORBIDDEN: No directory listing." ); } } try { // Get MIME type from file name extension, if possible String mime = null; int dot = f.getCanonicalPath().lastIndexOf( '.' ); if ( dot >= 0 ) mime = (String)theMimeTypes.get( f.getCanonicalPath().substring( dot + 1 ).toLowerCase()); if ( mime == null ) mime = MIME_DEFAULT_BINARY; // Support (simple) skipping: long startFrom = 0; String range = header.getProperty( "range" ); if ( range != null ) { if ( range.startsWith( "bytes=" )) { range = range.substring( "bytes=".length()); int minus = range.indexOf( '-' ); if ( minus > 0 ) range = range.substring( 0, minus ); try { startFrom = Long.parseLong( range ); } catch ( NumberFormatException nfe ) {} } } FileInputStream fis = new FileInputStream( f ); fis.skip( startFrom ); Response r = new Response( HTTP_OK, mime, fis ); r.addHeader( "Content-length", "" + (f.length() - startFrom)); r.addHeader( "Content-range", "" + startFrom + "-" + (f.length()-1) + "/" + f.length()); return r; } catch( IOException ioe ) { return new Response( HTTP_FORBIDDEN, MIME_PLAINTEXT, "FORBIDDEN: Reading file failed." ); } } /** * Hashtable mapping (String)FILENAME_EXTENSION -> (String)MIME_TYPE */ private static Hashtable theMimeTypes = new Hashtable(); static { StringTokenizer st = new StringTokenizer( "css text/css "+ "js text/javascript "+ "htm text/html "+ "html text/html "+ "txt text/plain "+ "asc text/plain "+ "gif image/gif "+ "jpg image/jpeg "+ "jpeg image/jpeg "+ "png image/png "+ "mp3 audio/mpeg "+ "m3u audio/mpeg-url " + "pdf application/pdf "+ "doc application/msword "+ "ogg application/x-ogg "+ "zip application/octet-stream "+ "exe application/octet-stream "+ "class application/octet-stream " ); while ( st.hasMoreTokens()) theMimeTypes.put( st.nextToken(), st.nextToken()); } /** * GMT date formatter */ private static java.text.SimpleDateFormat gmtFrmt; static { gmtFrmt = new java.text.SimpleDateFormat( "E, d MMM yyyy HH:mm:ss 'GMT'", Locale.US); gmtFrmt.setTimeZone(TimeZone.getTimeZone("GMT")); } /** * The distribution licence */ private static final String LICENCE = "Copyright (C) 2001,2005-2011 by Jarno Elonen \n"+ "and Copyright (C) 2010 by Konstantinos Togias \n"+ "\n"+ "Redistribution and use in source and binary forms, with or without\n"+ "modification, are permitted provided that the following conditions\n"+ "are met:\n"+ "\n"+ "Redistributions of source code must retain the above copyright notice,\n"+ "this list of conditions and the following disclaimer. Redistributions in\n"+ "binary form must reproduce the above copyright notice, this list of\n"+ "conditions and the following disclaimer in the documentation and/or other\n"+ "materials provided with the distribution. The name of the author may not\n"+ "be used to endorse or promote products derived from this software without\n"+ "specific prior written permission. \n"+ " \n"+ "THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR\n"+ "IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n"+ "OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n"+ "IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,\n"+ "INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n"+ "NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n"+ "DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n"+ "THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n"+ "(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n"+ "OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."; } bnd-1.50.0/biz.aQute.bndlib/src/test/lib/deployer/obr/OBRAllTests.java0000644000175000017500000000054111656076535025227 0ustar drazzibdrazzibpackage test.lib.deployer.obr; import junit.framework.Test; import junit.framework.TestSuite; public class OBRAllTests { public static Test suite() { TestSuite suite = new TestSuite(OBRAllTests.class.getName()); //$JUnit-BEGIN$ suite.addTestSuite(OBRTest.class); suite.addTestSuite(OBRParseTest.class); //$JUnit-END$ return suite; } } bnd-1.50.0/biz.aQute.bndlib/src/test/lib/deployer/obr/fullobr.xml0000644000175000017500000011053211656076535024457 0ustar drazzibdrazzib 2005961

Import package javax.crypto Import package javax.crypto.spec Import package javax.xml.datatype Import package javax.xml.namespace Import package javax.xml.parsers Import package org.eclipse.core.resources Import package org.eclipse.core.runtime Import package org.eclipse.core.runtime.content Import package org.eclipse.emf.common.notify Import package org.eclipse.emf.common.util Import package org.eclipse.emf.ecore Import package org.eclipse.emf.ecore.impl Import package org.eclipse.emf.ecore.plugin Import package org.eclipse.emf.ecore.resource Import package org.eclipse.emf.ecore.util Import package org.eclipse.emf.ecore.xml.type.internal Import package org.eclipse.emf.ecore.xml.type.util Import package org.osgi.framework ;version=[1.6.0,2.0.0) Import package org.xml.sax Import package org.xml.sax.helpers 2029922

Import package javax.crypto Import package javax.crypto.spec Import package javax.xml.datatype Import package javax.xml.namespace Import package javax.xml.parsers Import package org.eclipse.core.resources Import package org.eclipse.core.runtime Import package org.eclipse.core.runtime.content Import package org.eclipse.emf.common.notify Import package org.eclipse.emf.common.util Import package org.eclipse.emf.ecore Import package org.eclipse.emf.ecore.impl Import package org.eclipse.emf.ecore.plugin Import package org.eclipse.emf.ecore.resource Import package org.eclipse.emf.ecore.util Import package org.eclipse.emf.ecore.xml.type.internal Import package org.eclipse.emf.ecore.xml.type.util Import package org.osgi.framework ;version=[1.5.0,2.0.0) Import package org.xml.sax Import package org.xml.sax.helpers 357938

Import package javax.xml.namespace Import package javax.xml.parsers Import package org.eclipse.emf.common Import package org.eclipse.emf.common.notify Import package org.eclipse.emf.common.util Import package org.eclipse.emf.ecore Import package org.eclipse.emf.ecore.impl Import package org.eclipse.emf.ecore.resource Import package org.eclipse.emf.ecore.resource.impl Import package org.eclipse.emf.ecore.util Import package org.eclipse.emf.ecore.xml.namespace Import package org.eclipse.emf.ecore.xml.type Import package org.eclipse.emf.ecore.xml.type.internal Import package org.eclipse.emf.ecore.xml.type.util Import package org.w3c.dom Import package org.xml.sax Import package org.xml.sax.ext Import package org.xml.sax.helpers 362154

Import package javax.xml.namespace Import package javax.xml.parsers Import package org.eclipse.emf.common Import package org.eclipse.emf.common.notify Import package org.eclipse.emf.common.util Import package org.eclipse.emf.ecore Import package org.eclipse.emf.ecore.impl Import package org.eclipse.emf.ecore.resource Import package org.eclipse.emf.ecore.resource.impl Import package org.eclipse.emf.ecore.util Import package org.eclipse.emf.ecore.xml.namespace Import package org.eclipse.emf.ecore.xml.type Import package org.eclipse.emf.ecore.xml.type.internal Import package org.eclipse.emf.ecore.xml.type.util Import package org.w3c.dom Import package org.xml.sax Import package org.xml.sax.ext Import package org.xml.sax.helpers A simple OSGi command shell service. 62719 http://www.apache.org/licenses/LICENSE-2.0.txt http://www.apache.org/

Import Service org.osgi.service.startlevel.StartLevel Import Service org.osgi.service.packageadmin.PackageAdmin Import package org.apache.felix.shell ;version=1.0.0 Import package org.osgi.framework ;version=1.4.0 Import package org.osgi.service.log ;version=1.3.0 Import package org.osgi.service.packageadmin ;version=1.2.0 Import package org.osgi.service.startlevel ;version=1.1.0 Import package org.ungoverned.osgi.service.shell ;version=1.0.0 A simple textual user interface for Felix' shell service. 12740 http://www.apache.org/licenses/LICENSE-2.0.txt http://felix.apache.org/site/apache-felix-shell-tui.html

Import Service org.apache.felix.shell.ShellService Import package org.apache.felix.shell ;version=1.0.0 Import package org.osgi.framework ;version=1.3.0

bnd-1.50.0/biz.aQute.bndlib/src/test/lib/deployer/obr/testobr.xml0000644000175000017500000001152011656076535024471 0ustar drazzibdrazzib A simple OSGi command shell service. 62719 http://www.apache.org/licenses/LICENSE-2.0.txt http://www.apache.org/

Import Service org.osgi.service.startlevel.StartLevel Import Service org.osgi.service.packageadmin.PackageAdmin Import package org.apache.felix.shell ;version=1.0.0 Import package org.osgi.framework ;version=1.4.0 Import package org.osgi.service.log ;version=1.3.0 Import package org.osgi.service.packageadmin ;version=1.2.0 Import package org.osgi.service.startlevel ;version=1.1.0 Import package org.ungoverned.osgi.service.shell ;version=1.0.0 A simple textual user interface for Felix' shell service. 12740 http://www.apache.org/licenses/LICENSE-2.0.txt http://felix.apache.org/site/apache-felix-shell-tui.html

Import Service org.apache.felix.shell.ShellService Import package org.apache.felix.shell ;version=1.0.0 Import package org.osgi.framework ;version=1.3.0 bnd-1.50.0/biz.aQute.bndlib/src/test/lib/deployer/obr/referralobr.xml0000644000175000017500000000037211656076535025317 0ustar drazzibdrazzib bnd-1.50.0/biz.aQute.bndlib/src/test/split/0000755000175000017500000000000011656076535020246 5ustar drazzibdrazzibbnd-1.50.0/biz.aQute.bndlib/src/test/split/split-b.bnd0000644000175000017500000000006411656076535022305 0ustar drazzibdrazzibInclude-Resource: test/split/B=B, test/split/C=last bnd-1.50.0/biz.aQute.bndlib/src/test/split/split-a.bnd0000644000175000017500000000006511656076535022305 0ustar drazzibdrazzibInclude-Resource: test/split/A=A, test/split/C=first bnd-1.50.0/biz.aQute.bndlib/src/test/split/first0000644000175000017500000000000511656076535021313 0ustar drazzibdrazzibfirstbnd-1.50.0/biz.aQute.bndlib/src/test/split/A0000644000175000017500000000000011656076535020337 0ustar drazzibdrazzibbnd-1.50.0/biz.aQute.bndlib/src/test/split/last0000644000175000017500000000000411656076535021126 0ustar drazzibdrazziblastbnd-1.50.0/biz.aQute.bndlib/src/test/split/B0000644000175000017500000000000011656076535020340 0ustar drazzibdrazzibbnd-1.50.0/biz.aQute.bndlib/src/test/includeheadertest.prop0000755000175000017500000000004211656076535023510 0ustar drazzibdrazzibprops: a\ b\ c\ d last-props: end bnd-1.50.0/biz.aQute.bndlib/src/test/DiffTest.java0000644000175000017500000000070111656076535021464 0ustar drazzibdrazzibpackage test; import java.io.*; import java.util.*; import junit.framework.*; import aQute.lib.jardiff.*; import aQute.lib.osgi.*; public class DiffTest extends TestCase { public void testSimple() throws Exception { aQute.lib.jardiff.Diff diff = new Diff(); Map map = diff.diff(new Jar(new File("jar/ds.jar")), new Jar(new File("jar/asm.jar")), false); diff.print(System.out, map, 0); } } bnd-1.50.0/biz.aQute.bndlib/src/test/AnalyzerTest.java0000755000175000017500000004556511656076535022425 0ustar drazzibdrazzibpackage test; import java.io.*; import java.util.*; import java.util.jar.*; import aQute.bnd.test.*; import aQute.lib.osgi.*; class T0 { } abstract class T1 extends T0 { } class T2 extends T1 { } class T3 extends T2 { } public class AnalyzerTest extends BndTestCase { /** * Fastest way to create a manifest * @throws Exception */ public void testGenerateManifest() throws Exception { Analyzer analyzer = new Analyzer(); Jar bin = new Jar( new File("jar/osgi.jar")); bin.setManifest(new Manifest()); analyzer.setJar( bin ); analyzer.addClasspath( new File("jar/spring.jar")); analyzer.setProperty("Bundle-SymbolicName","org.osgi.core"); analyzer.setProperty("Export-Package","org.osgi.framework,org.osgi.service.event"); analyzer.setProperty("Bundle-Version","1.0"); analyzer.setProperty("Import-Package","*"); Manifest manifest = analyzer.calcManifest(); manifest.write(System.out); String export = manifest.getMainAttributes().getValue("Export-Package"); assertEquals("org.osgi.framework;version=\"1.3\",org.osgi.service.event;uses:=\"org.osgi.framework\";version=\"1.0.1\"",export); assertEquals("1.0",manifest.getMainAttributes().getValue("Bundle-Version")); assertEquals(analyzer.getErrors().toString(), 0, analyzer.getErrors().size()); assertEquals(analyzer.getWarnings().toString(), 0, analyzer.getWarnings().size()); } /** * * Make sure packages from embedded directories referenced from * * Bundle-Classpath are considered during import/export calculation. */ public void testExportContentsDirectory() throws Exception { Builder b = new Builder(); File embedded = new File("bin/aQute/lib").getCanonicalFile(); assertTrue(embedded.isDirectory()); // sanity check b.setProperty("Bundle-ClassPath", ".,jars/some.jar"); b.setProperty("-includeresource", "jars/some.jar/aQute/lib=" + embedded.getAbsolutePath()); b.setProperty("-exportcontents", "aQute.lib.osgi"); b.build(); assertTrue(b.getExports().toString(), b.getExports().containsKey("aQute.lib.osgi")); System.out.println(b.getErrors()); System.out.println(b.getWarnings()); assertEquals(b.getErrors().toString(), 0, b.getErrors().size()); assertEquals(b.getWarnings().toString(), 1, b.getWarnings().size()); } /** * Uses constraints must be filtered by imports or exports. * * @throws Exception */ public void testUsesFiltering() throws Exception { Builder b = new Builder(); b.addClasspath(new File("jar/osgi.jar")); b.setProperty("Export-Package", "org.osgi.service.event"); Jar jar = b.build(); String exports = jar.getManifest().getMainAttributes().getValue("Export-Package"); System.out.println(exports); assertTrue(exports.contains("uses:=\"org.osgi.framework\"")); System.out.println(b.getErrors()); System.out.println(b.getWarnings()); assertEquals(0, b.getErrors().size()); assertEquals(0, b.getWarnings().size()); b = new Builder(); b.addClasspath(new File("jar/osgi.jar")); b.setProperty("Import-Package", ""); b.setProperty("Export-Package", "org.osgi.service.event"); jar = b.build(); exports = jar.getManifest().getMainAttributes().getValue("Export-Package"); assertFalse(exports.contains("uses:=\"org.osgi.framework\"")); System.out.println(b.getErrors()); System.out.println(b.getWarnings()); assertEquals(1, b.getErrors().size()); assertEquals(0, b.getWarnings().size()); } /** * Test if require works * * @throws Exception */ public void testRequire() throws Exception { Builder b = new Builder(); b.addClasspath(new File("jar/osgi.jar")); b.setProperty("Private-Package", "org.osgi.framework"); b.setProperty("-require-bnd", "10000"); b.build(); System.out.println(b.getErrors()); System.out.println(b.getWarnings()); assertEquals(1, b.getErrors().size()); assertEquals(0, b.getWarnings().size()); } public void testComponentImportReference() throws Exception { Builder b = new Builder(); b.addClasspath(new File("jar/osgi.jar")); b.setProperty("Private-Package", "org.osgi.framework"); b.setProperty("Import-Package", "not.here,*"); b.setProperty("Service-Component", "org.osgi.framework.Bundle;ref=not.here.Reference"); b.build(); System.out.println(b.getErrors()); System.out.println(b.getWarnings()); assertEquals(0, b.getErrors().size()); assertEquals(0, b.getWarnings().size()); } public void testFindClass() throws Exception { Builder a = new Builder(); a.setProperty("Export-Package", "org.osgi.service.io"); a.addClasspath(new File("jar/osgi.jar")); a.build(); System.out.println(a.getErrors()); System.out.println(a.getWarnings()); Collection c = a.getClasses("", "IMPORTS", "javax.microedition.io"); System.out.println(c); } public void testMultilevelInheritance() throws Exception { Analyzer a = new Analyzer(); a.setJar(new File("bin")); a.analyze(); String result = a._classes("cmd", "named", "*T?", "extends", "test.T0", "concrete"); System.out.println(result); assertTrue(result.contains("test.T2")); assertTrue(result.contains("test.T3")); } public void testClassQuery() throws Exception { Analyzer a = new Analyzer(); a.setJar(new File("jar/osgi.jar")); a.analyze(); String result = a._classes("cmd", "named", "org.osgi.service.http.*", "abstract"); TreeSet r = new TreeSet(Processor.split(result)); assertEquals( new TreeSet(Arrays.asList("org.osgi.service.http.HttpContext", "org.osgi.service.http.HttpService")), r); } /** * Use a private activator, check it is not imported. * * @throws Exception */ public void testEmptyHeader() throws Exception { Builder a = new Builder(); a.setProperty("Bundle-Blueprint", " <> "); a.setProperty("Export-Package", "org.osgi.framework"); a.addClasspath(new File("jar/osgi.jar")); a.build(); Manifest manifest = a.getJar().getManifest(); System.out.println(a.getErrors()); System.out.println(a.getWarnings()); assertEquals(0, a.getErrors().size()); assertEquals(0, a.getWarnings().size()); String bb = manifest.getMainAttributes().getValue("Bundle-Blueprint"); System.out.println(bb); assertNotNull(bb); assertEquals("", bb); } /** * Test name section. */ public void testNameSection() throws Exception { Builder a = new Builder(); a.setProperty("Export-Package", "org.osgi.service.event, org.osgi.service.io"); a.addClasspath(new File("jar/osgi.jar")); a.setProperty("@org@osgi@service@event@Specification-Title", "spec title"); a.setProperty("@org@osgi@service@io@Specification-Title", "spec title io"); a.setProperty("@org@osgi@service@event@Specification-Version", "1.1"); a.setProperty("@org@osgi@service@event@Implementation-Version", "5.1"); Jar jar = a.build(); Manifest m = jar.getManifest(); Attributes attrs = m.getAttributes("org/osgi/service/event"); assertNotNull(attrs); assertEquals("5.1", attrs.getValue("Implementation-Version")); assertEquals("1.1", attrs.getValue("Specification-Version")); assertEquals("spec title", attrs.getValue("Specification-Title")); attrs = m.getAttributes("org/osgi/service/io"); assertNotNull(attrs); assertEquals("spec title io", attrs.getValue("Specification-Title")); } /** * Check if calcManifest sets the version */ /** * Test if mandatory attributes are augmented even when the version is not * set. */ public void testMandatoryWithoutVersion() throws Exception { Builder a = new Builder(); Properties p = new Properties(); p.put("Import-Package", "*"); p.put("Private-Package", "org.apache.mina.management.*"); a.setClasspath(new Jar[] { new Jar(new File("jar/mandatorynoversion.jar")) }); a.setProperties(p); Jar jar = a.build(); String imports = jar.getManifest().getMainAttributes().getValue("Import-Package"); System.out.println(imports); assertTrue(imports.indexOf("x=1") >= 0); assertTrue(imports.indexOf("y=2") >= 0); } /** * Use a private activator, check it is not imported. * * @throws Exception */ public void testPrivataBundleActivatorNotImported() throws Exception { Builder a = new Builder(); Properties p = new Properties(); p.put("Import-Package", "*"); p.put("Private-Package", "org.objectweb.*"); p.put("Bundle-Activator", "org.objectweb.asm.Item"); a.setClasspath(new Jar[] { new Jar(new File("jar/asm.jar")) }); a.setProperties(p); a.build(); Manifest manifest = a.getJar().getManifest(); System.out.println(a.getErrors()); System.out.println(a.getWarnings()); assertEquals(0, a.getErrors().size()); assertEquals(0, a.getWarnings().size()); String imports = manifest.getMainAttributes().getValue("Import-Package"); System.out.println(imports); assertNull(imports); } /** * Use an activator that is not in the bundle but do not allow it to be * imported, this should generate an error. * * @throws Exception */ public void testBundleActivatorNotImported() throws Exception { Builder a = new Builder(); Properties p = new Properties(); p.put("Import-Package", "!org.osgi.framework,*"); p.put("Private-Package", "org.objectweb.*"); p.put("Bundle-Activator", "org.osgi.framework.BundleActivator"); a.setClasspath(new Jar[] { new Jar(new File("jar/asm.jar")), new Jar(new File("jar/osgi.jar")) }); a.setProperties(p); a.build(); Manifest manifest = a.getJar().getManifest(); System.out.println(a.getErrors()); System.out.println(a.getWarnings()); assertEquals(1, a.getErrors().size()); assertTrue(a.getErrors().get(0).indexOf("Bundle-Activator not found") >= 0); // assertTrue(a.getErrors().get(1).indexOf("Unresolved references to") // >= 0); assertEquals(0, a.getWarnings().size()); String imports = manifest.getMainAttributes().getValue("Import-Package"); assertNull(imports); } /** * Use an activator that is on the class path but that is not in the bundle. * * @throws Exception */ public void testBundleActivatorImport() throws Exception { Builder a = new Builder(); Properties p = new Properties(); p.put("Private-Package", "org.objectweb.*"); p.put("Bundle-Activator", "org.osgi.framework.BundleActivator"); a.setClasspath(new Jar[] { new Jar(new File("jar/asm.jar")), new Jar(new File("jar/osgi.jar")) }); a.setProperties(p); a.build(); Manifest manifest = a.getJar().getManifest(); System.out.println(a.getErrors()); System.out.println(a.getWarnings()); assertEquals(0, a.getErrors().size()); assertEquals(0, a.getWarnings().size()); String imports = manifest.getMainAttributes().getValue("Import-Package"); assertNotNull(imports); assertTrue(imports.indexOf("org.osgi.framework") >= 0); } /** * The -removeheaders header removes any necessary after the manifest is * calculated. */ public void testRemoveheaders() throws Exception { Analyzer a = new Analyzer(); a.setJar(new File("jar/asm.jar")); Manifest m = a.calcManifest(); assertNotNull(m.getMainAttributes().getValue("Implementation-Title")); a = new Analyzer(); a.setJar(new File("jar/asm.jar")); a.setProperty("-removeheaders", "Implementation-Title"); m = a.calcManifest(); assertNull(m.getMainAttributes().getValue("Implementation-Title")); } /** * There was an export generated for a jar file. * * @throws Exception */ public void testExportForJar() throws Exception { Jar jar = new Jar("dot"); jar.putResource("target/aopalliance.jar", new FileResource(new File("jar/asm.jar"))); Analyzer an = new Analyzer(); an.setJar(jar); Properties p = new Properties(); p.put("Export-Package", "*"); an.setProperties(p); Manifest manifest = an.calcManifest(); String exports = manifest.getMainAttributes().getValue(Analyzer.EXPORT_PACKAGE); Map> map = Analyzer.parseHeader(exports, null); assertEquals(1, map.size()); assertEquals("target", map.keySet().iterator().next()); } /** * Test if version works */ public void testVersion() { Analyzer a = new Analyzer(); String v = a.getBndVersion(); assertNotNull(v); } /** * asm is a simple library with two packages. No imports are done. * */ public void testAsm() throws Exception { Properties base = new Properties(); base.put(Analyzer.IMPORT_PACKAGE, "*"); base.put(Analyzer.EXPORT_PACKAGE, "*;-noimport:=true"); Analyzer analyzer = new Analyzer(); analyzer.setJar(new File("jar/asm.jar")); analyzer.setProperties(base); analyzer.calcManifest().write(System.out); assertTrue(analyzer.getExports().containsKey("org.objectweb.asm.signature")); assertTrue(analyzer.getExports().containsKey("org.objectweb.asm")); assertFalse(analyzer.getImports().containsKey("org.objectweb.asm.signature")); assertFalse(analyzer.getImports().containsKey("org.objectweb.asm")); assertEquals("Expected size", 2, analyzer.getExports().size()); } /** * See if we set attributes on export * * @throws IOException */ public void testAsm2() throws Exception { Properties base = new Properties(); base.put(Analyzer.IMPORT_PACKAGE, "*"); base.put(Analyzer.EXPORT_PACKAGE, "org.objectweb.asm;name=short, org.objectweb.asm.signature;name=long"); Analyzer h = new Analyzer(); h.setJar(new File("jar/asm.jar")); h.setProperties(base); h.calcManifest().write(System.out); assertPresent(h.getExports(), "org.objectweb.asm.signature, org.objectweb.asm"); assertTrue(Arrays.asList("org.objectweb.asm", "org.objectweb.asm.signature").removeAll( h.getImports().keySet()) == false); assertEquals("Expected size", 2, h.getExports().size()); assertEquals("short", get(h.getExports(), "org.objectweb.asm", "name")); assertEquals("long", get(h.getExports(), "org.objectweb.asm.signature", "name")); } public void testDs() throws Exception { Properties base = new Properties(); base.put(Analyzer.IMPORT_PACKAGE, "*"); base.put(Analyzer.EXPORT_PACKAGE, "*;-noimport:=true"); File tmp = new File("jar/ds.jar"); Analyzer analyzer = new Analyzer(); analyzer.setJar(tmp); analyzer.setProperties(base); System.out.println(analyzer.calcManifest()); assertPresent(analyzer.getImports(), "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"); assertPresent(analyzer.getExports(), "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"); } public void testDsSkipOsgiImport() throws Exception { Properties base = new Properties(); base.put(Analyzer.IMPORT_PACKAGE, "!org.osgi.*, *"); base.put(Analyzer.EXPORT_PACKAGE, "*;-noimport:=true"); File tmp = new File("jar/ds.jar"); Analyzer h = new Analyzer(); h.setJar(tmp); h.setProperties(base); h.calcManifest().write(System.out); assertPresent(h.getImports(), "org.xml.sax, " + " javax.xml.parsers," + " org.xml.sax.helpers," + " org.eclipse.osgi.util"); System.out.println("IMports " + h.getImports()); assertNotPresent(h.getImports(), "org.osgi.service.packageadmin, " + "org.osgi.service.log," + " org.osgi.framework," + " org.osgi.util.tracker, " + "org.osgi.service.component, " + "org.osgi.service.cm"); assertPresent(h.getExports(), "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"); } public void testDsNoExport() throws Exception { Properties base = new Properties(); base.put(Analyzer.IMPORT_PACKAGE, "*"); base.put(Analyzer.EXPORT_PACKAGE, "!*"); File tmp = new File("jar/ds.jar"); Analyzer h = new Analyzer(); h.setJar(tmp); h.setProperties(base); h.calcManifest().write(System.out); assertPresent(h.getImports(), "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(), "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.out.println(h.getUnreachable()); } public void testClasspath() throws Exception { Properties base = new Properties(); base.put(Analyzer.IMPORT_PACKAGE, "*"); base.put(Analyzer.EXPORT_PACKAGE, "*;-noimport:=true"); File tmp = new File("jar/ds.jar"); File osgi = new File("jar/osgi.jar"); Analyzer h = new Analyzer(); h.setJar(tmp); h.setProperties(base); h.setClasspath(new File[] { osgi }); h.calcManifest().write(System.out); assertEquals("Version from osgi.jar", "[1.2,2)", get(h.getImports(), "org.osgi.service.packageadmin", "version")); assertEquals("Version from osgi.jar", "[1.3,2)", get(h.getImports(), "org.osgi.util.tracker", "version")); assertEquals("Version from osgi.jar", null, get(h.getImports(), "org.xml.sax", "version")); } /** * We detect that there are instruction on im/export package headers that * are never used. This usually indicates a misunderstanding or a change in * the underlying classpath. These are reflected as warnings. If there is an * extra import, and it contains no wildcards, then it is treated as a * wildcard * * @throws IOException */ public void testSuperfluous() throws Exception { Properties base = new Properties(); base.put(Analyzer.IMPORT_PACKAGE, "*, com.foo, com.foo.bar.*"); base.put(Analyzer.EXPORT_PACKAGE, "*, com.bar"); File tmp = new File("jar/ds.jar"); Analyzer h = new Analyzer(); h.setJar(tmp); h.setProperties(base); h.calcManifest().write(System.out); List warnings = h.getWarnings(); assertEquals(warnings.size(), 2); assertEquals("Superfluous export-package instructions: [com.bar]", warnings.get(0)); assertEquals("Did not find matching referal for com.foo.bar.*", warnings.get(1)); assertTrue(h.getImports().containsKey("com.foo")); } void assertNotPresent(Map map, String string) { StringTokenizer st = new StringTokenizer(string, ", "); while (st.hasMoreTokens()) { String packageName = st.nextToken(); assertFalse("Must not contain package " + packageName, map.containsKey(packageName)); } } void assertPresent(Map map, String string) { StringTokenizer st = new StringTokenizer(string, ", "); while (st.hasMoreTokens()) { String packageName = st.nextToken(); assertTrue("Must contain package " + packageName, map.containsKey(packageName)); } } String get(Map> headers, String packageName, String attr) { Map clauses = headers.get(packageName); if (clauses == null) return null; return (String) clauses.get(attr); } } bnd-1.50.0/biz.aQute.bndlib/src/test/JarSignerTest.java0000644000175000017500000000643111656076535022506 0ustar drazzibdrazzibpackage test; import java.io.*; import java.util.*; import java.util.jar.*; import junit.framework.*; import aQute.bnd.signing.*; import aQute.lib.osgi.*; import aQute.libg.generics.*; public class JarSignerTest extends TestCase { public void testNoManifest() throws Exception { Builder b = new Builder(); b.setProperty("-sign", "test"); b.setProperty(Constants.PLUGIN,JartoolSigner.class.getName()+";keystore=test/keystore;keypass=testtest;storepass=testtest;sigfile=test"); b.setProperty("-nomanifest","true"); b.setProperty("-resourceonly","true"); b.setProperty("Include-Resource", "WEB-INF/classes=@jar/osgi.jar"); Jar jar = b.build(); File tmp = new File("xyztmp.jar"); tmp.deleteOnExit(); jar.write( tmp ); Jar jar2 = new Jar(tmp); Manifest manifest = jar2.getManifest(); assertEquals( "1.0", manifest.getMainAttributes().getValue("Manifest-Version")); assertNotNull( manifest.getAttributes("WEB-INF/classes/org/osgi/framework/BundleContext.class")); } public void testError() throws Exception { JartoolSigner signer = new JartoolSigner(); Map properties = Create.map(); properties.put("keystore", "test/keystore"); properties.put("keypass", "testtest"); properties.put("storepass", "notvalid"); signer.setProperties(properties); Jar jar = new Jar( new File("test/test.jar")); Builder b = new Builder(); b.setTrace(true); b.setJar(jar); signer.sign(b, "test"); System.out.println( Processor.join(b.getErrors(),"\n")); assertEquals( 1, b.getErrors().size() ); assertEquals( 0, b.getWarnings().size() ); } public void testSimple() throws Exception { JartoolSigner signer = new JartoolSigner(); Map properties = Create.map(); properties.put("keystore", "test/keystore"); properties.put("keypass", "testtest"); properties.put("storepass", "testtest"); properties.put("sigfile", "test"); signer.setProperties(properties); Jar jar = new Jar( new File("test/test.jar")); Set names = new HashSet(jar.getResources().keySet()); names.remove("META-INF/MANIFEST.MF"); Builder b = new Builder(); b.setJar(jar); signer.sign(b, "test"); System.out.println( Processor.join(b.getErrors(), "\n")); System.out.println( Processor.join(b.getWarnings(), "\n")); assertEquals( 0, b.getErrors().size() ); assertEquals( 0, b.getWarnings().size() ); assertNotNull( jar.getResource("META-INF/TEST.SF") ); Manifest m = jar.getManifest(); // Should have added 2 new resources: TEST.SF and TEST.DSA/RSA assertEquals( names.size(), b.getJar().getResources().size()-3); Attributes a = m.getAttributes("aQute/rendezvous/DNS.class"); assertNotNull(a); assertEquals("G0/1CIZlB4eIVyY8tU/ZfMCqZm4=", a.getValue("SHA1-Digest")); // Check if all resources are named for ( String name : names ) { System.out.println("name: " + name); assertNotNull( m.getAttributes(name)); } } } bnd-1.50.0/biz.aQute.bndlib/src/test/bnd.info0000644000175000017500000000010611656076535020530 0ustar drazzibdrazzib# See BuilderTest.testBndInfo p=${p} a=${a} b=${b} now=${now} d=fixed bnd-1.50.0/biz.aQute.bndlib/src/test/spring-test1.spring0000644000175000017500000000516111656076535022702 0ustar drazzibdrazzib Simple implementation that uses fortunes supplied to it as a straight Set. A more realistic implementation would of course load the fortunes from file, a database, query a fortune web service, etc. bnd-1.50.0/biz.aQute.bndlib/src/test/.classpath0000644000175000017500000000104311656076535021074 0ustar drazzibdrazzib bnd-1.50.0/biz.aQute.bndlib/src/test/includeheadertest.mf0000755000175000017500000000012511656076535023134 0ustar drazzibdrazzibManifest-Version: 1 manifest: a b c d last-manifest: end -include: iht/test.prop bnd-1.50.0/biz.aQute.bndlib/src/test/RepoBuilderTest.java0000644000175000017500000000453111656076535023035 0ustar drazzibdrazzibpackage test; import junit.framework.*; public class RepoBuilderTest extends TestCase { public void testA() {} // public void testSimple() { // assertBundles("osgi", RepoBuilder.STRATEGY_LOWEST, new String[]{"osgi-3.0.0.jar"}); // assertBundles("osgi", RepoBuilder.STRATEGY_HIGHEST, new String[]{"osgi-4.2.0.jar"}); // assertBundles("osgi;version=4.1", RepoBuilder.STRATEGY_HIGHEST, new String[]{"osgi-4.2.0.jar"}); // assertBundles("osgi;version=4.1", RepoBuilder.STRATEGY_LOWEST, new String[]{"osgi-4.1.0.jar"}); // assertBundles("osgi;version=4.1.1", RepoBuilder.STRATEGY_LOWEST, new String[]{"osgi-4.2.0.jar"}); // assertBundles("osgi;version=\"(4.1,5)\"", RepoBuilder.STRATEGY_LOWEST, new String[]{"osgi-4.2.0.jar"}); // assertBundles("osgi;version=\"[4.1,5)\"", RepoBuilder.STRATEGY_LOWEST, new String[]{"osgi-4.1.0.jar"}); // assertBundles("osgi;version=\"[4.1,5)\"", RepoBuilder.STRATEGY_HIGHEST, new String[]{"osgi-4.2.0.jar"}); // assertBundles("osgi;version=\"[3,4)\"", RepoBuilder.STRATEGY_HIGHEST, new String[]{"osgi-3.0.0.jar"}); // //assertBundles("osgi,org.osgi.impl.service.log,org.osgi.impl.service.cm", RepoBuilder.STRATEGY_LOWEST, new String[]{"osgi-3.0.0.jar", "org.osgi.impl.service.cm-2.1.1.jar"}); // } // // // void assertBundles(String bundles, int strategy, String endsWith[]) { // RepoBuilder r = new RepoBuilder(); // Properties p = new Properties(); // p.setProperty("-plugin", "aQute.lib.deployer.FileRepo;location=src/test/repo"); // p.setProperty("-bundles", bundles ); // r.setProperties(p); // List b = r.getBundles(strategy, r.getProperty("-bundles")); // List l = new ArrayList(); // for ( Container c : b ) // l.add(c.getFile()); // check(r); // assertEquals( endsWith.length, b.size()); // for ( int i =0; i map = ComponentAnnotationReader.getDefinition(c); System.out.println(map); assertEquals("mycomp", map.get("name:")); assertEquals( "true", map.get("servicefactory:")); assertEquals("activatex", map.get("activate:")); assertEquals("deactivatex", map.get("deactivate:")); assertEquals("modifiedx", map.get("modified:")); assertEquals("org.osgi.service.log.LogService(abc=3)~", map.get("log/setLog")); assertEquals("org.osgi.service.packageadmin.PackageAdmin", map.get("packageAdmin/setPackageAdmin")); } public void testSimple() throws Exception { Clazz clazz = new Clazz("", null); ClassDataCollector cd = new ClassDataCollector() { public void addReference(String token) { } public void annotation(Annotation annotation) { System.out.println("Annotation " + annotation); } public void classBegin(int access, String name) { System.out.println("Class " + name); } public void classEnd() { System.out.println("Class end "); } public void extendsClass(String name) { System.out.println("extends " + name); } public void implementsInterfaces(String[] name) { System.out.println("implements " + Arrays.toString(name)); } public void constructor(int access, String descriptor) { System.out.println("constructor " + descriptor); } public void method(int access, String name, String descriptor) { System.out.println("method " + name + descriptor); } public void parameter(int p) { System.out.println("parameter " + p); } }; clazz.parseClassFile(getClass().getResourceAsStream("Target.class"), cd); } } @Component class Target implements Serializable { private static final long serialVersionUID = 1L; @Activate void activate() { } @Deactivate void deactivate() { } @Modified void modified() { } @Reference void setLog(LogService log) { } void unsetLog(LogService log) { } } bnd-1.50.0/biz.aQute.bndlib/src/test/activator/0000755000175000017500000000000011656076535021107 5ustar drazzibdrazzibbnd-1.50.0/biz.aQute.bndlib/src/test/activator/Activator.java0000755000175000017500000000035711656076535023716 0ustar drazzibdrazzibpackage test.activator; import org.osgi.framework.*; public class Activator implements BundleActivator { public void start(BundleContext context) throws Exception { } public void stop(BundleContext context) throws Exception { } } bnd-1.50.0/biz.aQute.bndlib/src/test/activator/inherits/0000755000175000017500000000000011656076535022734 5ustar drazzibdrazzibbnd-1.50.0/biz.aQute.bndlib/src/test/activator/inherits/InheritedActivator.java0000644000175000017500000000037611656076535027375 0ustar drazzibdrazzibpackage test.activator.inherits; import org.osgi.framework.*; import test.activator.*; import aQute.bnd.annotation.component.*; @Component(name="inheritedactivator",provide=BundleActivator.class) public class InheritedActivator extends Activator { } bnd-1.50.0/biz.aQute.bndlib/src/test/PluginTest.java0000644000175000017500000000343711656076535022063 0ustar drazzibdrazzibpackage test; import java.applet.*; import java.util.*; import junit.framework.*; import aQute.bnd.service.*; import aQute.lib.osgi.*; import aQute.libg.reporter.*; public class PluginTest extends TestCase { static Processor main = new Processor(); public void testMissingPluginNotUsed() throws Exception { Builder p = new Builder(); p.setProperty("-plugin", "missing;command:=\"-abc,-def\""); /*List plugins =*/ p.getPlugins(Object.class); assertEquals(0, p.getErrors().size()); p.setProperty("-abc", "whatever"); p.setProperty("-resourceonly", "true"); p.setProperty("Include-Resource", "jar/osgi.jar"); p.build(); assertEquals(1, p.getErrors().size()); assertTrue(p.getErrors().get(0).contains("Missing plugin")); } static class TPlugin implements Plugin { Map properties; public void setProperties(Map map) { properties = map; } public void setReporter(Reporter processor) { assertEquals(main, processor ); } } public void testPlugin() { main.setProperty(Constants.PLUGIN, "test.PluginTest.TPlugin;a=1;b=2"); for ( TPlugin plugin : main.getPlugins(TPlugin.class)) { assertEquals( test.PluginTest.TPlugin.class, plugin.getClass()); assertEquals( "1", plugin.properties.get("a")); assertEquals( "2", plugin.properties.get("b")); } } public void testLoadPlugin() { main.setProperty(Constants.PLUGIN, "thinlet.Thinlet;path:=jar/thinlet.jar"); for ( Applet applet : main.getPlugins(Applet.class)) { assertEquals( "thinlet.Thinlet", applet.getClass().getName()); } } } bnd-1.50.0/biz.aQute.bndlib/src/test/VersionPolicyTest.java0000644000175000017500000002403011656076535023422 0ustar drazzibdrazzibpackage test; import java.io.*; import java.util.*; import java.util.jar.*; import junit.framework.*; import aQute.lib.osgi.*; public class VersionPolicyTest extends TestCase { /** * Test disable default package versions. */ public void testDisableDefaultPackageVersion() throws Exception { Builder a = new Builder(); a.addClasspath(new File("bin")); a.setProperty("Bundle-Version", "1.2.3"); a.setProperty("Export-Package", "test.refer"); a.setProperty("-nodefaultversion", "true"); Jar jar = a.build(); Manifest m = jar.getManifest(); Map> exports = Processor.parseHeader(m.getMainAttributes().getValue(Constants.EXPORT_PACKAGE), null); Map attrs = exports.get("test.refer"); assertNotNull(attrs); assertNull( attrs.get("version")); } /** * Test default package versions. */ public void testDefaultPackageVersion() throws Exception { Builder a = new Builder(); a.addClasspath(new File("bin")); a.setProperty("Bundle-Version", "1.2.3"); a.setProperty("Export-Package", "test.refer"); Jar jar = a.build(); Manifest m = jar.getManifest(); Map> exports = Processor.parseHeader(m.getMainAttributes().getValue(Constants.EXPORT_PACKAGE), null); Map attrs = exports.get("test.refer"); assertNotNull(attrs); assertEquals( "1.2.3", attrs.get("version")); } /** * Test import provide:. */ public void testImportProvided() throws Exception { Builder a = new Builder(); a.addClasspath(new File("jar/osgi.jar")); a.addClasspath(new File("bin")); a.setProperty("Private-Package", "test.refer"); a.setProperty("Import-Package", "org.osgi.service.event;provide:=true,*"); Jar jar = a.build(); Map event = a.getImports().get("org.osgi.service.event"); assertEquals("[1.0,1.1)", event.get("version")); Map http = a.getImports().get("org.osgi.service.http"); assertEquals("[1.2,2)", http.get("version")); Manifest m = jar.getManifest(); String imports = m.getMainAttributes().getValue(Constants.IMPORT_PACKAGE); assertFalse( imports.contains(Constants.PROVIDE_DIRECTIVE)); } /** * Test import provide:. */ public void testExportProvided() throws Exception { Builder a = new Builder(); a.addClasspath(new File("jar/osgi.jar")); a.addClasspath(new File("bin")); a.setProperty("Private-Package", "test.refer"); a.setProperty("Export-Package", "org.osgi.service.http;provide:=true"); Jar jar = a.build(); Map event = a.getImports().get("org.osgi.service.event"); assertEquals("[1.0,2)", event.get("version")); Map http = a.getImports().get("org.osgi.service.http"); assertEquals("[1.2,1.3)", http.get("version")); Manifest m = jar.getManifest(); String imports = m.getMainAttributes().getValue(Constants.IMPORT_PACKAGE); assertFalse( imports.contains(Constants.PROVIDE_DIRECTIVE)); } /** * Test export annotation. */ public void testExportAnnotation() throws Exception { Builder a = new Builder(); a.addClasspath(new File("bin")); a.setProperty("build", "xyz"); a.setProperty("Export-Package", "test.versionpolicy.api"); a.build(); Map attrs = a.getExports().get("test.versionpolicy.api"); assertEquals("1.2.0.xyz", attrs.get("version")); assertEquals("PrivateImpl", attrs.get("exclude:")); assertEquals("a", attrs.get("mandatory:")); } /** * Check implementation version policy. * * Uses the package test.versionpolicy.(uses|implemented) * * TODO currently commented out because it is too restrictive unless * supported by package */ public void testImplementationVersionPolicies() throws Exception { // assertPolicy("test.versionpolicy.implemented", "IMPL"); // assertPolicy("test.versionpolicy.implmajor", "USES"); // assertPolicy("test.versionpolicy.uses", "USES"); } void assertPolicy(String pack, String type) throws Exception { Builder a = new Builder(); a.addClasspath(new File("bin")); a.setProperty("Export-Package", "test.versionpolicy.api"); Jar jar = a.build(); Builder b = new Builder(); b.addClasspath(jar); b.addClasspath(new File("bin")); b.setProperty("-versionpolicy-impl", "IMPL"); b.setProperty("-versionpolicy-uses", "USES"); b.setProperty("Private-Package", pack); b.build(); Manifest m = b.getJar().getManifest(); m.write(System.out); Map map = b.getImports().get("test.versionpolicy.api"); assertNotNull(map); // String s = map.get(Constants.IMPLEMENTED_DIRECTIVE); // assertEquals("true", s); Map> mp = Processor.parseHeader(m .getMainAttributes().getValue("Import-Package"), null); assertEquals(type, mp.get("test.versionpolicy.api").get("version")); } /** * hardcoded imports */ public void testHardcodedImports() throws Exception { Builder b = new Builder(); b.addClasspath(new File("jar/osgi.jar")); b.setProperty("-versionpolicy", "${range;[==,+)}"); b.setProperty("Private-Package", "org.objectweb.asm"); b.setProperty("Import-Package", "org.osgi.framework,org.objectweb.asm,abc;version=2.0.0,*"); b.build(); Manifest m = b.getJar().getManifest(); m.write(System.out); String s = b.getImports().get("org.objectweb.asm").get("version"); assertNull(s); s = b.getImports().get("abc").get("version"); assertEquals("2.0.0", s); s = b.getImports().get("org.osgi.framework").get("version"); assertEquals("[1.3,2)", s); } /** * Specify the version on the export and verify that the policy is applied * on the matching import. */ public void testExportsSpecifiesVersion() throws Exception { Builder b = new Builder(); b.addClasspath(new File("jar/osgi.jar")); b.addClasspath(new File("bin")); b.setProperty("Export-Package", "org.osgi.service.event"); b.setProperty("Private-Package", "test.refer"); b.build(); String s = b.getImports().get("org.osgi.service.event").get("version"); assertEquals("[1.0,2)", s); } /** * See if we a can override the version from the export statement and the * version from the source. */ public void testImportOverridesDiscoveredVersion() throws Exception { Builder b = new Builder(); b.addClasspath(new File("jar/osgi.jar")); b.addClasspath(new File("bin")); b.setProperty("Export-Package", "org.osgi.service.event"); b.setProperty("Private-Package", "test.refer"); b.setProperty("Import-Package", "org.osgi.service.event;version=2.1.3.q"); b.build(); String s = b.getImports().get("org.osgi.service.event").get("version"); assertEquals("2.1.3.q", s); } /** * Test if we can get the version from the source and apply the default * policy. */ public void testVersionPolicyImportedExportsDefaultPolicy() throws Exception { Builder b = new Builder(); b.addClasspath(new File("jar/osgi.jar")); b.addClasspath(new File("bin")); b.setProperty("Export-Package", "org.osgi.service.event"); b.setProperty("Private-Package", "test.refer"); b.build(); String s = b.getImports().get("org.osgi.service.event").get("version"); assertEquals("[1.0,2)", s); } /** * Test if we can get the version from the source and apply a specific * policy. */ public void testVersionPolicyImportedExportsWithPolicy() throws Exception { Builder b = new Builder(); b.addClasspath(new File("jar/osgi.jar")); b.addClasspath(new File("bin")); b.setProperty("-versionpolicy", "${range;[==,=+)}"); b.setProperty("Export-Package", "org.osgi.service.event"); b.setProperty("Private-Package", "test.refer"); b.build(); String s = b.getImports().get("org.osgi.service.event").get("version"); assertEquals("[1.0,1.1)", s); } /** * The default policy is truncate micro. Check if this is applied to the * import. */ public void testImportMicroTruncated() throws Exception { Builder b = new Builder(); b.addClasspath(new File("jar/osgi.jar")); b.setProperty("Import-Package", "org.osgi.service.event"); b.build(); String s = b.getImports().get("org.osgi.service.event").get("version"); assertEquals("[1.0,2)", s); } /** * See if we can apply a policy to an import where we get the version from * the source. */ public void testVersionPolicy() throws Exception { Builder b = new Builder(); b.addClasspath(new File("jar/osgi.jar")); b.setProperty("-versionpolicy", "${range;[==,=+)}"); b.setProperty("Import-Package", "org.osgi.service.event"); b.build(); String s = b.getImports().get("org.osgi.service.event").get("version"); assertEquals("[1.0,1.1)", s); } /** * Check if we can set a specific version on the import that does not use a * version policy. */ public void testImportMicroNotTruncated() throws Exception { Builder b = new Builder(); b.addClasspath(new File("jar/osgi.jar")); b.setProperty("Import-Package", "org.osgi.service.event;version=${@}"); b.build(); String s = b.getImports().get("org.osgi.service.event").get("version"); assertEquals("1.0.1", s); } } bnd-1.50.0/biz.aQute.bndlib/src/test/ComponentTest.java0000755000175000017500000011237511656076535022574 0ustar drazzibdrazzibpackage test; import java.io.*; import java.util.*; import java.util.jar.*; import javax.xml.namespace.*; import javax.xml.parsers.*; import javax.xml.xpath.*; import junit.framework.*; import org.osgi.framework.*; import org.osgi.service.component.*; import org.osgi.service.event.*; import org.osgi.service.log.*; import org.w3c.dom.*; import org.xml.sax.*; import aQute.bnd.annotation.component.*; import aQute.bnd.annotation.metatype.*; import aQute.lib.io.*; import aQute.lib.osgi.*; import aQute.lib.osgi.Constants; public class ComponentTest extends TestCase { final DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); final XPathFactory xpathf = XPathFactory.newInstance(); final XPath xpath = xpathf.newXPath(); DocumentBuilder db; { try { dbf.setNamespaceAware(true); db = dbf.newDocumentBuilder(); xpath.setNamespaceContext(new NamespaceContext() { public Iterator getPrefixes(String namespaceURI) { return Arrays.asList("md", "scr").iterator(); } public String getPrefix(String namespaceURI) { if (namespaceURI.equals("http://www.osgi.org/xmlns/metatype/v1.1.0")) return "md"; if (namespaceURI.equals("http://www.osgi.org/xmlns/scr/v1.1.0")) return "scr"; return null; } public String getNamespaceURI(String prefix) { if (prefix.equals("md")) return "http://www.osgi.org/xmlns/metatype/v1.1.0"; else if (prefix.equals("scr")) return "http://www.osgi.org/xmlns/scr/v1.1.0"; else return null; } }); } catch (ParserConfigurationException e) { // TODO Auto-generated catch block e.printStackTrace(); } } /** * Can we order the references? References are ordered by their name as Java does not * define the order of the methods. * * @throws Exception */ @Component static class TestReferenceOrdering { @Reference(service=LogService.class) void setA(ServiceReference ref) {} @Reference void setC(LogService log) {} @Reference(service=LogService.class) void setB(Map map) {} } public void testReferenceOrdering () throws Exception { Builder b = new Builder(); b.addClasspath( new File( "bin")); b.setProperty("Service-Component", "*TestReferenceOrdering"); b.setProperty("Private-Package", "test"); Jar jar = b.build(); Document doc = doc(b, "test.ComponentTest$TestReferenceOrdering"); NodeList nodes = (NodeList) xpath.evaluate("//reference", doc, XPathConstants.NODESET); assertEquals("a", nodes.item(0).getAttributes().getNamedItem("name").getTextContent()); assertEquals("b", nodes.item(1).getAttributes().getNamedItem("name").getTextContent()); assertEquals("c", nodes.item(2).getAttributes().getNamedItem("name").getTextContent()); } /** * Test to see if we ignore scala.ScalaObject as interface * @throws Exception */ public void testScalaObject () throws Exception { Builder b = new Builder(); b.addClasspath( new File( "jar/com.test.scala.jar")); b.setProperty("Service-Component", "*"); b.setProperty("Export-Package", "com.test.scala.*"); Jar jar = b.build(); Manifest m = jar.getManifest(); System.out.println(Processor.join(b.getErrors())); System.out.println(Processor.join(b.getWarnings())); System.out.println(m.getMainAttributes().getValue("Service-Component")); IO.copy(jar.getResource("OSGI-INF/com.test.scala.Service.xml").openInputStream(), System.out); Document doc = doc(b, "com.test.scala.Service"); assertEquals("com.test.scala.Service", xpath.evaluate("component/implementation/@class", doc)); assertEquals("", xpath.evaluate("component/service/provide/@interface", doc)); } /** * Test config with metatype */ @Component(name = "config", designateFactory = Config.class, configurationPolicy = ConfigurationPolicy.require) static class MetatypeConfig { interface Config { String name(); } } @Component(designate = Config.class) static class MetatypeConfig2 { interface Config { String name(); } } public void testConfig() throws Exception { Builder b = new Builder(); b.setExceptions(true); b.setClasspath(new File[] { new File("bin") }); b.setProperty("Service-Component", "*MetatypeConfig*"); b.setProperty("Private-Package", "test"); b.build(); System.out.println(b.getErrors()); System.out.println(b.getWarnings()); assertEquals(0, b.getErrors().size()); assertEquals(0, b.getWarnings().size()); System.out.println(b.getJar().getResources().keySet()); // Check component name { Resource cr = b.getJar().getResource("OSGI-INF/config.xml"); cr.write(System.out); Document d = db.parse(cr.openInputStream()); assertEquals("config", xpath.evaluate("/scr:component/@name", d, XPathConstants.STRING)); } // Check if config properly linked { Resource mr = b.getJar().getResource("OSGI-INF/metatype/config.xml"); mr.write(System.out); Document d = db.parse(mr.openInputStream()); assertEquals("config", xpath.evaluate("//Designate/@factoryPid", d, XPathConstants.STRING)); assertEquals("config", xpath.evaluate("//Object/@ocdref", d, XPathConstants.STRING)); } // Now with default name { Resource cr2 = b.getJar() .getResource("OSGI-INF/test.ComponentTest$MetatypeConfig2.xml"); cr2.write(System.out); Document d = db.parse(cr2.openInputStream()); assertEquals("test.ComponentTest$MetatypeConfig2", xpath.evaluate("//scr:component/@name", d, XPathConstants.STRING)); } { Resource mr2 = b.getJar().getResource( "OSGI-INF/metatype/test.ComponentTest$MetatypeConfig2.xml"); mr2.write(System.out); Document d = db.parse(mr2.openInputStream()); assertEquals("test.ComponentTest$MetatypeConfig2", xpath.evaluate( "//Designate/@pid", d, XPathConstants.STRING)); assertEquals("test.ComponentTest$MetatypeConfig2", xpath.evaluate("//Object/@ocdref", d, XPathConstants.STRING)); } } /** * Test properties */ @Meta.OCD static interface Config { String name(); } @Component(name = "props", properties = { "a=1", "b=3", "c=1|2|3" }, designate = Config.class, designateFactory = Config.class) static class PropertiesAndConfig { @Activate protected void activate(ComponentContext c) { } } public void testPropertiesAndConfig() throws Exception { Builder b = new Builder(); b.setExceptions(true); b.setClasspath(new File[] { new File("bin") }); b.setProperty("Service-Component", "*PropertiesAndConfig"); b.setProperty("Private-Package", "test"); b.build(); System.out.println(b.getErrors()); System.out.println(b.getWarnings()); assertEquals(0, b.getErrors().size()); assertEquals(0, b.getWarnings().size()); Resource cr = b.getJar().getResource("OSGI-INF/props.xml"); cr.write(System.out); { Document doc = doc(b, "props"); assertEquals("1", xpath.evaluate("scr:component/property[@name='a']/@value", doc)); assertEquals("3", xpath.evaluate("scr:component/property[@name='b']/@value", doc)); assertEquals("\n1\n2\n3\n", xpath.evaluate("scr:component/property[@name='c']", doc)); } } /** * Test if a reference is made to an interface implemented on a superclass. * * This is from https://github.com/bndtools/bnd/issues#issue/23 */ public void testProvideFromSuperClass() throws Exception { Builder b = new Builder(); b.setClasspath(new File[] { new File("bin") }); b.setProperty("Service-Component", "*InheritedActivator"); b.setProperty("Private-Package", "test.activator.inherits"); b.addClasspath(new File("jar/osgi.jar")); b.build(); System.out.println(b.getErrors()); System.out.println(b.getWarnings()); assertEquals(0, b.getErrors().size()); assertEquals(0, b.getWarnings().size()); Manifest m = b.getJar().getManifest(); String imports = m.getMainAttributes().getValue("Import-Package"); assertTrue(imports.contains("org.osgi.framework")); } /** * Test if a package private method gives us 1.1 + namespace in the XML */ @Component(name = "packageprotected") static class PackageProtectedActivateMethod { @Activate protected void activate(ComponentContext c) { } } @Component(name = "packageprivate") static class PackagePrivateActivateMethod { @Activate void activate(ComponentContext c) { } } public void testPackagePrivateActivateMethod() throws Exception { Builder b = new Builder(); b.setClasspath(new File[] { new File("bin") }); b.setProperty("Service-Component", "*Package*ActivateMethod"); b.setProperty("Private-Package", "test"); b.build(); System.out.println(b.getErrors()); System.out.println(b.getWarnings()); assertEquals(0, b.getErrors().size()); assertEquals(0, b.getWarnings().size()); { Document doc = doc(b, "packageprotected"); Object o = xpath.evaluate("component", doc, XPathConstants.NODE); assertNotNull(o); } { Resource r = b.getJar().getResource("OSGI-INF/packageprivate.xml"); r.write(System.out); assertNotNull(r); Document doc = db.parse(r.openInputStream()); assertNotNull(xpath.evaluate("//scr:component/@name", doc, XPathConstants.STRING)); } } /** * Test an attribute on an annotation */ @Component(name = "annotated") static class Annotated { @Reference protected void setLog(LogService log) { } } public void testAnnotatedWithAttribute() throws Exception { Builder b = new Builder(); b.setClasspath(new File[] { new File("bin") }); b.setProperty("Service-Component", "*NoUnbind;log=org.osgi.service.log.LogService"); b.setProperty("Private-Package", "test"); Jar jar = b.build(); Manifest manifest = jar.getManifest(); String sc = manifest.getMainAttributes().getValue(Constants.SERVICE_COMPONENT); assertFalse(sc.contains(";")); System.out.println(b.getErrors()); System.out.println(b.getWarnings()); assertEquals(0, b.getErrors().size()); assertEquals(0, b.getWarnings().size()); } /** * A non-FQN entry but we demand no annotations, should generate an error * and no component */ public void testNonFQNAndNoAnnotations() throws Exception { Builder b = new Builder(); b .setProperty("Include-Resource", "org/osgi/impl/service/coordinator/AnnotationWithJSR14.class=jar/AnnotationWithJSR14.jclass"); b.setProperty("Service-Component", "*;" + Constants.NOANNOTATIONS + "=true"); b.setProperty("-resourceonly", "true"); Jar jar = b.build(); System.out.println(b.getErrors()); System.out.println(b.getWarnings()); assertEquals(1, b.getErrors().size()); assertEquals(0, b.getWarnings().size()); Manifest manifest = jar.getManifest(); String component = manifest.getMainAttributes().getValue("Service-Component"); System.out.println(component); assertNull(component); } /** * Imported default package because JSR14 seems to do something weird with * annotations. * * @throws Exception */ public void testJSR14ComponentAnnotations() throws Exception { Builder b = new Builder(); b .setProperty("Include-Resource", "org/osgi/impl/service/coordinator/AnnotationWithJSR14.class=jar/AnnotationWithJSR14.jclass"); b.setProperty("Service-Component", "*"); b.setProperty("-resourceonly", "true"); Jar jar = b.build(); System.out.println(b.getErrors()); System.out.println(b.getWarnings()); assertEquals(0, b.getErrors().size()); assertEquals(1, b.getWarnings().size()); Manifest manifest = jar.getManifest(); String component = manifest.getMainAttributes().getValue("Service-Component"); System.out.println(component); assertNull(component); } @Component(name = "nounbind") static class NoUnbind { @Reference protected void setLog(LogService log) { } } public void testNoUnbind() throws Exception { Builder b = new Builder(); b.setClasspath(new File[] { new File("bin") }); b.setProperty("Service-Component", "*NoUnbind"); b.setProperty("Private-Package", "test"); b.build(); System.out.println(b.getErrors()); System.out.println(b.getWarnings()); assertEquals(0, b.getErrors().size()); assertEquals(0, b.getWarnings().size()); Document doc = doc(b, "nounbind"); assertEquals("setLog", xpath.evaluate("component/reference/@bind", doc)); assertEquals("", xpath.evaluate("component/reference/@unbind", doc)); } @Component(name = "explicitunbind") static class ExplicitUnbind { @Reference(unbind = "killLog") protected void setLog(LogService log) { } } public void testExplicitUnbind() throws Exception { Builder b = new Builder(); b.setClasspath(new File[] { new File("bin") }); b.setProperty("Service-Component", "*ExplicitUnbind"); b.setProperty("Private-Package", "test"); b.build(); System.out.println(b.getErrors()); System.out.println(b.getWarnings()); assertEquals(1, b.getErrors().size()); assertEquals(0, b.getWarnings().size()); Document doc = doc(b, "explicitunbind"); assertEquals("setLog", xpath.evaluate("component/reference/@bind", doc)); assertEquals("killLog", xpath.evaluate("component/reference/@unbind", doc)); } /** * Test to see if we get a namespace when we use 1.1 semantics on the * activate and deactivate */ @Component(name = "ncomp", provide = {}) static class NewActivateVersion { @Activate protected void activate(ComponentContext context) { } } @Component(name = "ndcomp", provide = {}) static class NewDeActivateVersion { @Deactivate protected void deactivate() { } } @Component(name = "nbcomp", provide = {}) static class NewBindVersion { @Reference protected void bind(ServiceReference ref, Map map) { } } public void testNewVersion() throws Exception { Builder b = new Builder(); b.setClasspath(new File[] { new File("bin") }); b.setProperty("Service-Component", "*Version"); b.setProperty("Private-Package", "test"); b.build(); System.out.println(b.getErrors()); System.out.println(b.getWarnings()); assertEquals(0, b.getErrors().size()); assertEquals(0, b.getWarnings().size()); { Document doc = doc(b, "ncomp"); Node o = (Node) xpath.evaluate("component", doc, XPathConstants.NODE); assertNotNull("Expected ncomp to have old namespace", o); } // Node node = doc.getElementsByTagName("component").item(0); // assertNotNull(node.getNamespaceURI()); // doc = doc(b, "ndcomp"); // assertNotNull(doc.getElementsByTagName("component").item(0).getNamespaceURI()); // doc = doc(b, "nbcomp"); // assertNotNull(doc.getElementsByTagName("component").item(0).getNamespaceURI()); } /** * Test the same bind method names */ @Component(name = "cpcomp") static class SameRefName { @Reference protected void bind(LogService log) { } @Reference protected void bind(EventAdmin event) { } } public void testSameRefName() throws Exception { Builder b = new Builder(); b.setClasspath(new File[] { new File("bin") }); b.setProperty("Service-Component", "*.SameRefName"); b.setProperty("Private-Package", "test"); b.build(); System.out.println(b.getErrors()); System.out.println(b.getWarnings()); assertEquals(1, b.getErrors().size()); assertEquals(0, b.getWarnings().size()); // Document doc = doc(b, "cpcomp"); } /** * Test the configuration policy */ @Component(name = "cpcomp", configurationPolicy = ConfigurationPolicy.require, provide = { Serializable.class, EventAdmin.class }) static class ConfigurationPolicyTest { } public void testConfigurationPolicy() throws Exception { Builder b = new Builder(); b.setClasspath(new File[] { new File("bin") }); b.setProperty("Service-Component", "*.ConfigurationPolicyTest"); b.setProperty("Private-Package", "test"); b.build(); System.out.println(b.getErrors()); System.out.println(b.getWarnings()); assertEquals(0, b.getErrors().size()); assertEquals(0, b.getWarnings().size()); Document doc = doc(b, "cpcomp"); assertEquals("java.io.Serializable", doc.getElementsByTagName("provide").item(0) .getAttributes().getNamedItem("interface").getTextContent()); assertEquals("org.osgi.service.event.EventAdmin", doc.getElementsByTagName("provide").item( 1).getAttributes().getNamedItem("interface").getTextContent()); } /** * Test to see if we use defaults we get the old version of the namespace */ @Component(name = "vcomp", provide = {}) static class OldVersion { @Activate protected void activate(ComponentContext cc) { } @Deactivate protected void deactivate(ComponentContext cc) { } @Reference protected void bindLog(LogService log) { } } public void testOldVersion() throws Exception { Builder b = new Builder(); b.setClasspath(new File[] { new File("bin") }); b.setProperty("Service-Component", "*.OldVersion"); b.setProperty("Private-Package", "test"); b.build(); System.out.println(b.getErrors()); System.out.println(b.getWarnings()); assertEquals(0, b.getErrors().size()); assertEquals(0, b.getWarnings().size()); Document doc = doc(b, "vcomp"); assertEquals(null, doc.getElementsByTagName("component").item(0).getNamespaceURI()); } /** * Test if an activate/deactivate method that has wrong prototype */ @Component(name = "wacomp", provide = {}) static class ActivateWithWrongArguments { @Activate// Is not allowed, must give an error protected void whatever(String x) { } } public void testActivateWithActivateWithWrongArguments() throws Exception { Builder b = new Builder(); b.setClasspath(new File[] { new File("bin") }); b.setProperty("Service-Component", "*.ActivateWithWrongArguments"); b.setProperty("Private-Package", "test"); b.build(); System.out.println(b.getErrors()); System.out.println(b.getWarnings()); assertEquals(1, b.getErrors().size()); assertEquals(0, b.getWarnings().size()); Document doc = doc(b, "wacomp"); assertEquals("whatever", xpath.evaluate("scr:component/@activate",doc,XPathConstants.STRING)); assertAttribute(doc, "whatever", "scr:component/@activate"); } /** * Test if an activate/deactivate method can have multiple args */ @Component(name = "amcomp", provide = {}) static class ActivateWithMultipleArguments { @Activate protected void whatever(Map map, ComponentContext cc, BundleContext bc, Map x) { } } public void testActivateWithMultipleArguments() throws Exception { Builder b = new Builder(); b.setClasspath(new File[] { new File("bin") }); b.setProperty("Service-Component", "*.ActivateWithMultipleArguments"); b.setProperty("Private-Package", "test"); b.build(); System.out.println(b.getErrors()); System.out.println(b.getWarnings()); assertEquals(0, b.getErrors().size()); assertEquals(0, b.getWarnings().size()); Document doc = doc(b, "amcomp"); assertAttribute(doc, "whatever", "scr:component/@activate"); } /** * Test components with references that have multiple arguments. */ @Component(name = "mcomp", provide = {}) static class MultipleArguments { @Reference protected void bindWithMap(LogService log, Map map) { } } @Component(name = "rcomp", provide = {}) static class ReferenceArgument { @Reference(service = LogService.class) protected void bindReference(ServiceReference ref) { } } public void testMultipleArguments() throws Exception { Builder b = new Builder(); b.setClasspath(new File[] { new File("bin") }); b.setProperty("Service-Component", "*.(MultipleArguments|ReferenceArgument)"); b.setProperty("Private-Package", "test"); b.build(); System.out.println(b.getErrors()); System.out.println(b.getWarnings()); assertEquals(0, b.getErrors().size()); assertEquals(0, b.getWarnings().size()); Document doc = doc(b, "mcomp"); assertAttribute(doc, "bindWithMap", "scr:component/reference/@bind"); assertAttribute(doc, "org.osgi.service.log.LogService", "scr:component/reference/@interface"); doc = doc(b, "rcomp"); assertAttribute(doc, "bindReference", "scr:component/reference/@bind"); assertAttribute(doc, "org.osgi.service.log.LogService", "scr:component/reference/@interface"); } /** * Test components with weird bind methods. */ @Component(name = "xcomp", provide = {}) static class TypeVersusDetailed { @Reference(type = '*') protected void bind(LogService log) { } @Reference(multiple = true, optional = true, dynamic = true) protected void bind2( LogService log) { } } public void testTypeVersusDetailed() throws Exception { Builder b = new Builder(); b.setClasspath(new File[] { new File("bin") }); b.setProperty("Service-Component", "*.TypeVersusDetailed"); b.setProperty("Private-Package", "test"); b.build(); System.out.println(b.getErrors()); System.out.println(b.getWarnings()); assertEquals(0, b.getErrors().size()); assertEquals(0, b.getWarnings().size()); Document doc = doc(b, "xcomp"); print(doc, ""); assertAttribute(doc, "bind2", "component/reference[1]/@bind"); assertAttribute(doc, "dynamic", "component/reference[1]/@policy"); assertAttribute(doc, "0..n", "component/reference[1]/@cardinality"); assertAttribute(doc, "bind", "component/reference[2]/@bind"); assertAttribute(doc, "dynamic", "component/reference[2]/@policy"); assertAttribute(doc, "0..n", "component/reference[2]/@cardinality"); } /** * Test components with weird bind methods. */ @Component(name = "acomp", provide = {}) static class MyComponent4 { @Activate protected void xyz() { } } public void testAnnotationsNamespaceVersion() throws Exception { Builder b = new Builder(); b.setClasspath(new File[] { new File("bin") }); b.setProperty("Service-Component", "*.MyComponent4"); b.setProperty("Private-Package", "test"); b.build(); System.out.println(b.getErrors()); System.out.println(b.getWarnings()); assertEquals(0, b.getErrors().size()); assertEquals(0, b.getWarnings().size()); Document doc = doc(b, "acomp"); System.out.println(doc.getDocumentElement().getNamespaceURI()); } /** * Test components with weird bind methods. */ @Component(name = "acomp", configurationPolicy = ConfigurationPolicy.require) static class MyComponent2 { @Reference protected void addLogMultiple(LogService log) { } } public void testAnnotationsStrangeBindMethods() throws Exception { Builder b = new Builder(); b.setClasspath(new File[] { new File("bin") }); b.setProperty("Service-Component", "*.MyComponent2"); b.setProperty("Private-Package", "test"); b.build(); System.out.println(b.getErrors()); System.out.println(b.getWarnings()); assertEquals(0, b.getErrors().size()); assertEquals(0, b.getWarnings().size()); Document doc = doc(b, "acomp"); assertEquals("addLogMultiple", xpath.evaluate("//@bind", doc)); assertEquals("", xpath.evaluate("//@unbind", doc)); assertAttribute(doc, "logMultiple", "scr:component/reference[1]/@name"); assertAttribute(doc, "addLogMultiple", "scr:component/reference[1]/@bind"); } /** * Test setting the unbind method */ @Component(name = "acomp", configurationPolicy = ConfigurationPolicy.ignore) static class MyComponent3 { @Reference(unbind = "destroyX") protected void putX(LogService log) { } } public void testAnnotationsSettingUnbind() throws Exception { Builder b = new Builder(); b.setClasspath(new File[] { new File("bin") }); b.setProperty("Service-Component", "*.MyComponent3"); b.setProperty("Private-Package", "test"); b.build(); System.out.println(b.getErrors()); System.out.println(b.getWarnings()); assertEquals(1, b.getErrors().size()); assertEquals(0, b.getWarnings().size()); Document doc = doc(b, "acomp"); assertAttribute(doc, "putx", "scr:component/reference[1]/@name"); assertAttribute(doc, "putX", "scr:component/reference[1]/@bind"); assertAttribute(doc, "destroyX", "scr:component/reference[1]/@unbind"); } /** * Test some more components * * @author aqute * */ @Component(name = "acomp", enabled = true, factory = "abc", immediate = false, provide = LogService.class, servicefactory = true, configurationPolicy = ConfigurationPolicy.optional) static class MyComponent implements Serializable { private static final long serialVersionUID = 1L; LogService log; @Activate protected void activatex() { } @Deactivate protected void deactivatex() { } @Modified protected void modifiedx() { } @Reference(type = '~', target = "(abc=3)") protected void setLog(LogService log) { this.log = log; } protected void unsetLog(LogService log) { this.log = null; } } public void testAnnotations() throws Exception { Builder b = new Builder(); b.setClasspath(new File[] { new File("bin") }); b.setProperty("Service-Component", "*.MyComponent"); b.setProperty("Private-Package", "test"); b.build(); System.out.println(b.getErrors()); System.out.println(b.getWarnings()); assertEquals(0, b.getErrors().size()); assertEquals(0, b.getWarnings().size()); Document doc = doc(b, "acomp"); print(doc, ""); assertAttribute(doc, "test.ComponentTest$MyComponent", "scr:component/implementation/@class"); assertAttribute(doc, "acomp", "scr:component/@name"); assertAttribute(doc, "abc", "scr:component/@factory"); assertAttribute(doc, "true", "scr:component/service/@servicefactory"); assertAttribute(doc, "activatex", "scr:component/@activate"); assertAttribute(doc, "modifiedx", "scr:component/@modified"); assertAttribute(doc, "deactivatex", "scr:component/@deactivate"); assertAttribute(doc, "org.osgi.service.log.LogService", "scr:component/service/provide/@interface"); assertAttribute(doc, "(abc=3)", "scr:component/reference/@target"); assertAttribute(doc, "setLog", "scr:component/reference/@bind"); assertAttribute(doc, "unsetLog", "scr:component/reference/@unbind"); assertAttribute(doc, "0..1", "scr:component/reference/@cardinality"); } public void assertAttribute(Document doc, String value, String expr) throws XPathExpressionException { System.out.println(expr); String o = (String) xpath.evaluate(expr, doc, XPathConstants.STRING); if ( o == null ) { } assertNotNull(o); assertEquals(value, o); } Document doc(Builder b, String name) throws Exception { Jar jar = b.getJar(); Resource r = jar.getResource("OSGI-INF/" + name + ".xml"); assertNotNull(r); Document doc = db.parse(r.openInputStream()); r.write(System.out); return doc; } public void testV1_1Directives() throws Exception { Element component = setup("test.activator.Activator;factory:=blabla;immediate:=true;enabled:=false;configuration-policy:=optional;activate:=start;deactivate:=stop;modified:=modified"); assertEquals("http://www.osgi.org/xmlns/scr/v1.1.0", component.getNamespaceURI()); assertEquals("blabla", component.getAttribute("factory")); assertEquals("false", component.getAttribute("enabled")); assertEquals("optional", component.getAttribute("configuration-policy")); assertEquals("start", component.getAttribute("activate")); assertEquals("stop", component.getAttribute("deactivate")); assertEquals("modified", component.getAttribute("modified")); } public void testNoNamespace() throws Exception { Element component = setup("test.activator.Activator"); assertEquals(null, component.getNamespaceURI()); } public void testAutoNamespace() throws Exception { Element component = setup("test.activator.Activator;activate:='start';deactivate:='stop'"); assertEquals("http://www.osgi.org/xmlns/scr/v1.1.0", component.getNamespaceURI()); } public void testCustomNamespace() throws Exception { Element component = setup("test.activator.Activator;version:=2"); assertEquals("http://www.osgi.org/xmlns/scr/v2.0.0", component.getNamespaceURI()); } Element setup(String header) throws Exception { Builder b = new Builder(); b.setProperty(Analyzer.SERVICE_COMPONENT, header); b.setClasspath(new File[] { new File("bin"), new File("jar/osgi.jar") }); b.setProperty("Private-Package", "test.activator, org.osgi.service.http.*"); b.build(); System.out.println(b.getErrors()); System.out.println(b.getWarnings()); assertEquals(0, b.getErrors().size()); assertEquals(0, b.getWarnings().size()); print(b.getJar().getResource("OSGI-INF/test.activator.Activator.xml"), System.out); Document doc = db.parse(new InputSource(b.getJar().getResource( "OSGI-INF/test.activator.Activator.xml").openInputStream())); return doc.getDocumentElement(); } private void print(Resource resource, OutputStream out) throws Exception { InputStream in = resource.openInputStream(); try { byte[] buffer = new byte[1024]; int size = in.read(buffer); while (size > 0) { out.write(buffer, 0, size); size = in.read(buffer); } out.flush(); } finally { in.close(); } } /* * public void testWildcards() throws Exception { Builder b = new Builder(); * b .setProperty(Analyzer.SERVICE_COMPONENT, "test/component/*.xml"); * b.setProperty("-resourceonly", "true"); b.setProperty("Include-Resource", * "test/component=test/component"); Jar jar = b.build(); * System.out.println(b.getErrors()); System.out.println(b.getWarnings()); * assertEquals(0, b.getErrors().size()); assertEquals(0, * b.getWarnings().size()); } */ public void testImplementation() throws Exception { Builder b = new Builder(); b .setProperty( Analyzer.SERVICE_COMPONENT, "silly.name;implementation:=test.activator.Activator;provide:=java.io.Serialization;servicefactory:=true"); b.setClasspath(new File[] { new File("bin"), new File("jar/osgi.jar") }); b.setProperty("Private-Package", "test.activator"); b.build(); System.out.println(b.getErrors()); System.out.println(b.getWarnings()); assertEquals(0, b.getErrors().size()); assertEquals(0, b.getWarnings().size()); Jar jar = b.getJar(); Document doc = db.parse(new InputSource(jar.getResource("OSGI-INF/silly.name.xml") .openInputStream())); assertEquals("test.activator.Activator", doc.getElementsByTagName("implementation").item(0) .getAttributes().getNamedItem("class").getNodeValue()); assertEquals("true", doc.getElementsByTagName("service").item(0).getAttributes() .getNamedItem("servicefactory").getNodeValue()); } /** * Standard activator with reference to http. * * @throws Exception */ public void testProperties() throws Exception { java.util.Properties p = new Properties(); p.put(Analyzer.EXPORT_PACKAGE, "test.activator,org.osgi.service.http"); p.put(Analyzer.IMPORT_PACKAGE, "*"); p.put(Analyzer.SERVICE_COMPONENT, "test.activator.Activator;properties:=\"a=3|4,b=1|2|3\""); Builder b = new Builder(); b.setClasspath(new File[] { new File("bin"), new File("jar/osgi.jar") }); b.setProperties(p); b.build(); assertEquals(0, b.getErrors().size()); assertEquals(0, b.getWarnings().size()); Jar jar = b.getJar(); Document doc = db.parse(new InputSource(jar.getResource( "OSGI-INF/test.activator.Activator.xml").openInputStream())); NodeList l = doc.getElementsByTagName("property"); assertEquals(2, l.getLength()); Node n = l.item(0); System.out.println(n.getFirstChild().getNodeValue()); assertEquals("3\n4", l.item(0).getFirstChild().getNodeValue().trim()); assertEquals("1\n2\n3", l.item(1).getFirstChild().getNodeValue().trim()); assertEquals("test.activator.Activator", doc.getElementsByTagName("implementation").item(0) .getAttributes().getNamedItem("class").getNodeValue()); // assertEquals("test.activator.Activator", xp.evaluate( // "/component/implementation/@class", doc)); // assertEquals("org.osgi.service.http.HttpService", xp.evaluate( // "/component/reference[@name='http']/@interface", doc)); // assertEquals("setHttp", xp.evaluate( // "/component/reference[@name='http']/@bind", doc)); // assertEquals("unsetHttp", xp.evaluate( // "/component/reference[@name='http']/@unbind", doc)); // assertEquals("", xp.evaluate( // "/component/reference[@name='http']/@target", doc)); } /** * Check if all the directives work * * @throws Exception */ public void testUnknownDirective() throws Exception { java.util.Properties p = new Properties(); p.put(Analyzer.EXPORT_PACKAGE, "test.activator,org.osgi.service.http"); p.put(Analyzer.IMPORT_PACKAGE, "*"); p.put(Analyzer.SERVICE_COMPONENT, "test.activator.Activator;provides:=true"); Builder b = new Builder(); b.setClasspath(new File[] { new File("bin"), new File("jar/osgi.jar") }); b.setProperties(p); b.build(); assertEquals(1, b.getErrors().size()); assertTrue(((String) b.getErrors().get(0)).indexOf("Unrecognized directive") >= 0); assertEquals(0, b.getWarnings().size()); } /** * Check if all the directives work * * @throws Exception */ public void testDirectives() throws Exception { // Element component = // setup("test.activator.Activator;http=org.osgi.service.http.HttpService;dynamic:=http;optional:=http;provide:=test.activator.Activator; multiple:=http"); // assertEquals("test.activator.Activator", xp.evaluate( // "/component/implementation/@class", doc)); // assertEquals("org.osgi.service.http.HttpService", xp.evaluate( // "/component/reference[@name='http']/@interface", doc)); // assertEquals("setHttp", xp.evaluate( // "/component/reference[@name='http']/@bind", doc)); // assertEquals("unsetHttp", xp.evaluate( // "/component/reference[@name='http']/@unbind", doc)); // assertEquals("0..n", xp.evaluate( // "/component/reference[@name='http']/@cardinality", doc)); // assertEquals("dynamic", xp.evaluate( // "/component/reference[@name='http']/@policy", doc)); // assertEquals("test.activator.Activator", xp.evaluate( // "/component/service/provide/@interface", doc)); } /** * Check if a bad filter on a service component causes an error. * * @throws Exception */ public void testBadFilter() throws Exception { // java.util.Properties p = new Properties(); // p.put(Analyzer.EXPORT_PACKAGE, // "test.activator,org.osgi.service.http"); // p.put(Analyzer.IMPORT_PACKAGE, "*"); // p // .put( // Analyzer.SERVICE_COMPONENT, // "test.activator.Activator;http=\"org.osgi.service.http.HttpService(|p=1)(p=2))\""); // Builder b = new Builder(); // b // .setClasspath(new File[] { new File("bin"), // new File("jar/osgi.jar") }); // b.setProperties(p); // b.build(); // assertEquals(1, b.getErrors().size()); // assertTrue(((String) b.getErrors().get(0)) // .indexOf("is not a correct filter") >= 0); // assertEquals(0, b.getWarnings().size()); } /** * Check if we can set a target filter * * @throws Exception */ public void testFilter() throws Exception { Element component = setup("test.activator.Activator;http=\"org.osgi.service.http.HttpService(|(p=1)(p=2))\""); Element implementation = (Element) component.getElementsByTagName("implementation").item(0); assertEquals(null, implementation.getNamespaceURI()); assertEquals("test.activator.Activator", implementation.getAttribute("class")); Element reference = (Element) component.getElementsByTagName("reference").item(0); assertEquals("org.osgi.service.http.HttpService", reference.getAttribute("interface")); assertEquals("setHttp", reference.getAttribute("bind")); assertEquals("unsetHttp", reference.getAttribute("unbind")); assertEquals("(|(p=1)(p=2))", reference.getAttribute("target")); } /** * Standard activator with reference to http. * * @throws Exception */ public void testSimple() throws Exception { Element component = setup("test.activator.Activator;http=org.osgi.service.http.HttpService?"); Element implementation = (Element) component.getElementsByTagName("implementation").item(0); assertEquals(null, implementation.getNamespaceURI()); assertEquals("test.activator.Activator", implementation.getAttribute("class")); Element reference = (Element) component.getElementsByTagName("reference").item(0); assertEquals("org.osgi.service.http.HttpService", reference.getAttribute("interface")); assertEquals("setHttp", reference.getAttribute("bind")); assertEquals("unsetHttp", reference.getAttribute("unbind")); assertEquals("", reference.getAttribute("target")); assertEquals("0..1", reference.getAttribute("cardinality")); assertEquals("dynamic", reference.getAttribute("policy")); } /** * Standard activator with reference to http. * * @throws Exception */ public void testQuestion() throws Exception { Element component = setup("test.activator.Activator;http=org.osgi.service.http.HttpService?"); Element reference = (Element) component.getElementsByTagName("reference").item(0); assertEquals("0..1", reference.getAttribute("cardinality")); assertEquals("dynamic", reference.getAttribute("policy")); } public void testStar() throws Exception { Element component = setup("test.activator.Activator;http=org.osgi.service.http.HttpService*"); Element reference = (Element) component.getElementsByTagName("reference").item(0); assertEquals("0..n", reference.getAttribute("cardinality")); assertEquals("dynamic", reference.getAttribute("policy")); } public void testPlus() throws Exception { Element component = setup("test.activator.Activator;http=org.osgi.service.http.HttpService+"); Element reference = (Element) component.getElementsByTagName("reference").item(0); assertEquals("1..n", reference.getAttribute("cardinality")); assertEquals("dynamic", reference.getAttribute("policy")); } public void testTilde() throws Exception { Element component = setup("test.activator.Activator;http=org.osgi.service.http.HttpService~"); Element reference = (Element) component.getElementsByTagName("reference").item(0); assertEquals("0..1", reference.getAttribute("cardinality")); assertEquals("", reference.getAttribute("policy")); } private void print(Node doc, String indent) { System.out.println(indent + doc); NamedNodeMap attributes = doc.getAttributes(); if (attributes != null) for (int i = 0; i < attributes.getLength(); i++) { print(attributes.item(i), indent + " "); } NodeList nl = doc.getChildNodes(); for (int i = 0; i < nl.getLength(); i++) { print(nl.item(i), indent + " "); } } } bnd-1.50.0/biz.aQute.bndlib/src/test/classreference/0000755000175000017500000000000011656076535022077 5ustar drazzibdrazzibbnd-1.50.0/biz.aQute.bndlib/src/test/classreference/ClassReference.java0000755000175000017500000000022411656076535025627 0ustar drazzibdrazzibpackage test.classreference; public class ClassReference { public void testClassReference() { System.out.println(javax.swing.Box.class); } } bnd-1.50.0/biz.aQute.bndlib/src/test/.cvsignore0000644000175000017500000000002111656076535021104 0ustar drazzibdrazzibRichardTest.java bnd-1.50.0/biz.aQute.bndlib/src/test/PackTest.java0000644000175000017500000000055411656076535021500 0ustar drazzibdrazzibpackage test; import junit.framework.*; public class PackTest extends TestCase { public void testNot() {} // public void testSimple() throws Exception { // Workspace ws= Workspace.getWorkspace("/Ws/aQute"); // Project p = ws.getProject("aQute.metatype"); // ProjectLauncher pl = p.getProjectLauncher(); // // Jar jar = pl.executable(); // // } } bnd-1.50.0/biz.aQute.bndlib/src/test/packageinfo/0000755000175000017500000000000011656076535021362 5ustar drazzibdrazzibbnd-1.50.0/biz.aQute.bndlib/src/test/packageinfo/packageinfo0000644000175000017500000000011111656076535023545 0ustar drazzibdrazzibversion 1.0.0-SNAPSHOT Implementation-Version 1.2.3 Implementation-Title bnd-1.50.0/biz.aQute.bndlib/src/test/packageinfo/Dummy.java0000644000175000017500000000006311656076535023317 0ustar drazzibdrazzibpackage test.packageinfo; public class Dummy { } bnd-1.50.0/biz.aQute.bndlib/src/test/packageinfo/ref/0000755000175000017500000000000011656076535022136 5ustar drazzibdrazzibbnd-1.50.0/biz.aQute.bndlib/src/test/packageinfo/ref/DummyRef.java0000644000175000017500000000016411656076535024532 0ustar drazzibdrazzibpackage test.packageinfo.ref; import test.packageinfo.*; public class DummyRef { Dummy dummy = new Dummy(); } bnd-1.50.0/biz.aQute.bndlib/src/test/VerifierTest.java0000755000175000017500000002202411656076535022374 0ustar drazzibdrazzibpackage test; import java.io.File; import java.util.Properties; import java.util.jar.Manifest; import junit.framework.TestCase; import aQute.lib.osgi.*; public class VerifierTest extends TestCase { public void testnativeCode() throws Exception { Builder b = new Builder(); b.addClasspath( new File("bin")); b.setProperty("-resourceonly", "true"); b.setProperty("Include-Resource", "native/win32/NTEventLogAppender-1.2.dll;literal='abc'"); b.setProperty("Bundle-NativeCode", "native/win32/NTEventLogAppender-1.2.dll; osname=Win32; processor=x86"); Jar jar = b.build(); Verifier v = new Verifier(jar); v.setJar(jar); v.verifyNative(); System.out.println( v.getErrors()); assertEquals(0, v.getErrors().size()); v.close(); b.close(); } public void testFilter() { testFilter("(&(a=b)(c=1))"); testFilter("(&(a=b)(!(c=1))(&(c=1))(c=1)(c=1)(c=1)(c=1)(c=1)(c=1)(c=1)(c=1))"); testFilter("(!(a=b))"); testInvalidFilter("(!(a=b)(c=2))"); testInvalidFilter("(axb)"); testInvalidFilter("(a=3 "); testFilter("(room=*)"); testFilter("(room=bedroom)"); testFilter("(room~= B E D R O O M )"); testFilter("(room=abc)"); testFilter(" ( room >=aaaa)"); testFilter("(room <=aaaa)"); testFilter(" ( room =b*) "); testFilter(" ( room =*m) "); testFilter("(room=bed*room)"); testFilter(" ( room =b*oo*m) "); testFilter(" ( room =*b*oo*m*) "); testFilter(" ( room =b*b* *m*) "); testFilter(" (& (room =bedroom) (channel ~=34))"); testFilter(" (& (room =b*) (room =*x) (channel=34))"); testFilter("(| (room =bed*)(channel=222)) "); testFilter("(| (room =boom*)(channel=101)) "); testFilter(" (! (room =ab*b*oo*m*) ) "); testFilter(" (status =\\(o*\\\\\\)\\*) "); testFilter(" (canRecord =true\\(x\\)) "); testFilter("(max Record Time <=140) "); testFilter("(shortValue >=100) "); testFilter("(intValue <=100001) "); testFilter("(longValue >=10000000000) "); testFilter(" ( & ( byteValue <=100) ( byteValue >=10) ) "); testFilter("(weirdValue =100) "); testFilter("(bigIntValue =4123456) "); testFilter("(bigDecValue =4.123456) "); testFilter("(floatValue >=1.0) "); testFilter("(doubleValue <=2.011) "); testFilter("(charValue ~=a) "); testFilter("(booleanValue =true) "); testFilter("(primIntArrayValue =1) "); testFilter("(primLongArrayValue =2) "); testFilter("(primByteArrayValue =3) "); testFilter("(primShortArrayValue =1) "); testFilter("(primFloatArrayValue =1.1) "); testFilter("(primDoubleArrayValue =2.2) "); testFilter("(primCharArrayValue ~=D) "); testFilter("(primBooleanArrayValue =false) "); testFilter("(& (| (room =d*m) (room =bed*) (room=abc)) (! (channel=999)))"); testFilter("(room=bedroom)"); testFilter("(*=foo)"); testInvalidFilter("(! ab=b)"); testInvalidFilter("(| ab=b)"); testInvalidFilter("(&=c)"); testInvalidFilter("(!=c)"); testInvalidFilter("(|=c)"); testInvalidFilter("(& ab=b)"); testInvalidFilter("(!ab=*)"); testInvalidFilter("(|ab=*)"); testInvalidFilter("(&ab=*)"); testFilter("(empty=)"); testFilter("(empty=*)"); testFilter("(space= )"); testFilter("(space=*)"); testFilter("(intvalue=*)"); testFilter("(intvalue=b)"); testFilter("(intvalue=)"); testFilter("(longvalue=*)"); testFilter("(longvalue=b)"); testFilter("(longvalue=)"); testFilter("(shortvalue=*)"); testFilter("(shortvalue=b)"); testFilter("(shortvalue=)"); testFilter("(bytevalue=*)"); testFilter("(bytevalue=b)"); testFilter("(bytevalue=)"); testFilter("(charvalue=*)"); testFilter("(charvalue=)"); testFilter("(floatvalue=*)"); testFilter("(floatvalue=b)"); testFilter("(floatvalue=)"); testFilter("(doublevalue=*)"); testFilter("(doublevalue=b)"); testFilter("(doublevalue=)"); testFilter("(booleanvalue=*)"); testFilter("(booleanvalue=b)"); testFilter("(booleanvalue=)"); testInvalidFilter(""); testInvalidFilter("()"); testInvalidFilter("(=foo)"); testInvalidFilter("("); testInvalidFilter("(abc = ))"); testInvalidFilter("(& (abc = xyz) (& (345))"); testInvalidFilter(" (room = b**oo!*m*) ) "); testInvalidFilter(" (room = b**oo)*m*) ) "); testInvalidFilter(" (room = *=b**oo*m*) ) "); testInvalidFilter(" (room = =b**oo*m*) ) "); testFilter("(shortValue =100*) "); testFilter("(intValue =100*) "); testFilter("(longValue =100*) "); testFilter("( byteValue =1*00 )"); testFilter("(bigIntValue =4*23456) "); testFilter("(bigDecValue =4*123456) "); testFilter("(floatValue =1*0) "); testFilter("(doubleValue =2*011) "); testFilter("(charValue =a*) "); testFilter("(booleanValue =t*ue) "); } private void testFilter(String string) { int index = Verifier.verifyFilter(string, 0); while (index < string.length() && Character.isWhitespace(string.charAt(index))) index++; if ( index != string.length()) throw new IllegalArgumentException("Characters after filter"); } private void testInvalidFilter(String string) { try { testFilter(string); fail("Invalid filter"); } catch (Exception e) { } } public void testBundleActivationPolicyNone() throws Exception { Builder v = new Builder(); v.setProperty("Private-Package", "aQute.bnd.make"); v.addClasspath( new File("bin")); v.build(); assertEquals(0, v.getWarnings().size()); System.out.println(v.getErrors()); assertEquals(0, v.getErrors().size()); } public void testBundleActivationPolicyBad() throws Exception { Builder v = new Builder(); v.setProperty("Private-Package", "aQute.bnd.make"); v.addClasspath( new File("bin")); v.setProperty(Constants.BUNDLE_ACTIVATIONPOLICY, "eager"); v.build(); System.out.println("Errors: " + Processor.join(v.getErrors(), "\n")); System.out.println("Warnings: " + Processor.join(v.getWarnings(), "\n")); assertEquals(1, v.getWarnings().size()); assertEquals(0, v.getErrors().size()); } public void testBundleActivationPolicyGood() throws Exception { Builder v = new Builder(); v.setProperty("Private-Package", "aQute.bnd.make"); v.addClasspath( new File("bin")); v.setProperty(Constants.BUNDLE_ACTIVATIONPOLICY, "lazy ; hello:=1"); v.build(); System.out.println("Errors: " + Processor.join(v.getErrors(), "\n")); System.out.println("Warnings: " + Processor.join(v.getWarnings(), "\n")); assertEquals(0, v.getWarnings().size()); assertEquals(0, v.getErrors().size()); } public void testBundleActivationPolicyMultiple() throws Exception { Builder v = new Builder(); v.setProperty("Private-Package", "aQute.bnd.make"); v.addClasspath( new File("bin")); v.setProperty(Constants.BUNDLE_ACTIVATIONPOLICY, "lazy;hello:=1,2"); v.build(); assertEquals(1, v.getWarnings().size()); assertEquals(0, v.getErrors().size()); } public void testInvalidCaseForHeader() throws Exception { Properties p = new Properties(); p.put("Export-package", "org.apache.mina.*"); p.put("Bundle-Classpath", "."); Analyzer analyzer = new Analyzer(); analyzer.setProperties(p); analyzer.getProperties(); System.out.println("Errors " + analyzer.getErrors()); System.out.println("Warnings " + analyzer.getWarnings()); assertEquals(0, analyzer.getErrors().size()); assertEquals(2, analyzer.getWarnings().size()); } public void testSimple() throws Exception { File cp[] = { new File("jar/mina.jar") }; Properties p = new Properties(); p.put("Export-Package", "org.apache.mina.*;version=1"); p.put("Import-Package", "*"); p.put("DynamicImport-Package", "org.slf4j"); Builder bmaker = new Builder(); bmaker.setProperties(p); bmaker.setClasspath(cp); Jar jar = bmaker.build(); Manifest m = jar.getManifest(); assertFalse(m.getMainAttributes().getValue("Import-Package").indexOf( "org.slf4j") >= 0); assertTrue(m.getMainAttributes().getValue("DynamicImport-Package") .indexOf("org.slf4j") >= 0); System.out.println(Processor.join( bmaker.getErrors(),"\n")); System.out.println(Processor.join( bmaker.getWarnings(),"\n")); assertTrue(bmaker.getErrors().size() == 0); assertTrue(bmaker.getWarnings().size() == 0); } } bnd-1.50.0/biz.aQute.bndlib/src/test/ProcessorTest.java0000644000175000017500000000337011656076535022600 0ustar drazzibdrazzibpackage test; import junit.framework.*; import aQute.lib.osgi.*; public class ProcessorTest extends TestCase{ public void testPlugins() { } public void testDuplicates() { assertEquals("", Processor.removeDuplicateMarker("~") ); assertTrue( Processor.isDuplicate("abc~")); assertTrue( Processor.isDuplicate("abc~~~~~~~~~")); assertTrue( Processor.isDuplicate("~")); assertFalse( Processor.isDuplicate("")); assertFalse( Processor.isDuplicate("abc")); assertFalse( Processor.isDuplicate("ab~c")); assertFalse( Processor.isDuplicate("~abc")); assertEquals("abc", Processor.removeDuplicateMarker("abc~") ); assertEquals("abc", Processor.removeDuplicateMarker("abc~~~~~~~") ); assertEquals("abc", Processor.removeDuplicateMarker("abc") ); assertEquals("ab~c", Processor.removeDuplicateMarker("ab~c") ); assertEquals("~abc", Processor.removeDuplicateMarker("~abc") ); assertEquals("", Processor.removeDuplicateMarker("") ); assertEquals("", Processor.removeDuplicateMarker("~~~~~~~~~~~~~~") ); } public void appendPathTest() throws Exception { assertEquals("a/b/c", Processor.appendPath("","a/b/c/")); assertEquals("a/b/c", Processor.appendPath("","/a/b/c")); assertEquals("a/b/c", Processor.appendPath("/","/a/b/c/")); assertEquals("a/b/c", Processor.appendPath("a","b/c/")); assertEquals("a/b/c", Processor.appendPath("a","b","c")); assertEquals("a/b/c", Processor.appendPath("a","b","/c/")); assertEquals("a/b/c", Processor.appendPath("/","a","b","/c/")); assertEquals("a/b/c", Processor.appendPath("////////","////a////b///c//")); } } bnd-1.50.0/biz.aQute.bndlib/src/test/resourcesonly/0000755000175000017500000000000011656076535022027 5ustar drazzibdrazzibbnd-1.50.0/biz.aQute.bndlib/src/test/resourcesonly/simple.mf0000755000175000017500000000026511656076535023652 0ustar drazzibdrazzibExport-Package=aQute.bean;special=true, org.objectweb.asm.util, *xml2mif Import-Package=* Bundle-Includes=../../jar, simple.mf, @../../jar/thinlet.jar Private-Package=aQute.lib.aim bnd-1.50.0/biz.aQute.bndlib/src/test/resourcesonly/top.mf0000755000175000017500000000031111656076535023153 0ustar drazzibdrazzib-include=include.mf Export-Package=aQute.bean;special=true, org.objectweb.asm.util, *xml2mif Import-Package=* Bundle-Includes=../../jar, simple.mf, @../../jar/thinlet.jar Private-Package=aQute.lib.aim bnd-1.50.0/biz.aQute.bndlib/src/test/resourcesonly/variables.mf0000755000175000017500000000003111656076535024320 0ustar drazzibdrazzibp=aQute.test Header=${p} bnd-1.50.0/biz.aQute.bndlib/src/test/resourcesonly/include.mf0000755000175000017500000000026511656076535024004 0ustar drazzibdrazzibExport-Package=aQute.bean;special=true, org.objectweb.asm.util, *xml2mif Import-Package=* Bundle-Includes=../../jar, simple.mf, @../../jar/thinlet.jar Private-Package=aQute.lib.aim bnd-1.50.0/biz.aQute.bndlib/src/test/CachingURLResourceHandleTest.java0000644000175000017500000000166211656076535025366 0ustar drazzibdrazzibpackage test; import java.io.File; import java.io.IOException; import junit.framework.TestCase; import aQute.lib.deployer.obr.CachingURLResourceHandle; import aQute.lib.deployer.obr.CachingURLResourceHandle.CachingMode; public class CachingURLResourceHandleTest extends TestCase { File currentDir = new File(System.getProperty("user.dir")); public void testResolveAbsolute() throws IOException { CachingURLResourceHandle handle; File testFile = new File(currentDir, "bnd.bnd").getAbsoluteFile(); String testUrl = testFile.toURI().toURL().toExternalForm(); // Ignore base handle = new CachingURLResourceHandle(testUrl, "http://ignored", null, CachingMode.PreferCache); assertEquals(testUrl, handle.getResolvedUrl().toExternalForm()); // Base may be null handle = new CachingURLResourceHandle(testUrl, null, null, CachingMode.PreferCache); assertEquals(testUrl, handle.getResolvedUrl().toExternalForm()); } } bnd-1.50.0/biz.aQute.bndlib/src/test/MakeTest.java0000644000175000017500000000747111656076535021504 0ustar drazzibdrazzibpackage test; import java.io.*; import java.util.*; import junit.framework.*; import aQute.lib.osgi.*; /** * Tests the make functionality. * * @author aqute * */ public class MakeTest extends TestCase { /** * Test a make plugin */ public void testMakePlugin() throws Exception { Builder b = new Builder(); b.setProperty("Export-Package", "*"); b.setProperty("Include-Resource", "jar/asm.jar.md5"); b.setProperty("-make", "(*).md5;type=md5;file=$1"); b.setProperty("-plugin", "test.make.MD5"); b.addClasspath( new File("jar/osgi.jar")); Jar jar = b.build(); System.out.println(b.getErrors()); System.out.println(b.getWarnings()); assertEquals(0, b.getErrors().size()); assertEquals(0, b.getWarnings().size()); assertNotNull( jar.getResource("asm.jar.md5")); } /** * Check if we can get a resource through the make copy facility. * * @throws Exception */ public void testCopy() throws Exception { Builder bmaker = new Builder(); Properties p = new Properties(); p.setProperty("-resourceonly","true"); p.setProperty("-plugin", "aQute.bnd.make.MakeBnd, aQute.bnd.make.MakeCopy"); p.setProperty("-make", "(*).jar;type=bnd;recipe=bnd/$1.bnd, (*).jar;type=copy;from=jar/$1.jar"); p.setProperty("Include-Resource", "asm.jar,xyz=asm.jar"); bmaker.setProperties(p); Jar jar = bmaker.build(); assertNotNull(jar.getResource("asm.jar")); assertNotNull(jar.getResource("xyz")); report(bmaker); } /** * Check if we can create a JAR recursively * * @throws Exception */ public void testJarInJarInJar() throws Exception { Builder bmaker = new Builder(); Properties p = new Properties(); p.setProperty("-plugin", "aQute.bnd.make.MakeBnd, aQute.bnd.make.MakeCopy"); p.setProperty("-resourceonly","true"); p.setProperty("-make", "(*).jar;type=bnd;recipe=bnd/$1.bnd"); p.setProperty("Include-Resource", "makesondemand.jar"); bmaker.setProperties(p); bmaker.setClasspath( new String[] {"bin"}); Jar jar = bmaker.build(); JarResource resource = (JarResource) jar.getResource("makesondemand.jar"); assertNotNull(resource); jar = resource.getJar(); resource = (JarResource) jar.getResource("ondemand.jar"); assertNotNull(resource); report(bmaker); } /** * Check if we can create a jar on demand through the make * facility with a new name. * * @throws Exception */ public void testComplexOnDemand() throws Exception { Builder bmaker = new Builder(); Properties p = new Properties(); p.setProperty("-resourceonly","true"); p.setProperty("-plugin", "aQute.bnd.make.MakeBnd, aQute.bnd.make.MakeCopy"); p.setProperty("-make", "(*).jar;type=bnd;recipe=bnd/$1.bnd"); p.setProperty("Include-Resource", "www/xyz.jar=ondemand.jar"); bmaker.setProperties(p); bmaker.setClasspath( new String[] {"bin"}); Jar jar = bmaker.build(); Resource resource =jar.getResource("www/xyz.jar"); assertNotNull(resource); assertTrue( resource instanceof JarResource ); report(bmaker); } void report(Processor processor) { System.out.println(); for ( int i=0; i map = Create.map(); map.put("location", "test/eclipse"); map.put("name", "eclipse-test"); er.setProperties(map); System.out.println(er.list("*")); } } bnd-1.50.0/biz.aQute.bndlib/src/test/DSAnnotationTest.java0000644000175000017500000001315111656076535023160 0ustar drazzibdrazzibpackage test; import java.io.*; import org.osgi.service.component.annotations.*; import org.osgi.service.log.*; import aQute.bnd.test.*; import aQute.lib.osgi.*; public class DSAnnotationTest extends BndTestCase { @Component public class Defaults implements Serializable, Runnable { @Activate void open() { } @Deactivate void close() { } @Modified void modified() { } @Reference void setLogService(LogService log) { } void unsetLogService(LogService log) { } void modifiedLogService(LogService log) { } public void run() { // TODO Auto-generated method stub } } @Component(service = Object.class, configurationPolicy = ConfigurationPolicy.IGNORE, enabled = false, factory = "factory", immediate = false, name = "name", property = { "a=1", "a=2", "b=3" }, properties = "resource.props", servicefactory = false) public class Explicit implements Serializable, Runnable { @Activate void open() { } @Deactivate void close() { } @Modified void changed() { } @Reference(cardinality = ReferenceCardinality.AT_LEAST_ONE, name = "foo", policy = ReferencePolicy.DYNAMIC, service = Object.class, target = "(objectclass=*)", unbind = "unset" /* * , * modified */) void setLogService( LogService log) { } void unset(Object log) { } void unset() { } void unsetLogService(LogService log) { } void modifiedLogService(Object log) { } public void run() { // TODO Auto-generated method stub } } public void testBasic() throws Exception { Builder b = new Builder(); b.setProperty("-dsannotations", "test.*"); b.setProperty("Private-Package", "test"); b.addClasspath(new File("bin")); Jar jar = b.build(); assertOk(b); { // // Test all the defaults // Resource r = jar.getResource("OSGI-INF/test.DSAnnotationTest$Defaults.xml"); System.out.println(Processor.join(jar.getResources().keySet(),"\n")); assertNotNull(r); r.write(System.out); XmlTester xt = new XmlTester(r.openInputStream(), "scr", "http://www.osgi.org/xmlns/scr/1.1.0"); // Test the defaults xt.assertAttribute("test.DSAnnotationTest$Defaults", "scr:component/implementation/@class"); // Default must be the implementation class xt.assertAttribute("test.DSAnnotationTest$Defaults", "scr:component/@name"); xt.assertAttribute("", "scr:component/@configuration-policy"); xt.assertAttribute("", "scr:component/@immediate"); xt.assertAttribute("", "scr:component/@enabled"); xt.assertAttribute("", "scr:component/@factory"); xt.assertAttribute("", "scr:component/@servicefactory"); xt.assertAttribute("open", "scr:component/@activate"); xt.assertAttribute("close", "scr:component/@deactivate"); xt.assertAttribute("modified", "scr:component/@modified"); xt.assertAttribute("java.io.Serializable", "scr:component/service/provide[1]/@interface"); xt.assertAttribute("java.lang.Runnable", "scr:component/service/provide[2]/@interface"); xt.assertAttribute("0", "count(scr:component/properties)"); xt.assertAttribute("0", "count(scr:component/property)"); xt.assertAttribute("", "scr:component/reference[1]/@target"); xt.assertAttribute("setLogService", "scr:component/reference[1]/@bind"); xt.assertAttribute("unsetLogService", "scr:component/reference[1]/@unbind"); xt.assertAttribute("", "scr:component/reference[1]/@cardinality"); xt.assertAttribute("", "scr:component/reference[1]/@policy"); xt.assertAttribute("", "scr:component/reference[1]/@target"); } { // // Test explicit // Resource r = jar.getResource("OSGI-INF/test.DSAnnotationTest$Explicit.xml"); assertNotNull(r); r.write(System.out); XmlTester xt = new XmlTester(r.openInputStream(), "scr", "http://www.osgi.org/xmlns/scr/1.1.0"); // Test the defaults xt.assertAttribute("test.DSAnnotationTest$Explicit", "scr:component/implementation/@class"); // Default must be the implementation class xt.assertAttribute("test.DSAnnotationTest$Explicit", "scr:component/@name"); xt.assertAttribute("ignore", "scr:component/@configuration-policy"); xt.assertAttribute("false", "scr:component/@immediate"); xt.assertAttribute("false", "scr:component/@enabled"); xt.assertAttribute("factory", "scr:component/@factory"); xt.assertAttribute("false", "scr:component/@servicefactory"); xt.assertAttribute("open", "scr:component/@activate"); xt.assertAttribute("close", "scr:component/@deactivate"); xt.assertAttribute("changed", "scr:component/@modified"); xt.assertAttribute("java.lang.Object", "scr:component/service/provide[1]/@interface"); xt.assertAttribute("1", "count(scr:component/service/provide)"); xt.assertAttribute("1", "count(scr:component/properties)"); xt.assertAttribute("2", "count(scr:component/property)"); xt.assertAttribute("(objectclass=*)", "scr:component/reference[1]/@target"); xt.assertAttribute("setLogService", "scr:component/reference[1]/@bind"); xt.assertAttribute("unset", "scr:component/reference[1]/@unbind"); xt.assertAttribute("modifiedLogService", "scr:component/reference[1]/@modified"); xt.assertAttribute("1..n", "scr:component/reference[1]/@cardinality"); xt.assertAttribute("dynamic", "scr:component/reference[1]/@policy"); xt.assertAttribute("(objectclass=*)", "scr:component/reference[1]/@target"); xt.assertAttribute("2", "count(scr:component/property)"); xt.assertAttribute("1", "count(scr:component/properties)"); xt.assertAttribute("resource.props", "scr:component/properties[1]/@entry"); } } } bnd-1.50.0/biz.aQute.bndlib/src/test/MergeTest.java0000644000175000017500000000402411656076535021655 0ustar drazzibdrazzibpackage test; import java.io.*; import java.util.*; import junit.framework.*; import aQute.lib.osgi.*; public class MergeTest extends TestCase { public void testFirst() throws Exception { testMerge("first", new String[] { "A", "C" }, new String[] { "B" }, "first", 0, 0); } public void testMergeFirst() throws Exception { testMerge("merge-first", new String[] { "A", "B", "C" }, new String[] { "" }, "first", 0, 0); } public void testDefault() throws Exception { testMerge(null, new String[] { "A", "B", "C" }, new String[] { }, "first", 0, 1); } public void testMergeLast() throws Exception { testMerge("merge-last", new String[] { "A", "B", "C" }, new String[] { "" }, "last", 0, 0); } public void testError() throws Exception { testMerge("error", null, null,null, 1, 0); } void testMerge(String type, String[] in, String[] out, String c, int errors, int warnings) throws Exception { Builder b = new Builder(); b.setClasspath(new File[] { new File("src/test/split/split-a.jar"), new File("src/test/split/split-b.jar") }); Properties p = new Properties(); if (type != null) p.put("Export-Package", "test.split;-split-package:=" + type); else p.put("Export-Package", "test.split"); p.put("Import-Package", ""); b.setProperties(p); Jar jar = b.build(); System.out.println("Errors :" + b.getErrors()); System.out.println("Warnings :" + b.getWarnings()); assertEquals(errors, b.getErrors().size()); assertEquals(warnings, b.getWarnings().size()); if (errors != 0) return; for (int i = 0; in != null && i < in.length; i++) assertNotNull("Contains " + in[i], jar.getResource("test/split/" + in[i])); for (int i = 0; out != null && i < out.length; i++) assertNull("Does not contain " + out[i], jar .getResource("test/split/" + out[i])); Resource r = jar.getResource("test/split/C"); InputStream is = r.openInputStream(); BufferedReader dis = new BufferedReader( new InputStreamReader(is)); String s = dis.readLine(); assertEquals(s, c); } } bnd-1.50.0/biz.aQute.bndlib/src/test/repo/0000755000175000017500000000000011656076535020060 5ustar drazzibdrazzibbnd-1.50.0/biz.aQute.bndlib/src/test/repo/ee.minimum/0000755000175000017500000000000011656076535022123 5ustar drazzibdrazzibbnd-1.50.0/biz.aQute.bndlib/src/test/repo/org.osgi.impl.service.cm/0000755000175000017500000000000011656076535024604 5ustar drazzibdrazzibbnd-1.50.0/biz.aQute.bndlib/src/test/repo/osgi/0000755000175000017500000000000011656076535021021 5ustar drazzibdrazzibbnd-1.50.0/biz.aQute.bndlib/src/test/repo/org.osgi.impl.service.io/0000755000175000017500000000000011656076535024614 5ustar drazzibdrazzibbnd-1.50.0/biz.aQute.bndlib/src/test/NativeHeader.java0000755000175000017500000000331611656076535022323 0ustar drazzibdrazzibpackage test; import java.util.*; import junit.framework.*; import aQute.lib.osgi.*; public class NativeHeader extends TestCase { public void testFunnyHeader() throws Exception { Verifier v = new Verifier(); v.doNative("org/osgi/test/cases/framework/fragments/tb8/linux_x86/libNative.so; osname=Linux; processor=x86; osversion=\"(1000,10000]\","); assertBad(v, "name"); } public void testWildcardNotAtEnd() throws Exception { Verifier v = new Verifier(); v.doNative("x.so;osname=win32,*,x.dll"); assertBad(v, "may only END in wildcard"); } public void testWildcard() throws Exception { Verifier v = new Verifier(); v.doNative("x.so ;y.so;osname=Linux;processor=amd64,*"); assertOk(v); } public void testSimple() throws Exception { Verifier v = new Verifier(); v.doNative("\rnative/libclib_jiio.so ;\r" + "native/libmlib_jai.so;\r" + "osname=Linux ;\r" + "processor=amd64\r"); assertOk(v); } void assertOk(Processor v) { System.err.println(v.getWarnings()); System.err.println(v.getErrors()); assertEquals(0, v.getErrors().size()); assertEquals(0, v.getWarnings().size()); } void assertBad(Processor v, String ok) { assertEmptyAfterRemove(v.getErrors(), ok); assertEmptyAfterRemove(v.getWarnings(), ok); } private void assertEmptyAfterRemove(List errors, String ok) { for ( String s: errors ) { if ( s.indexOf(ok)<0) fail("Found error/warning that can not be removed: " + s + " : " + ok); } } } bnd-1.50.0/biz.aQute.bndlib/src/test/GlobTest.java0000644000175000017500000000174511656076535021510 0ustar drazzibdrazzibpackage test; import aQute.libg.glob.Glob; import junit.framework.TestCase; public class GlobTest extends TestCase { public void testSimple() { Glob glob = new Glob("*foo*"); assertTrue(glob.matcher("foo").find()); assertTrue(glob.matcher("food").find()); assertTrue(glob.matcher("Xfoo").find()); assertTrue(glob.matcher("XfooY").find()); assertFalse(glob.matcher("ood").find()); } public void testUrl() { Glob glob; glob = new Glob("http://www.example.com/*"); assertTrue(glob.matcher("http://www.example.com/repository.xml").find()); assertFalse(glob.matcher("https://www.example.com/repository.xml").find()); glob = new Glob("http://*.example.com/*"); assertTrue(glob.matcher("http://www.example.com/repository.xml").find()); assertTrue(glob.matcher("http://foo.example.com/repository.xml").find()); assertFalse(glob.matcher("http://example.com/repository.xml").find()); assertFalse(glob.matcher("http://foo.exampleXcom/repository.xml").find()); } } bnd-1.50.0/biz.aQute.bndlib/src/test/ClasspathTest.java0000755000175000017500000000400011656076535022535 0ustar drazzibdrazzibpackage test; import java.io.*; import java.util.*; import java.util.jar.*; import junit.framework.*; import aQute.lib.osgi.*; public class ClasspathTest extends TestCase { /** * Test if we can refer to the jars on the classpath by their file name ( * ignoring the path) * * @throws Exception */ public void testBundleClasspath() throws Exception { Builder b = new Builder(); b.setProperty("Include-Resource", "bin=bin"); b.setProperty("Bundle-Classpath", "bin"); Jar jar = b.build(); assertNotNull(jar.getResource("bin/aQute/lib/osgi/Verifier.class")); // from // test.jar } /** * Test if we can refer to the jars on the classpath by their file name ( * ignoring the path) * * @throws Exception */ public void testFindJarOnClasspath() throws Exception { Properties p = new Properties(); p.put("Include-Resource", "tb1.jar, @test.jar"); Builder b = new Builder(); b.setClasspath(new String[] { "src", "src/test/test.jar", "src/test/tb1.jar" }); b.setProperties(p); Jar jar = b.build(); assertNotNull(jar.getResource("aQute/lib/aim/AIM.class")); // from // test.jar assertNotNull(jar.getResource("tb1.jar")); } /** * Test if we can use URLs on the classpath * * @throws Exception */ public void testSimple() throws Exception { Properties p = new Properties(); p.put("-classpath", new File("jar/osgi.jar").toURI().toURL().toString()); p.put("Export-Package", "org.osgi.service.event"); p.put("Private-Package", "test.refer"); Builder b = new Builder(); b.setClasspath(new String[] { "bin" }); b.setProperties(p); Jar jar = b.build(); Manifest m = jar.getManifest(); String importPackage = m.getMainAttributes().getValue("Import-Package"); assertTrue(importPackage.contains("org.osgi.framework;version=\"[1.3,2)\"")); assertTrue(importPackage.contains("org.osgi.service.event;version=\"[1.0,2)\"")); } } bnd-1.50.0/biz.aQute.bndlib/src/test/MetatypeTest.java0000644000175000017500000010037511656076535022414 0ustar drazzibdrazzibpackage test; import java.io.*; import java.lang.reflect.*; import java.net.*; import java.util.*; import java.util.regex.*; import javax.xml.namespace.*; import javax.xml.parsers.*; import javax.xml.xpath.*; import junit.framework.*; import org.w3c.dom.*; import aQute.bnd.annotation.metatype.*; import aQute.lib.io.*; import aQute.lib.osgi.*; import aQute.libg.generics.*; public class MetatypeTest extends TestCase { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); XPathFactory xpathf = XPathFactory.newInstance(); XPath xpath = xpathf.newXPath(); DocumentBuilder db; { try { dbf.setNamespaceAware(true); db = dbf.newDocumentBuilder(); xpath.setNamespaceContext(new NamespaceContext() { public Iterator getPrefixes(String namespaceURI) { return Arrays.asList("md").iterator(); } public String getPrefix(String namespaceURI) { return "md"; } public String getNamespaceURI(String prefix) { return "http://www.osgi.org/xmlns/metatype/v1.1.0"; } }); } catch (ParserConfigurationException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public void testOptions() { } /** * Test method naming options with '.' and reserved names */ @Meta.OCD public static interface Naming { String secret(); String _secret(); // .secret String __secret(); // _secret String $new(); // new String $$new(); // $new String a_b_c(); // a.b.c String a__b__c(); // a_b_c String _a__b(); // .a_b String $$$$$$$$a__b(); // $$$$a_b String $$$$$$$$a_b(); // $$$$a.b String a$(); // a String a$$(); // a$ String a$$$(); // a$ String a$$$$(); // a$$ String a$$_$$(); // a$.$ String a$$__$$(); // a$_$ String a_$_(); // a.. @Meta.AD(id="secret") String xsecret(); @Meta.AD(id=".secret") String x_secret(); @Meta.AD(id="_secret") String x__secret(); // _secret @Meta.AD(id="new") String x$new(); // new @Meta.AD(id="$new") String x$$new(); // $new @Meta.AD(id="a.b.c") String xa_b_c(); // a.b.c @Meta.AD(id="a_b_c") String xa__b__c(); // a_b_c @Meta.AD(id=".a_b") String x_a__b(); // .a_b @Meta.AD(id="$$$$a_b") String x$$$$$$$$a__b(); // $$$$a_b @Meta.AD(id="$$$$a.b") String x$$$$$$$$a_b(); // $$$$a.b @Meta.AD(id="a") String xa$(); // a @Meta.AD(id="a$") String xa$$(); // a$ @Meta.AD(id="a$") String xa$$$(); // a$ @Meta.AD(id="a$$") String xa$$$$(); // a$$ @Meta.AD(id="a$.$") String xa$$_$$(); // a$.$ @Meta.AD(id="a$_$") String xa$$__$$(); // a$_$ @Meta.AD(id="a..") String xa_$_(); // a.. String noid(); @Meta.AD(id=Meta.NULL) String nullid(); } public void testNaming() throws Exception { Map map = Create.map(); map.put("_secret", "_secret"); map.put("_secret", "_secret"); map.put(".secret", ".secret"); map.put("$new", "$new"); map.put("new", "new"); map.put("secret", "secret"); map.put("a_b_c", "a_b_c"); map.put("a.b.c", "a.b.c"); map.put(".a_b", ".a_b"); map.put("$$$$a_b", "$$$$a_b"); map.put("$$$$a.b", "$$$$a.b"); map.put("a", "a"); map.put("a$", "a$"); map.put("a$$", "a$$"); map.put("a$.$", "a$.$"); map.put("a$_$", "a$_$"); map.put("a..", "a.."); map.put("noid", "noid"); map.put("nullid", "nullid"); Naming trt = Configurable.createConfigurable(Naming.class, map); // By name assertEquals( "secret", trt.secret() ); assertEquals( "_secret", trt.__secret() ); assertEquals( ".secret", trt._secret() ); assertEquals( "new", trt.$new() ); assertEquals( "$new", trt.$$new() ); assertEquals( "a.b.c", trt.a_b_c() ); assertEquals( "a_b_c", trt.a__b__c() ); assertEquals( ".a_b", trt._a__b() ); assertEquals( "$$$$a.b", trt.$$$$$$$$a_b() ); assertEquals( "$$$$a_b", trt.$$$$$$$$a__b() ); assertEquals( "a", trt.a$() ); assertEquals( "a$", trt.a$$() ); assertEquals( "a$", trt.a$$$() ); assertEquals( "a$.$", trt.a$$_$$() ); assertEquals( "a$_$", trt.a$$__$$() ); assertEquals( "a..", trt.a_$_() ); assertEquals( "noid", trt.noid() ); assertEquals( "nullid", trt.nullid() ); // By AD assertEquals( "secret", trt.xsecret() ); assertEquals( "_secret", trt.x__secret() ); assertEquals( ".secret", trt.x_secret() ); assertEquals( "new", trt.x$new() ); assertEquals( "$new", trt.x$$new() ); assertEquals( "a.b.c", trt.xa_b_c() ); assertEquals( "a_b_c", trt.xa__b__c() ); assertEquals( ".a_b", trt.x_a__b() ); assertEquals( "$$$$a.b", trt.x$$$$$$$$a_b() ); assertEquals( "$$$$a_b", trt.x$$$$$$$$a__b() ); assertEquals( "a", trt.xa$() ); assertEquals( "a$", trt.xa$$() ); assertEquals( "a$", trt.xa$$$() ); assertEquals( "a$.$", trt.xa$$_$$() ); Builder b = new Builder(); b.addClasspath(new File("bin")); b.setProperty("Export-Package", "test"); b.setProperty("-metatype", "*"); b.build(); assertEquals(0, b.getErrors().size()); assertEquals(0, b.getWarnings().size()); Resource r = b.getJar().getResource("OSGI-INF/metatype/test.MetatypeTest$Naming.xml"); IO.copy(r.openInputStream(), System.out); Document d = db.parse(r.openInputStream(),"UTF-8"); assertEquals("http://www.osgi.org/xmlns/metatype/v1.1.0", d.getDocumentElement() .getNamespaceURI()); } /** * Test the special conversions. */ public static class MyList extends ArrayList { private static final long serialVersionUID = 1L; public MyList() { System.out.println("Constr"); } } interface CollectionsTest { Collection collection(); List list(); Set set(); Queue queue(); // Deque deque(); Stack stack(); ArrayList arrayList(); LinkedList linkedList(); LinkedHashSet linkedHashSet(); MyList myList(); } public void testCollections() throws Exception { CollectionsTest trt = set( CollectionsTest.class, new int[]{1,2,3}); List source = Arrays.asList("1","2","3"); assertTrue( trt.collection() instanceof Collection); assertEqualList( source, trt.collection()); assertTrue( trt.list() instanceof List); assertEqualList( source, trt.list()); assertTrue( trt.set() instanceof Set); assertEqualList( source, trt.set()); assertTrue( trt.queue() instanceof Queue); assertEqualList(source, trt.queue()); // assertTrue( trt.deque() instanceof Deque); // assertEqualList( source, trt.deque()); assertTrue( trt.stack() instanceof Stack); assertEqualList(source, trt.stack()); assertTrue( trt.arrayList() instanceof ArrayList); assertEqualList( source, trt.arrayList()); assertTrue( trt.linkedList() instanceof LinkedList); assertEqualList( source, trt.linkedList()); assertTrue( trt.linkedHashSet() instanceof LinkedHashSet); assertEqualList( source, trt.linkedHashSet()); assertTrue( trt.myList() instanceof MyList); assertEqualList( source, trt.myList()); } private void assertEqualList(List a, Collection b) { if ( a.size() == b.size()) { for ( Object x : a ) { if ( !b.contains(x)) throw new AssertionFailedError("expected:<" +a + "> but was: <"+ b +">"); } return; } throw new AssertionFailedError("expected:<" +a + "> but was: <"+ b +">"); } /** * Test the special conversions. */ interface SpecialConversions { enum X { A, B, C } X enumv(); Pattern pattern(); Class clazz(); URI constructor(); } public void testSpecialConversions() throws URISyntaxException { Properties p = new Properties(); p.put("enumv", "A"); p.put("pattern", ".*"); p.put("clazz", "java.lang.Object"); p.put("constructor", "http://www.aQute.biz"); SpecialConversions trt = Configurable.createConfigurable(SpecialConversions.class, (Map) p); assertEquals(SpecialConversions.X.A, trt.enumv()); assertEquals(".*", trt.pattern().pattern()); assertEquals(Object.class, trt.clazz()); assertEquals(new URI("http://www.aQute.biz"), trt.constructor()); } /** * Test the converter. * * @throws URISyntaxException */ public void testConverter() throws URISyntaxException { { // Test collections as value TestReturnTypes trt = set(TestReturnTypes.class,Arrays.asList(55)); assertTrue(Arrays.equals(new boolean[] { true }, trt.rpaBoolean())); assertTrue(Arrays.equals(new byte[] { 55 }, trt.rpaByte())); assertTrue(Arrays.equals(new short[] { 55 }, trt.rpaShort())); assertTrue(Arrays.equals(new int[] { 55 }, trt.rpaInt())); assertTrue(Arrays.equals(new long[] { 55 }, trt.rpaLong())); assertTrue(Arrays.equals(new float[] { 55 }, trt.rpaFloat())); assertTrue(Arrays.equals(new double[] { 55 }, trt.rpaDouble())); assertEquals(Arrays.asList(true), trt.rBooleans()); assertEquals(Arrays.asList(new Byte((byte) 55)), trt.rBytes()); assertEquals(Arrays.asList(new Short((short) 55)), trt.rShorts()); assertEquals(Arrays.asList(new Integer(55)), trt.rInts()); assertEquals(Arrays.asList(new Long(55L)), trt.rLongs()); assertEquals(Arrays.asList(new Float(55F)), trt.rFloats()); assertEquals(Arrays.asList(new Double(55D)), trt.rDoubles()); assertEquals(Arrays.asList("55"), trt.rStrings()); assertEquals(Arrays.asList(new URI("55")), trt.rURIs()); assertTrue(Arrays.equals(new Boolean[] { true }, trt.raBoolean())); assertTrue(Arrays.equals(new Byte[] { 55 }, trt.raByte())); assertTrue(Arrays.equals(new Short[] { 55 }, trt.raShort())); assertTrue(Arrays.equals(new Integer[] { 55 }, trt.raInt())); assertTrue(Arrays.equals(new Long[] { 55L }, trt.raLong())); assertTrue(Arrays.equals(new Float[] { 55F }, trt.raFloat())); assertTrue(Arrays.equals(new Double[] { 55D }, trt.raDouble())); assertTrue(Arrays.equals(new String[] { "55" }, trt.raString())); assertTrue(Arrays.equals(new URI[] { new URI("55") }, trt.raURI())); } { // Test primitive arrays as value TestReturnTypes trt = set(TestReturnTypes.class,new int[] { 55 }); assertTrue(Arrays.equals(new boolean[] { true }, trt.rpaBoolean())); assertTrue(Arrays.equals(new byte[] { 55 }, trt.rpaByte())); assertTrue(Arrays.equals(new short[] { 55 }, trt.rpaShort())); assertTrue(Arrays.equals(new int[] { 55 }, trt.rpaInt())); assertTrue(Arrays.equals(new long[] { 55 }, trt.rpaLong())); assertTrue(Arrays.equals(new float[] { 55 }, trt.rpaFloat())); assertTrue(Arrays.equals(new double[] { 55 }, trt.rpaDouble())); assertEquals(Arrays.asList(true), trt.rBooleans()); assertEquals(Arrays.asList(new Byte((byte) 55)), trt.rBytes()); assertEquals(Arrays.asList(new Short((short) 55)), trt.rShorts()); assertEquals(Arrays.asList(new Integer(55)), trt.rInts()); assertEquals(Arrays.asList(new Long(55L)), trt.rLongs()); assertEquals(Arrays.asList(new Float(55F)), trt.rFloats()); assertEquals(Arrays.asList(new Double(55D)), trt.rDoubles()); assertEquals(Arrays.asList("55"), trt.rStrings()); assertEquals(Arrays.asList(new URI("55")), trt.rURIs()); assertTrue(Arrays.equals(new Boolean[] { true }, trt.raBoolean())); assertTrue(Arrays.equals(new Byte[] { 55 }, trt.raByte())); assertTrue(Arrays.equals(new Short[] { 55 }, trt.raShort())); assertTrue(Arrays.equals(new Integer[] { 55 }, trt.raInt())); assertTrue(Arrays.equals(new Long[] { 55L }, trt.raLong())); assertTrue(Arrays.equals(new Float[] { 55F }, trt.raFloat())); assertTrue(Arrays.equals(new Double[] { 55D }, trt.raDouble())); assertTrue(Arrays.equals(new String[] { "55" }, trt.raString())); assertTrue(Arrays.equals(new URI[] { new URI("55") }, trt.raURI())); } { // Test single value TestReturnTypes trt = set(TestReturnTypes.class,55); assertEquals(true, trt.rpBoolean()); assertEquals(55, trt.rpByte()); assertEquals(55, trt.rpShort()); assertEquals(55, trt.rpInt()); assertEquals(55L, trt.rpLong()); assertEquals(55.0D, trt.rpDouble()); assertEquals(55.0F, trt.rpFloat()); assertEquals((Boolean) true, trt.rBoolean()); assertEquals(new Byte((byte) 55), trt.rByte()); assertEquals(new Short((short) 55), trt.rShort()); assertEquals(new Integer(55), trt.rInt()); assertEquals(new Long(55L), trt.rLong()); assertEquals(new Float(55F), trt.rFloat()); assertEquals(new Double(55), trt.rDouble()); assertEquals("55", trt.rString()); assertEquals(new URI("55"), trt.rURI()); assertTrue(Arrays.equals(new boolean[] { true }, trt.rpaBoolean())); assertTrue(Arrays.equals(new byte[] { 55 }, trt.rpaByte())); assertTrue(Arrays.equals(new short[] { 55 }, trt.rpaShort())); assertTrue(Arrays.equals(new int[] { 55 }, trt.rpaInt())); assertTrue(Arrays.equals(new long[] { 55 }, trt.rpaLong())); assertTrue(Arrays.equals(new float[] { 55 }, trt.rpaFloat())); assertTrue(Arrays.equals(new double[] { 55 }, trt.rpaDouble())); assertEquals(Arrays.asList(true), trt.rBooleans()); assertEquals(Arrays.asList(new Byte((byte) 55)), trt.rBytes()); assertEquals(Arrays.asList(new Short((short) 55)), trt.rShorts()); assertEquals(Arrays.asList(new Integer(55)), trt.rInts()); assertEquals(Arrays.asList(new Long(55L)), trt.rLongs()); assertEquals(Arrays.asList(new Float(55F)), trt.rFloats()); assertEquals(Arrays.asList(new Double(55D)), trt.rDoubles()); assertEquals(Arrays.asList("55"), trt.rStrings()); assertEquals(Arrays.asList(new URI("55")), trt.rURIs()); assertTrue(Arrays.equals(new Boolean[] { true }, trt.raBoolean())); assertTrue(Arrays.equals(new Byte[] { 55 }, trt.raByte())); assertTrue(Arrays.equals(new Short[] { 55 }, trt.raShort())); assertTrue(Arrays.equals(new Integer[] { 55 }, trt.raInt())); assertTrue(Arrays.equals(new Long[] { 55L }, trt.raLong())); assertTrue(Arrays.equals(new Float[] { 55F }, trt.raFloat())); assertTrue(Arrays.equals(new Double[] { 55D }, trt.raDouble())); assertTrue(Arrays.equals(new String[] { "55" }, trt.raString())); assertTrue(Arrays.equals(new URI[] { new URI("55") }, trt.raURI())); } } T set(Class interf, Object value) { Properties p = new Properties(); Method ms[] = interf.getMethods(); Set failed = new HashSet(); for (Method m : ms) { p.put(m.getName(), value); } return Configurable.createConfigurable(interf, (Map) p); } /** * Test enum handling */ @Meta.OCD public static interface Enums { enum X { requireConfiguration, optionalConfiguration, ignoreConfiguration }; X r(); X i(); X o(); } public void testEnum() throws Exception { Builder b = new Builder(); b.addClasspath(new File("bin")); b.setProperty("Export-Package", "test"); b.setProperty("-metatype", "*"); b.build(); assertEquals(0, b.getErrors().size()); assertEquals(0, b.getWarnings().size()); Resource r = b.getJar().getResource("OSGI-INF/metatype/test.MetatypeTest$Enums.xml"); IO.copy(r.openInputStream(), System.out); Document d = db.parse(r.openInputStream()); assertEquals("http://www.osgi.org/xmlns/metatype/v1.1.0", d.getDocumentElement() .getNamespaceURI()); Properties p = new Properties(); p.setProperty("r", "requireConfiguration"); p.setProperty("i", "ignoreConfiguration"); p.setProperty("o", "optionalConfiguration"); Enums enums = Configurable.createConfigurable(Enums.class, (Map) p); assertEquals(Enums.X.requireConfiguration, enums.r()); assertEquals(Enums.X.ignoreConfiguration, enums.i()); assertEquals(Enums.X.optionalConfiguration, enums.o()); } /** * Test the OCD settings */ @Meta.OCD() public static interface OCDEmpty { } @Meta.OCD(description = "description") public static interface OCDDescription { } @Meta.OCD() public static interface OCDDesignatePidOnly { } @Meta.OCD(factory = true) public static interface OCDDesignatePidFactory { } @Meta.OCD(id = "id") public static interface OCDId { } @Meta.OCD(id = "id") public static interface OCDIdWithPid { } @Meta.OCD(localization = "localization") public static interface OCDLocalization { } @Meta.OCD(name = "name") public static interface OCDName { } public void testOCD() throws Exception { Builder b = new Builder(); b.addClasspath(new File("bin")); b.setProperty("Export-Package", "test"); b.setProperty("-metatype", "*"); b.build(); assertEquals(0, b.getErrors().size()); assertEquals(0, b.getWarnings().size()); System.out.println(b.getJar().getResources().keySet()); assertOCD(b, "test.MetatypeTest$OCDEmpty", "test.MetatypeTest$OCDEmpty", "Metatype test OCDEmpty", null, "test.MetatypeTest$OCDEmpty", false, null); assertOCD(b, "test.MetatypeTest$OCDName", "test.MetatypeTest$OCDName", "name", null, "test.MetatypeTest$OCDName", false, null); assertOCD(b, "test.MetatypeTest$OCDDescription", "test.MetatypeTest$OCDDescription", "Metatype test OCDDescription", "description", "test.MetatypeTest$OCDDescription", false, null); assertOCD(b, "test.MetatypeTest$OCDDesignatePidOnly", "test.MetatypeTest$OCDDesignatePidOnly", "Metatype test OCDDesignate pid only", null, "test.MetatypeTest$OCDDesignatePidOnly", false, null); assertOCD(b, "test.MetatypeTest$OCDDesignatePidFactory", "test.MetatypeTest$OCDDesignatePidFactory", "Metatype test OCDDesignate pid factory", null, "test.MetatypeTest$OCDDesignatePidFactory", true, null); assertOCD(b, "test.MetatypeTest$OCDId", "id", "Metatype test OCDId", null, "id", false, null); assertOCD(b, "test.MetatypeTest$OCDIdWithPid", "id", "Metatype test OCDId with pid", null, "id", false, null); assertOCD(b, "test.MetatypeTest$OCDLocalization", "test.MetatypeTest$OCDLocalization", "Metatype test OCDLocalization", null, "test.MetatypeTest$OCDLocalization", false, "localization"); } void assertOCD(Builder b, String cname, String id, String name, String description, String designate, boolean factory, String localization) throws Exception { Resource r = b.getJar().getResource("OSGI-INF/metatype/" + cname + ".xml"); assertNotNull(r); IO.copy(r.openInputStream(), System.out); Document d = db.parse(r.openInputStream()); assertEquals(id, xpath.evaluate("//OCD/@id", d, XPathConstants.STRING)); assertEquals(name, xpath.evaluate("//OCD/@name", d, XPathConstants.STRING)); assertEquals(localization == null ? cname : localization, xpath.evaluate("//OCD/@localization", d, XPathConstants.STRING)); assertEquals(description == null ? "" : description, xpath.evaluate("//OCD/@description", d, XPathConstants.STRING)); if (designate == null) { assertEquals(id, xpath.evaluate("//Designate/@pid", d, XPathConstants.STRING)); if (factory) assertEquals(id, xpath.evaluate("//Designate/@factoryPid", d, XPathConstants.STRING)); } else { assertEquals(designate, xpath.evaluate("//Designate/@pid", d, XPathConstants.STRING)); if (factory) assertEquals(designate, xpath.evaluate("//Designate/@factoryPid", d, XPathConstants.STRING)); } assertEquals(id, xpath.evaluate("//Object/@ocdref", d, XPathConstants.STRING)); } /** * Test the AD settings. */ @Meta.OCD(description = "advariations") public static interface TestAD { @Meta.AD String noSettings(); @Meta.AD(id = "id") String withId(); @Meta.AD(name = "name") String withName(); @Meta.AD(max = "1") String withMax(); @Meta.AD(min = "-1") String withMin(); @Meta.AD(deflt = "deflt") String withDefault(); @Meta.AD(cardinality = 0) String[] withC0(); @Meta.AD(cardinality = 1) String[] withC1(); @Meta.AD(cardinality = -1) Collection withC_1(); @Meta.AD(cardinality = -1) String[] withC_1ButArray(); @Meta.AD(cardinality = 1) Collection withC1ButCollection(); @Meta.AD(type = Meta.Type.String) int withInt(); @Meta.AD(type = Meta.Type.Integer) String withString(); @Meta.AD(description = "description") String a(); @Meta.AD(optionValues = { "a", "b" }) String valuesOnly(); @Meta.AD(optionValues = { "a", "b" }, optionLabels = { "A", "B" }) String labelsAndValues(); @Meta.AD(required = true) String required(); @Meta.AD(required = false) String notRequired(); } public void testAD() throws Exception { Builder b = new Builder(); b.addClasspath(new File("bin")); b.setProperty("Export-Package", "test"); b.setProperty("-metatype", "*"); b.build(); Resource r = b.getJar().getResource("OSGI-INF/metatype/test.MetatypeTest$TestAD.xml"); assertEquals(0, b.getErrors().size()); assertEquals(0, b.getWarnings().size()); System.out.println(b.getJar().getResources().keySet()); assertNotNull(r); IO.copy(r.openInputStream(), System.out); Document d = db.parse(r.openInputStream()); assertAD(d, "noSettings", "No settings", "noSettings", null, null, null, 0, "String", null, null, null); assertAD(d, "withId", "With id", "id", null, null, null, 0, "String", null, null, null); assertAD(d, "name", "name", "withName", null, null, null, 0, "String", null, null, null); assertAD(d, "withMax", "With max", "withMax", null, "1", null, 0, "String", null, null, null); assertAD(d, "withMin", "With min", "withMin", "-1", null, null, 0, "String", null, null, null); assertAD(d, "withC1", "With c1", "withC1", null, null, null, 1, "String", null, null, null); assertAD(d, "withC0", "With c0", "withC0", null, null, null, 2147483647, "String", null, null, null); assertAD(d, "withC_1", "With c 1", "withC.1", null, null, null, -1, "String", null, null, null); assertAD(d, "withC_1ButArray", "With c 1 but array", "withC.1ButArray", null, null, null, -1, "String", null, null, null); assertAD(d, "withC1ButCollection", "With c1 but collection", "withC1ButCollection", null, null, null, 1, "String", null, null, null); assertAD(d, "withInt", "With int", "withInt", null, null, null, 0, "String", null, null, null); assertAD(d, "withString", "With string", "withString", null, null, null, 0, "Integer", null, null, null); assertAD(d, "a", "A", "a", null, null, null, 0, "String", "description", null, null); assertAD(d, "valuesOnly", "Values only", "valuesOnly", null, null, null, 0, "String", null, new String[] { "a", "b" }, new String[] { "a", "b" }); assertAD(d, "labelsAndValues", "Labels and values", "labelsAndValues", null, null, null, 0, "String", null, new String[] { "a", "b" }, new String[] { "A", "A" }); } void assertAD(Document d, String mname, String name, String id, String min, String max, String deflt, int cardinality, String type, String description, String[] optionvalues, String optionLabels[]) throws XPathExpressionException { assertEquals(name, xpath.evaluate("//OCD/AD[@id='" + id + "']/@name", d, XPathConstants.STRING)); assertEquals(id, xpath.evaluate("//OCD/AD[@id='" + id + "']/@id", d, XPathConstants.STRING)); assertEquals(min == null ? "" : min, xpath.evaluate("//OCD/AD[@id='" + id + "']/@min", d, XPathConstants.STRING)); assertEquals(max == null ? "" : max, xpath.evaluate("//OCD/AD[@id='" + id + "']/@max", d, XPathConstants.STRING)); assertEquals(deflt == null ? "" : deflt, xpath.evaluate("//OCD/AD[@id='" + id + "']/@deflt", d, XPathConstants.STRING)); assertEquals(cardinality + "", xpath.evaluate("//OCD/AD[@id='" + id + "']/@cardinality", d, XPathConstants.STRING)); assertEquals(type, xpath.evaluate("//OCD/AD[@id='" + id + "']/@type", d, XPathConstants.STRING)); assertEquals(description == null ? "" : description, xpath.evaluate("//OCD/AD[@id='" + id + "']/@description", d, XPathConstants.STRING)); } /** * Test all the return types. */ @Meta.OCD(description = "simple", name = "TestSimple") public static interface TestReturnTypes { boolean rpBoolean(); byte rpByte(); char rpCharacter(); short rpShort(); int rpInt(); long rpLong(); float rpFloat(); double rpDouble(); Boolean rBoolean(); Byte rByte(); Character rCharacter(); Short rShort(); Integer rInt(); Long rLong(); Float rFloat(); Double rDouble(); String rString(); URI rURI(); boolean[] rpaBoolean(); byte[] rpaByte(); char[] rpaCharacter(); short[] rpaShort(); int[] rpaInt(); long[] rpaLong(); float[] rpaFloat(); double[] rpaDouble(); Collection rBooleans(); Collection rBytes(); Collection rCharacters(); Collection rShorts(); Collection rInts(); Collection rLongs(); Collection rFloats(); Collection rDoubles(); Collection rStrings(); Collection rURIs(); Boolean[] raBoolean(); Byte[] raByte(); Character[] raCharacter(); Short[] raShort(); Integer[] raInt(); Long[] raLong(); Float[] raFloat(); Double[] raDouble(); String[] raString(); URI[] raURI(); } public void testReturnTypes() throws Exception { Builder b = new Builder(); b.addClasspath(new File("bin")); b.setProperty("Export-Package", "test"); b.setProperty("-metatype", "*"); b.build(); Resource r = b.getJar().getResource( "OSGI-INF/metatype/test.MetatypeTest$TestReturnTypes.xml"); assertEquals(0, b.getErrors().size()); assertEquals(0, b.getWarnings().size()); System.out.println(b.getJar().getResources().keySet()); assertNotNull(r); IO.copy(r.openInputStream(), System.out); Document d = db.parse(r.openInputStream()); assertEquals("http://www.osgi.org/xmlns/metatype/v1.1.0", d.getDocumentElement() .getNamespaceURI()); // Primitives assertEquals("Boolean", xpath.evaluate("//OCD/AD[@id='rpBoolean']/@type", d)); assertEquals("Byte", xpath.evaluate("//OCD/AD[@id='rpByte']/@type", d)); assertEquals("Character", xpath.evaluate("//OCD/AD[@id='rpCharacter']/@type", d)); assertEquals("Short", xpath.evaluate("//OCD/AD[@id='rpShort']/@type", d)); assertEquals("Integer", xpath.evaluate("//OCD/AD[@id='rpInt']/@type", d)); assertEquals("Long", xpath.evaluate("//OCD/AD[@id='rpLong']/@type", d)); assertEquals("Float", xpath.evaluate("//OCD/AD[@id='rpFloat']/@type", d)); assertEquals("Double", xpath.evaluate("//OCD/AD[@id='rpDouble']/@type", d)); // Primitive Wrappers assertEquals("Boolean", xpath.evaluate("//OCD/AD[@id='rBoolean']/@type", d)); assertEquals("Byte", xpath.evaluate("//OCD/AD[@id='rByte']/@type", d)); assertEquals("Character", xpath.evaluate("//OCD/AD[@id='rCharacter']/@type", d)); assertEquals("Short", xpath.evaluate("//OCD/AD[@id='rShort']/@type", d)); assertEquals("Integer", xpath.evaluate("//OCD/AD[@id='rInt']/@type", d)); assertEquals("Long", xpath.evaluate("//OCD/AD[@id='rLong']/@type", d)); assertEquals("Float", xpath.evaluate("//OCD/AD[@id='rFloat']/@type", d)); assertEquals("Double", xpath.evaluate("//OCD/AD[@id='rDouble']/@type", d)); // Primitive Arrays assertEquals("Boolean", xpath.evaluate("//OCD/AD[@id='rpaBoolean']/@type", d)); assertEquals("Byte", xpath.evaluate("//OCD/AD[@id='rpaByte']/@type", d)); assertEquals("Character", xpath.evaluate("//OCD/AD[@id='rpaCharacter']/@type", d)); assertEquals("Short", xpath.evaluate("//OCD/AD[@id='rpaShort']/@type", d)); assertEquals("Integer", xpath.evaluate("//OCD/AD[@id='rpaInt']/@type", d)); assertEquals("Long", xpath.evaluate("//OCD/AD[@id='rpaLong']/@type", d)); assertEquals("Float", xpath.evaluate("//OCD/AD[@id='rpaFloat']/@type", d)); assertEquals("Double", xpath.evaluate("//OCD/AD[@id='rpaDouble']/@type", d)); assertEquals("2147483647", xpath.evaluate("//OCD/AD[@id='rpaBoolean']/@cardinality", d)); assertEquals("2147483647", xpath.evaluate("//OCD/AD[@id='rpaByte']/@cardinality", d)); assertEquals("2147483647", xpath.evaluate("//OCD/AD[@id='rpaCharacter']/@cardinality", d)); assertEquals("2147483647", xpath.evaluate("//OCD/AD[@id='rpaShort']/@cardinality", d)); assertEquals("2147483647", xpath.evaluate("//OCD/AD[@id='rpaInt']/@cardinality", d)); assertEquals("2147483647", xpath.evaluate("//OCD/AD[@id='rpaLong']/@cardinality", d)); assertEquals("2147483647", xpath.evaluate("//OCD/AD[@id='rpaFloat']/@cardinality", d)); assertEquals("2147483647", xpath.evaluate("//OCD/AD[@id='rpaDouble']/@cardinality", d)); // Wrapper + Object arrays assertEquals("Boolean", xpath.evaluate("//OCD/AD[@id='raBoolean']/@type", d)); assertEquals("Byte", xpath.evaluate("//OCD/AD[@id='raByte']/@type", d)); assertEquals("Character", xpath.evaluate("//OCD/AD[@id='raCharacter']/@type", d)); assertEquals("Short", xpath.evaluate("//OCD/AD[@id='raShort']/@type", d)); assertEquals("Integer", xpath.evaluate("//OCD/AD[@id='raInt']/@type", d)); assertEquals("Long", xpath.evaluate("//OCD/AD[@id='raLong']/@type", d)); assertEquals("Float", xpath.evaluate("//OCD/AD[@id='raFloat']/@type", d)); assertEquals("Double", xpath.evaluate("//OCD/AD[@id='raDouble']/@type", d)); assertEquals("String", xpath.evaluate("//OCD/AD[@id='raString']/@type", d)); assertEquals("String", xpath.evaluate("//OCD/AD[@id='raURI']/@type", d)); assertEquals("2147483647", xpath.evaluate("//OCD/AD[@id='raBoolean']/@cardinality", d)); assertEquals("2147483647", xpath.evaluate("//OCD/AD[@id='raByte']/@cardinality", d)); assertEquals("2147483647", xpath.evaluate("//OCD/AD[@id='raCharacter']/@cardinality", d)); assertEquals("2147483647", xpath.evaluate("//OCD/AD[@id='raShort']/@cardinality", d)); assertEquals("2147483647", xpath.evaluate("//OCD/AD[@id='raInt']/@cardinality", d)); assertEquals("2147483647", xpath.evaluate("//OCD/AD[@id='raLong']/@cardinality", d)); assertEquals("2147483647", xpath.evaluate("//OCD/AD[@id='raFloat']/@cardinality", d)); assertEquals("2147483647", xpath.evaluate("//OCD/AD[@id='raDouble']/@cardinality", d)); assertEquals("2147483647", xpath.evaluate("//OCD/AD[@id='raString']/@cardinality", d)); assertEquals("2147483647", xpath.evaluate("//OCD/AD[@id='raURI']/@cardinality", d)); // Wrapper + Object collections assertEquals("Boolean", xpath.evaluate("//OCD/AD[@id='rBooleans']/@type", d)); assertEquals("Byte", xpath.evaluate("//OCD/AD[@id='rBytes']/@type", d)); assertEquals("Character", xpath.evaluate("//OCD/AD[@id='rCharacter']/@type", d)); assertEquals("Short", xpath.evaluate("//OCD/AD[@id='rShorts']/@type", d)); assertEquals("Integer", xpath.evaluate("//OCD/AD[@id='rInts']/@type", d)); assertEquals("Long", xpath.evaluate("//OCD/AD[@id='rLongs']/@type", d)); assertEquals("Float", xpath.evaluate("//OCD/AD[@id='rFloats']/@type", d)); assertEquals("Double", xpath.evaluate("//OCD/AD[@id='rDoubles']/@type", d)); assertEquals("String", xpath.evaluate("//OCD/AD[@id='rStrings']/@type", d)); assertEquals("String", xpath.evaluate("//OCD/AD[@id='rURIs']/@type", d)); assertEquals("-2147483648", xpath.evaluate("//OCD/AD[@id='rBooleans']/@cardinality", d)); assertEquals("-2147483648", xpath.evaluate("//OCD/AD[@id='rBytes']/@cardinality", d)); assertEquals("-2147483648", xpath.evaluate("//OCD/AD[@id='rCharacters']/@cardinality", d)); assertEquals("-2147483648", xpath.evaluate("//OCD/AD[@id='rShorts']/@cardinality", d)); assertEquals("-2147483648", xpath.evaluate("//OCD/AD[@id='rInts']/@cardinality", d)); assertEquals("-2147483648", xpath.evaluate("//OCD/AD[@id='rLongs']/@cardinality", d)); assertEquals("-2147483648", xpath.evaluate("//OCD/AD[@id='rFloats']/@cardinality", d)); assertEquals("-2147483648", xpath.evaluate("//OCD/AD[@id='rDoubles']/@cardinality", d)); assertEquals("-2147483648", xpath.evaluate("//OCD/AD[@id='rStrings']/@cardinality", d)); assertEquals("-2147483648", xpath.evaluate("//OCD/AD[@id='rURIs']/@cardinality", d)); } /** * Test simple * * @author aqute * */ @Meta.OCD(description = "simple", name = "TestSimple") public static interface TestSimple { @Meta.AD String simple(); String[] notSoSimple(); Collection stringCollection(); } public void testSimple() throws Exception { Builder b = new Builder(); b.addClasspath(new File("bin")); b.setProperty("Export-Package", "test"); b.setProperty("-metatype", "*"); b.build(); Resource r = b.getJar().getResource("OSGI-INF/metatype/test.MetatypeTest$TestSimple.xml"); assertEquals(0, b.getErrors().size()); assertEquals(0, b.getWarnings().size()); System.out.println(b.getJar().getResources().keySet()); assertNotNull(r); IO.copy(r.openInputStream(), System.out); Document d = db.parse(r.openInputStream()); assertEquals("TestSimple", xpath.evaluate("//OCD/@name", d)); assertEquals("simple", xpath.evaluate("//OCD/@description", d)); assertEquals("test.MetatypeTest$TestSimple", xpath.evaluate("//OCD/@id", d)); assertEquals("test.MetatypeTest$TestSimple", xpath.evaluate("//Designate/@pid", d)); assertEquals("test.MetatypeTest$TestSimple", xpath.evaluate("//Object/@ocdref", d)); assertEquals("simple", xpath.evaluate("//OCD/AD[@id='simple']/@id", d)); assertEquals("Simple", xpath.evaluate("//OCD/AD[@id='simple']/@name", d)); assertEquals("String", xpath.evaluate("//OCD/AD[@id='simple']/@type", d)); assertEquals(Integer.MAX_VALUE + "", xpath.evaluate("//OCD/AD[@id='notSoSimple']/@cardinality", d)); } } bnd-1.50.0/biz.aQute.bndlib/src/test/defaultbsn.bnd0000644000175000017500000000004211656076535021723 0ustar drazzibdrazzibExport-Package: org.objectweb.asm bnd-1.50.0/biz.aQute.bndlib/src/test/TestBndBook.java0000644000175000017500000000221311656076535022132 0ustar drazzibdrazzibpackage test; import java.io.*; import junit.framework.*; import aQute.lib.osgi.*; public class TestBndBook extends TestCase { public void testFilterout() throws Exception { Builder b = new Builder(); b.addClasspath( new File("jar/osgi.jar")); b.addClasspath( new File("jar/ds.jar")); b.setProperty("Export-Package", "org.eclipse.*, org.osgi.*"); b.setProperty("fwusers", "${classes;importing;org.osgi.framework}"); b.setProperty("foo", "${filterout;${fwusers};org\\.osgi\\..*}"); b.build(); String fwusers = b.getProperty("fwusers"); String foo = b.getProperty("foo"); assertTrue( fwusers.length() > foo.length() ); assertTrue( fwusers.indexOf("org.osgi.framework.ServicePermission")>=0 ); assertTrue( fwusers.indexOf("org.eclipse.equinox.ds.instance.BuildDispose")>=0 ); assertFalse( foo.indexOf("org.osgi.framework.ServicePermission")>=0 ); assertTrue( foo.indexOf("org.eclipse.equinox.ds.instance.BuildDispose")>=0 ); System.out.println(b.getProperty("fwusers")); System.out.println(b.getProperty("foo")); } } bnd-1.50.0/biz.aQute.bndlib/src/test/signing/0000755000175000017500000000000011656076535020551 5ustar drazzibdrazzibbnd-1.50.0/biz.aQute.bndlib/src/test/signing/META-INF/0000755000175000017500000000000011656076535021711 5ustar drazzibdrazzibbnd-1.50.0/biz.aQute.bndlib/src/test/signing/META-INF/test.SF0000644000175000017500000014744711656076535023143 0ustar drazzibdrazzibSignature-Version: 1.0 Created-By: 1.5.0_16 (Apple Inc.) SHA1-Digest-Manifest-Main-Attributes: Q7PJRAQxIU7Z9zxsvMVOCHD23Xg= SHA1-Digest-Manifest: hpyH1C5MR9wlzZeh7jfCdSZSdSw= Name: org/osgi/service/cu/admin/spi/ControlUnitFactory.class SHA1-Digest: sfbSMsfMtzMQzuPQ3v/aX2FGMSM= Name: org/osgi/service/application/ApplicationDescriptor$2.class SHA1-Digest: aE4psXWIpj/pwsVK+hhRWWOnSko= Name: org/osgi/service/permissionadmin/PermissionInfo.class SHA1-Digest: CE/HJ2SPShlHV4kC6RwO9Um40L0= Name: org/osgi/service/dmt/AlertItem.class SHA1-Digest: HzQeOQ6OeXhjVYTgsWjOPOWi6QE= Name: org/osgi/service/metatype2/ExtendedAttributeDefinition.class SHA1-Digest: Mr29xJHZxvDmrp0nD+UN4MvXyAA= Name: OSGI-OPT/src/org/osgi/service/device/DriverLocator.java SHA1-Digest: ttLvHE4cTVWTh/KyQFEvCe3UZj0= Name: org/osgi/framework/FrameworkUtil$1.class SHA1-Digest: R0vV7c1qQL8kjqDz3borEO7Rht8= Name: org/osgi/framework/Bundle.class SHA1-Digest: mDIGgkLA6KEof7q/TB20YxdWnVI= Name: OSGI-OPT/src/org/osgi/service/device/Constants.java SHA1-Digest: WUJA8fVkTfj2tnOyHQqT0SodD5Q= Name: OSGI-OPT/src/org/osgi/service/useradmin/UserAdminListener.java SHA1-Digest: KH19dv9EbkDiYqSFKWX6EpZ6oGA= Name: org/osgi/service/obr/Capability.class SHA1-Digest: WwbsushVuYEr0S+avz5NFs2xBzU= Name: org/osgi/service/application/ApplicationException.class SHA1-Digest: QJ95XV1Up4ozKQ6HbnbOrRMvOsI= Name: OSGI-OPT/src/org/osgi/service/cu/package.html SHA1-Digest: 3r5ZLPdqDIkhgcerjrsVSkJZ6Sw= Name: OSGI-OPT/src/org/osgi/service/metatype2/MetaDataService.java SHA1-Digest: vGFKEpjNq1LBL4NBytDpwnTv4Tk= Name: org/osgi/service/metatype/ObjectClassDefinition.class SHA1-Digest: FMKOntonz30XbkZ4UZK1z7R7VOo= Name: org/osgi/service/wireadmin/Producer.class SHA1-Digest: /sET15Wu40LhJHpL5+ZZj0v8x5s= Name: OSGI-OPT/src/org/osgi/util/tracker/ServiceTrackerCustomizer.java SHA1-Digest: eS0vOHK0N/huQ6DEfC/XEDgewJQ= Name: org/osgi/service/application/ApplicationHandle$1.class SHA1-Digest: iek+GzhRz49K7WZM3u/eiirKzpo= Name: OSGI-OPT/src/org/osgi/framework/ServiceRegistration.java SHA1-Digest: Fw6MuI1QQMs7Ks6G6xRzVrfu5bs= Name: OSGI-OPT/src/org/osgi/service/component/ComponentFactory.java SHA1-Digest: 2O+1IR4l2L+ivdr6bj+dZjx1IpA= Name: OSGI-OPT/src/org/osgi/service/obr/packageinfo SHA1-Digest: t1FGRj/I2RimWmNGmlCbuu4ro2I= Name: OSGI-OPT/src/org/osgi/service/wireadmin/Envelope.java SHA1-Digest: +qKiCzI6C+SeVriEpSMx69O1Fas= Name: org/osgi/framework/PackagePermission.class SHA1-Digest: 04XUZYW/hWuETz15aWXNUzmLMGU= Name: OSGI-OPT/src/org/osgi/service/device/package.html SHA1-Digest: 61mtzAn9PUYAhAUpU5QwRTMqe9M= Name: OSGI-OPT/src/org/osgi/service/obr/RepositoryPermission.java SHA1-Digest: KAhLhBSwpHRpO3r1X3Pd6wE9XMA= Name: OSGI-OPT/src/org/osgi/util/position/package.html SHA1-Digest: wG/VjhMSWfN/095+nBbtldLo/jE= Name: OSGI-OPT/src/org/osgi/service/deploymentadmin/spi/DeploymentCust omizerPermission.java SHA1-Digest: 0DMQxaE43wz6tpfFawg1Zwa4HZU= Name: org/osgi/util/tracker/ServiceTrackerCustomizer.class SHA1-Digest: Er374Swkpo5AibzELJIepml/8VI= Name: org/osgi/service/dmt/security/AlertPermission.class SHA1-Digest: b8t3uBNgEDn6s2UdDebUcc89rX0= Name: org/osgi/service/device/DriverLocator.class SHA1-Digest: 3VCdvTVaY5p8Ly43hQsOeRJdCuc= Name: OSGI-OPT/src/org/osgi/service/cm/ConfigurationEvent.java SHA1-Digest: DhzUR76HMjRlna9qFE4rbpuWlwU= Name: org/osgi/service/cu/admin/spi/ManagedControlUnit.class SHA1-Digest: zxxXyv/g7Z6GgQVWzfUoxJEhQ6c= Name: OSGI-OPT/src/org/osgi/service/cm/ManagedService.java SHA1-Digest: tQbZ4YuuXlZ2Efpe3IJS3bvIcZg= Name: org/osgi/service/condpermadmin/BooleanCondition.class SHA1-Digest: VrtH3O3CisyOFszVZ6CHsqwIA+A= Name: org/osgi/service/cm/ConfigurationPermission.class SHA1-Digest: V6mg0MXlBtL8zSZj0aHz3h+1o3A= Name: OSGI-OPT/src/org/osgi/service/wireadmin/WireAdminEvent.java SHA1-Digest: tzNMhjFoVx0TMTw+I/gxoQdYRVE= Name: org/osgi/util/tracker/ServiceTracker$AllTracked.class SHA1-Digest: Ftj4XhKm3Z6sM5krxBUGXzWflV0= Name: OSGI-OPT/src/org/osgi/service/prefs/PreferencesService.java SHA1-Digest: NNel5+KKWmAFvPHluKrndIT9SME= Name: org/osgi/service/useradmin/Role.class SHA1-Digest: ZBfuxvfgESwsUHTqy5YrnYclR1Q= Name: about.html SHA1-Digest: 6GRCBrgAPCPRoE2KKy3J8k9obV0= Name: OSGI-OPT/src/org/osgi/service/upnp/UPnPStateVariable.java SHA1-Digest: 3sLYonfPj++NV4TXaIYLYWcXLSk= Name: OSGI-OPT/src/org/osgi/service/monitor/MonitorPermission.java SHA1-Digest: 73d9abBm87dkXpyxTVXOc+NEFhA= Name: OSGI-OPT/src/org/osgi/service/condpermadmin/ConditionalPermissio nAdmin.java SHA1-Digest: dh5O6y3shhnYsZZQKhBKf8mBn70= Name: org/osgi/service/dmt/spi/DataPlugin.class SHA1-Digest: kE0mBCW1+QcKPRpYFpmSlHN4YQY= Name: org/osgi/service/component/ComponentContext.class SHA1-Digest: qpwZ2+6JS9ukSDof5TTzsuXVdJg= Name: OSGI-OPT/src/org/osgi/service/dmt/security/DmtPrincipalPermissio n.java SHA1-Digest: BVmmhZDgTuiT+wh+Dn2woTdCYD0= Name: org/osgi/service/obr/Resolver.class SHA1-Digest: 26YweX1pe1F0iUjPiPSIK4+AVgE= Name: OSGI-OPT/src/org/osgi/util/measurement/Unit.java SHA1-Digest: k/O5kSM9F/SzHPN74ns3oZrn3m0= Name: OSGI-OPT/src/org/osgi/util/measurement/State.java SHA1-Digest: Jr1H07MOt7bxjCcfjhcMfJTTpuU= Name: OSGI-OPT/src/org/osgi/framework/FrameworkUtil.java SHA1-Digest: DDRiclUJinOFB4YmgVfcenoVdoc= Name: OSGI-OPT/src/org/osgi/service/wireadmin/packageinfo SHA1-Digest: KM7HMwim7qnRZaqYw9OKIRCw88g= Name: OSGI-OPT/src/org/osgi/service/power/packageinfo SHA1-Digest: xDjYgopxOjS5taQwbP2ntKAnNzQ= Name: org/osgi/service/dmt/security/DmtPermission.class SHA1-Digest: m5McZb8Te2p7m8KhqXm18NI64aU= Name: org/osgi/service/wireadmin/WireAdminListener.class SHA1-Digest: cSdtBzNcyh99NOQXIZEsEbtBh00= Name: org/osgi/service/monitor/packageinfo SHA1-Digest: FyS36PoKt7mYRTtUX7D4v4fr0as= Name: org/osgi/service/dmt/security/DmtPrincipalPermission.class SHA1-Digest: VQ1QRbxc7ccmEVroR+ddohTJyU8= Name: OSGI-OPT/src/org/osgi/service/upnp/UPnPService.java SHA1-Digest: pFIw9CDr0WdrF9cqPBt/6JwAE7A= Name: OSGI-OPT/src/org/osgi/service/obr/RepositoryAdmin.java SHA1-Digest: bbhUVG4tav3xRW9snhYDxojsfag= Name: OSGI-OPT/src/org/osgi/service/cu/StateVariableListener.java SHA1-Digest: M8182T6l1gp/IxNRpBJj37c42wU= Name: org/osgi/service/upnp/UPnPAction.class SHA1-Digest: rjL8gokfNTr3zVkRVKTmTZSHHy4= Name: org/osgi/service/deploymentadmin/DeploymentAdminPermission.class SHA1-Digest: fJ6V3cIgeFmlVj4TCbQqLh8Edbc= Name: OSGI-OPT/src/org/osgi/framework/Constants.java SHA1-Digest: 3uSwCgFLubyYjE0GAAM4itYW3lQ= Name: org/osgi/service/permissionadmin/PermissionAdmin.class SHA1-Digest: vWM4+XdOYdJS8uyE86fNVkH1yVk= Name: OSGI-OPT/src/org/osgi/service/deploymentadmin/DeploymentExceptio n.java SHA1-Digest: ybgf55dCYCR6iQsv1WidJAeOQew= Name: org/osgi/util/gsm/IMSICondition$1.class SHA1-Digest: j02f22884nCpndJovordJzjo95s= Name: org/osgi/framework/ServiceListener.class SHA1-Digest: gxUV7TW3cWUCjImgeu1UVRip7ZU= Name: OSGI-OPT/src/org/osgi/framework/ServiceEvent.java SHA1-Digest: l5hqV26dPSxYNHaDT22jqJ2VfWE= Name: org/osgi/service/startlevel/packageinfo SHA1-Digest: SCTgcEiasy60ZhTlaZpxt+VwFwg= Name: OSGI-OPT/src/org/osgi/service/permissionadmin/package.html SHA1-Digest: FWOxzx0PWfhqS6QYkHMHKjecndg= Name: org/osgi/service/upnp/UPnPEventListener.class SHA1-Digest: v6VDr3vloHQKDksY1stsqZmzEmE= Name: OSGI-OPT/src/org/osgi/service/condpermadmin/BundleSignerConditio n.java SHA1-Digest: e2AMBUgiZxJ/dUBIyJX6JR/lK1g= Name: OSGI-OPT/src/org/osgi/service/cu/admin/spi/ControlUnitFactory.ja va SHA1-Digest: FqxuLNNqX/UupPOQbpN70AEYvsE= Name: org/osgi/service/metatype2/MetaDataService.class SHA1-Digest: NGEji4oX5Mh4DfDi8dkj6GKjjRo= Name: OSGI-OPT/src/org/osgi/service/dmt/spi/ReadWriteDataSession.java SHA1-Digest: h5s4wza3N7L5lrtQz7U5v/pza/0= Name: org/osgi/framework/ServiceEvent.class SHA1-Digest: I0nks/VMG6Zefx5tojzW4WRPdpQ= Name: org/osgi/service/cu/packageinfo SHA1-Digest: x57SK8qmQ9S59SaWCVOxIAHclbI= Name: OSGI-OPT/src/org/osgi/service/cm/ConfigurationAdmin.java SHA1-Digest: HPfiAneRKjvyInad9oDyZogKQWY= Name: OSGI-OPT/src/org/osgi/service/deploymentadmin/spi/packageinfo SHA1-Digest: TRuidqI0izFTiZc3YwteXLobRPs= Name: org/osgi/service/device/Constants.class SHA1-Digest: ddKS3wdlMD/YJWvrNi12vTPOU5A= Name: org/osgi/service/monitor/StatusVariable.class SHA1-Digest: zkTLzjYsFgL6doqG2SCvhEEogVc= Name: org/osgi/service/application/ApplicationHandle$2.class SHA1-Digest: heVPWvDMoIRHTB+UbfEM/PktPE8= Name: org/osgi/service/obr/Resource.class SHA1-Digest: 2DvYuk1dW0S9lhKLkMkLaXYkfeM= Name: org/osgi/service/application/packageinfo SHA1-Digest: L7pfZ2QCSp+VLhnMBYTT3dYJbYo= Name: org/osgi/service/event/EventHandler.class SHA1-Digest: 4Wp6XMEOhNpNWAy+m49V3rA0m4M= Name: OSGI-OPT/src/org/osgi/service/cu/admin/spi/CUAdminCallback.java SHA1-Digest: hDOyxu0qP/KRkUJKqN3oFfReSYE= Name: org/osgi/service/useradmin/User.class SHA1-Digest: RZSbT0QdRtnbXChjJqw2kdvQ0QU= Name: OSGI-OPT/src/org/osgi/framework/Version.java SHA1-Digest: DjjQqQozngoDfDbfMe5o4QUWl+o= Name: OSGI-OPT/src/org/osgi/service/cu/admin/ControlUnitAdmin.java SHA1-Digest: hOAwMEx8LM1Ese77mX20BjxDktk= Name: org/osgi/framework/BundleException.class SHA1-Digest: J5llQXVY+tfOeApZJpauhyDllqE= Name: OSGI-OPT/src/org/osgi/service/provisioning/package.html SHA1-Digest: NYtqW4gA3nJQXCUtw1A3e6FqRKg= Name: org/osgi/service/component/ComponentFactory.class SHA1-Digest: t3vlT3RoVSKwLRimlYqbgwVrP7E= Name: OSGI-OPT/src/org/osgi/service/cm/ConfigurationPlugin.java SHA1-Digest: VY3HzXRpxPxrKGiqDbmwY3gh+KA= Name: org/osgi/service/url/URLStreamHandlerSetter.class SHA1-Digest: X7BRQE7kSKSyOqm4jECFpPhi5Eg= Name: org/osgi/service/component/packageinfo SHA1-Digest: /xY1f7+hISH03T2DokxdWi/OUD0= Name: org/osgi/service/deploymentadmin/DeploymentException.class SHA1-Digest: of69BmtH1ik295WsG76dlLT8Cvg= Name: OSGI-OPT/src/org/osgi/service/deploymentadmin/DeploymentAdmin.ja va SHA1-Digest: vRtt0l8jtHNcU7WDNCan7OMBoDk= Name: org/osgi/service/deploymentadmin/BundleInfo.class SHA1-Digest: QWJbc2GuIl0LWtyUDvwu2mzNaVM= Name: org/osgi/service/deploymentadmin/spi/DeploymentCustomizerPermiss ion.class SHA1-Digest: 2T915E+ooS52hKhGdhLAnMoaNas= Name: org/osgi/service/obr/Requirement.class SHA1-Digest: 7OOfbj5tptsc9//yiQNTO4QUFPA= Name: OSGI-OPT/src/org/osgi/service/deploymentadmin/spi/package.html SHA1-Digest: Li1ME10z46dsRnF92ml+PlueG0k= Name: OSGI-OPT/src/org/osgi/service/metatype2/ExtendedObjectClassDefin ition.java SHA1-Digest: qIxdL7SCcFQxR65hMgnGhkzc1ls= Name: org/osgi/service/metatype2/ExtendedObjectClassDefinition.class SHA1-Digest: rmkIiVuooBt8kcQbuC82wWzShJ8= Name: org/osgi/framework/BundleActivator.class SHA1-Digest: g0zeOodlRBFEu3NpPttgyMty+H4= Name: OSGI-OPT/src/org/osgi/service/cm/ConfigurationListener.java SHA1-Digest: AhC1L3JgvDawGCtJBm0NtPnmq1k= Name: OSGI-OPT/src/org/osgi/framework/Bundle.java SHA1-Digest: aWbtgALau4eeIE1Q/lay32K/AvI= Name: org/osgi/service/useradmin/UserAdminPermission.class SHA1-Digest: pR9F4FBHh56pLj/7uNz97V8bfMA= Name: OSGI-OPT/src/org/osgi/framework/BundleActivator.java SHA1-Digest: rK/g1INN1qRkkQmV6VJYoQ9efEc= Name: OSGI-OPT/src/org/osgi/service/useradmin/Authorization.java SHA1-Digest: tDxp473gPUefCWu+i2BuiShfG+I= Name: org/osgi/util/measurement/Unit.class SHA1-Digest: Rc0VGWrDwWSVE3jurJK+xVZdxZs= Name: org/osgi/framework/SynchronousBundleListener.class SHA1-Digest: 1DR3NKDIeAnuNkuUhoH737IXIyc= Name: org/osgi/service/packageadmin/PackageAdmin.class SHA1-Digest: 3VQBEbW7JTpvsM2MMM8tozEiJ8A= Name: OSGI-OPT/src/org/osgi/service/application/packageinfo SHA1-Digest: aUGgeVyzhS8qAOlJXDtFhcb92Go= Name: org/osgi/framework/Filter.class SHA1-Digest: WgKzS+hS3wri/hjhSyEGrru1xnA= Name: OSGI-OPT/src/org/osgi/util/gsm/IMSICondition.java SHA1-Digest: gbMl+2TzCWoGEGapEOalLN8SqZo= Name: org/osgi/service/useradmin/UserAdmin.class SHA1-Digest: 7DtBWSkC0gfrJhJRVeWFrqJ2l8w= Name: org/osgi/service/prefs/BackingStoreException.class SHA1-Digest: NyTtMBHun/iuJ2VliPfAgbSq6gM= Name: OSGI-OPT/src/org/osgi/service/condpermadmin/BundleLocationCondit ion.java SHA1-Digest: iL5Lg2HaPw7XUU21djuIb5VPDnY= Name: org/osgi/service/power/packageinfo SHA1-Digest: KKgPLGnwzPVPq6ipkVKBRRM/4W4= Name: org/osgi/service/provisioning/packageinfo SHA1-Digest: 0xav4aw6lmJApY6McMMmS8p8l5E= Name: org/osgi/service/dmt/spi/ReadableDataSession.class SHA1-Digest: bw9KDLmyGoIiS4ERB3nq4FvVMjQ= Name: OSGI-OPT/src/org/osgi/service/metatype2/packageinfo SHA1-Digest: nQI1k9rrV/3gpoubhVauPgaVY4I= Name: OSGI-OPT/src/org/osgi/service/obr/Repository.java SHA1-Digest: tz5qCfolNBIBhvybJWjwXVRMrlg= Name: org/osgi/framework/BundleContext.class SHA1-Digest: tnnh9mNI75TIPFNb8H0k/WKUoxA= Name: OSGI-OPT/src/org/osgi/service/cu/admin/spi/ManagedControlUnit.ja va SHA1-Digest: bM3G+wpU4OvL01cqsTrX7VVmSoo= Name: OSGI-OPT/src/org/osgi/util/tracker/ServiceTracker.java SHA1-Digest: P/UDK+C1qajosD3JzqJSJCXjKxA= Name: org/osgi/service/wireadmin/packageinfo SHA1-Digest: F26MO7na/1S6XaQGqxtqpHalSw8= Name: OSGI-OPT/src/org/osgi/service/power/PowerHandler.java SHA1-Digest: WSLcfhI5+OfkLMv+IlqtAXpdm60= Name: OSGI-OPT/src/org/osgi/service/dmt/spi/package.html SHA1-Digest: EyExbRUcMUvIgeriUDYWxvIX1iM= Name: org/osgi/service/dmt/spi/packageinfo SHA1-Digest: 9g5jCX/uSxevai+4ZVY0bRxQ8fY= Name: OSGI-OPT/src/org/osgi/service/monitor/package.html SHA1-Digest: nritY4o8hsL1msY7vqPa5O41UTo= Name: org/osgi/service/component/ComponentException.class SHA1-Digest: bKNd7rU0xtcArMXlIX9zeBlWbVI= Name: OSGI-OPT/src/org/osgi/service/http/HttpContext.java SHA1-Digest: EZsUSHnvRbkoUqAUaKTIZytO9P0= Name: org/osgi/service/metatype2/MetaDataListener.class SHA1-Digest: pl+3Gw0mfg/Z9YkTeEpwYnuSjOk= Name: org/osgi/service/wireadmin/WirePermissionCollection.class SHA1-Digest: XLHa3jJkeMdQdL18FpyRAczG1BQ= Name: org/osgi/service/event/packageinfo SHA1-Digest: NY8VG6jl8hLofRKbIaWuFKfCkBY= Name: org/osgi/service/cu/admin/ControlUnitAdmin.class SHA1-Digest: oX5/UUtKUrbz1Ii4gMY6/ODtaMU= Name: org/osgi/service/wireadmin/WireConstants.class SHA1-Digest: ye3kpQK/oLYEBYQKo9F3Ui/680Q= Name: org/osgi/service/condpermadmin/ConditionalPermissionInfo.class SHA1-Digest: doqYJzj0aZ1J0fsfVxWz/6pyJgE= Name: OSGI-OPT/src/org/osgi/service/packageadmin/packageinfo SHA1-Digest: VnTA1dpKnxqZaDgh6qoKUevSyVc= Name: org/osgi/service/cu/diag/DiagnosableControlUnit.class SHA1-Digest: FInC6EkF1iwjHxQOdfbGkjFzFRc= Name: OSGI-OPT/src/org/osgi/framework/ServiceListener.java SHA1-Digest: XchWym2JB8TKZnInEEfW0nCCUeE= Name: OSGI-OPT/src/org/osgi/service/cm/ConfigurationException.java SHA1-Digest: QQABK4FoQBHLunSmCDu5Qb54tFs= Name: org/osgi/service/prefs/PreferencesService.class SHA1-Digest: Y02W8rZc/5RaUyUcSIr93t5CIRw= Name: org/osgi/service/deploymentadmin/DeploymentAdmin.class SHA1-Digest: dXKPOZ8duLUxJ8Kzv0TlMcIGjjQ= Name: org/osgi/service/application/ApplicationHandle.class SHA1-Digest: PZaGURIfGrG3QoboK+W8TlUzj0Y= Name: org/osgi/framework/ServiceFactory.class SHA1-Digest: jRLe9oNOVWuFL9qpp67SnjdVBc8= Name: OSGI-OPT/src/org/osgi/service/deploymentadmin/DeploymentPackage. java SHA1-Digest: epjd52FJJ8rw2JFeLKY4zjoGVjI= Name: OSGI-OPT/src/org/osgi/service/wireadmin/package.html SHA1-Digest: GozY5bKUfsbzX4FVcVzTwV7eeHo= Name: OSGI-OPT/src/org/osgi/framework/Filter.java SHA1-Digest: q7aIjtxN3mLzLhSCggiZWPEc3/g= Name: org/osgi/application/ApplicationServiceListener.class SHA1-Digest: 2gQZKVK21lRr0r6PdhOZXTwWArA= Name: OSGI-OPT/src/org/osgi/framework/BundleEvent.java SHA1-Digest: ry9XXINCQsVIGs2ZgxEmqgjs9Eo= Name: OSGI-OPT/src/org/osgi/service/upnp/UPnPLocalStateVariable.java SHA1-Digest: n7U+2FKucLbfEIJyxlTRTEdTLyc= Name: OSGI-OPT/src/org/osgi/service/cu/admin/HierarchyListener.java SHA1-Digest: SdPxctxdeOSqgQJe3GoFj6UL0aU= Name: org/osgi/service/cu/admin/packageinfo SHA1-Digest: 0UJOubdVdTfHgtbhgLSSAXH75d8= Name: OSGI-OPT/src/org/osgi/framework/packageinfo SHA1-Digest: O1NwL4L9XrYb7RQaGU/xZ1rPYCM= Name: OSGI-OPT/src/org/osgi/service/io/ConnectorService.java SHA1-Digest: 4ARQXoaU65OoeW3JbVD8iVdd/MM= Name: OSGI-OPT/src/org/osgi/service/component/ComponentConstants.java SHA1-Digest: nhXRhdi1HehPvgVQt2J6kLZ6RfM= Name: org/osgi/service/upnp/packageinfo SHA1-Digest: zfpggI7VR812W0d5Z72p2LGptf0= Name: OSGI-OPT/src/org/osgi/service/monitor/MonitorListener.java SHA1-Digest: Y1gnv8rTedv6SsHC+Zv33U+OVP8= Name: org/osgi/service/dmt/RemoteAlertSender.class SHA1-Digest: YeoatqIF51AIrjpgDvI5FEx/VFw= Name: OSGI-OPT/src/org/osgi/service/condpermadmin/ConditionalPermissio nInfo.java SHA1-Digest: pa1J0TAgkgGr9vK5Nz5cdlnH8fA= Name: org/osgi/service/dmt/security/packageinfo SHA1-Digest: IbmPRxSSpo6SpaRWUxWmTju0SUI= Name: OSGI-OPT/src/org/osgi/service/log/LogListener.java SHA1-Digest: ELYD3waDLSjkghrRyXm7bb3kWEY= Name: org/osgi/service/dmt/Acl.class SHA1-Digest: lBAeFEE79x9tbJ1Ksg797cMQHL4= Name: org/osgi/service/cu/diag/Status.class SHA1-Digest: MsXwxeusu7Ko1NEGNuGTs5kT7jg= Name: OSGI-OPT/src/org/osgi/util/xml/packageinfo SHA1-Digest: bp1+9Y0kfXN6oSRqcJy+7kyalcI= Name: OSGI-OPT/src/org/osgi/service/provisioning/packageinfo SHA1-Digest: 9ooyDAYiP29KMkn9I/tqZt13JM4= Name: org/osgi/util/mobile/UserPromptCondition.class SHA1-Digest: ydalVGHWNbPwv1XS3Sbx3ap2WBI= Name: org/osgi/service/useradmin/UserAdminEvent.class SHA1-Digest: qxK/mDWlZf4ZQpGj1d48eCMQ4wk= Name: OSGI-OPT/src/org/osgi/service/wireadmin/Producer.java SHA1-Digest: ZMj5T46gUfWbLMX1akZaz71i5J8= Name: OSGI-OPT/src/org/osgi/application/ApplicationServiceEvent.java SHA1-Digest: iEdx7rcgg8T5clpC7b8Ai1vXr0k= Name: org/osgi/service/power/PowerPermissionCollection.class SHA1-Digest: qjhmRh3xHGTt1+DzswUEJaigHro= Name: OSGI-OPT/src/org/osgi/framework/Configurable.java SHA1-Digest: AYa0hYRT7mdVugV77IC6CjHtn1I= Name: org/osgi/service/deploymentadmin/packageinfo SHA1-Digest: UvNF0aGhEWxme6lOnQU68iGq3I8= Name: OSGI-OPT/src/org/osgi/service/monitor/MonitorAdmin.java SHA1-Digest: PEdJ4FjterkegMlqvib4w8NQTAs= Name: org/osgi/service/packageadmin/ExportedPackage.class SHA1-Digest: y1jrsmRS6cI/T5cZzxOy2KPBeTI= Name: LICENSE SHA1-Digest: b9HqwNfxSwcCCQCVqrJErLzJgOg= Name: org/osgi/service/upnp/UPnPException.class SHA1-Digest: hat0tytKqGW2pa7AFZUVaixluwc= Name: OSGI-OPT/src/org/osgi/service/prefs/package.html SHA1-Digest: CExINR/268h2UyGBok1tpibJJsg= Name: org/osgi/service/obr/RepositoryAdmin.class SHA1-Digest: 3/LHqb+XS/Uram7spDM2cUy66Bc= Name: org/osgi/service/upnp/UPnPLocalStateVariable.class SHA1-Digest: BaliwtaIp9md48mmURWQm8dtPV0= Name: org/osgi/service/application/ApplicationDescriptor.class SHA1-Digest: Nce8EtVd0rXgP3E4B7R/UJrV7p0= Name: OSGI-OPT/src/org/osgi/service/dmt/AlertItem.java SHA1-Digest: g0LRWyf0vzuT05+mjOK0xEkS2gs= Name: OSGI-OPT/src/org/osgi/service/prefs/packageinfo SHA1-Digest: mAl1swYObOrckUER9ZE+mdfyZmw= Name: org/osgi/service/metatype/MetaTypeProvider.class SHA1-Digest: /gO96XK7yFeUEozZwRdBKHGzwlc= Name: OSGI-OPT/src/org/osgi/service/dmt/spi/packageinfo SHA1-Digest: wpqOB4C+6cG4aZOz1ksiiXa7Qww= Name: org/osgi/service/deploymentadmin/DeploymentAdminPermission$1.cla ss SHA1-Digest: oT+6wmJfNf3urxX7LNLqZRWouh8= Name: OSGI-OPT/src/org/osgi/service/dmt/RemoteAlertSender.java SHA1-Digest: IkwHw3l54oELbcF1J6hyDBvX144= Name: OSGI-OPT/src/org/osgi/service/packageadmin/RequiredBundle.java SHA1-Digest: dBAFCS5n/yxd+YtMTsYiq+0jRMY= Name: org/osgi/service/useradmin/Group.class SHA1-Digest: m7QM0uORsLEFroVYxDcC04zCvzQ= Name: org/osgi/service/io/packageinfo SHA1-Digest: pZsyLGMUOdJnI6v5iqLwZ+BYXOw= Name: OSGI-OPT/src/org/osgi/service/cu/admin/ControlUnitAdminException .java SHA1-Digest: hnh2GpuES+/KOc0ppTuGfm8OXh4= Name: org/osgi/service/http/HttpContext.class SHA1-Digest: Q2fvwp9p5Vyb/tzS0TUJgKp4zlY= Name: org/osgi/service/dmt/MetaNode.class SHA1-Digest: 6lBYlRleYWUGHgkxwnmOs87vUcQ= Name: OSGI-OPT/src/org/osgi/service/permissionadmin/PermissionInfo.jav a SHA1-Digest: 93F2AkIiWSJaG8ILqp/jwB4uHKA= Name: org/osgi/util/position/Position.class SHA1-Digest: QfCUjB/keFET6sR/a1b5RJdilGc= Name: OSGI-OPT/src/org/osgi/service/cu/diag/DiagnosableControlUnit.jav a SHA1-Digest: w/v0lvaa7UAyqEJTdSd9FJAXnf0= Name: OSGI-OPT/src/org/osgi/service/upnp/UPnPException.java SHA1-Digest: KV9ENXYFuZRySsgkBwpuEfBU/Lg= Name: OSGI-OPT/src/org/osgi/service/log/LogReaderService.java SHA1-Digest: TxgscdaZq8QcVbrpySgOzSHc8mg= Name: org/osgi/util/gsm/IMEICondition.class SHA1-Digest: /m/zvs6W3AVYys8gXUZvtpoPjFc= Name: org/osgi/service/permissionadmin/packageinfo SHA1-Digest: /X9I6BMWshDO1mJEDfdkJXl8vho= Name: org/osgi/framework/FrameworkListener.class SHA1-Digest: Z2K4/t8oNe/NFvRUQ3r9YyFzPDs= Name: OSGI-OPT/src/org/osgi/service/dmt/security/packageinfo SHA1-Digest: XGtd1Sc5PwO2zJB5mT0bs65lzyg= Name: OSGI-OPT/src/org/osgi/service/upnp/packageinfo SHA1-Digest: 0BmOI9Dr/aMOL86yxro/w71ACEs= Name: OSGI-OPT/src/org/osgi/service/prefs/BackingStoreException.java SHA1-Digest: FJiT873SfpSbhEgj6zTvGQ+EbZo= Name: OSGI-OPT/src/org/osgi/service/useradmin/UserAdminEvent.java SHA1-Digest: +vHlDUKcqNyKj47HP8abkTze1vE= Name: org/osgi/service/obr/packageinfo SHA1-Digest: kvWJfhxviXOqVnyAZoQrxtO3B+Q= Name: OSGI-OPT/src/org/osgi/service/useradmin/Role.java SHA1-Digest: EKK2iWS571PYXrYcaaFFut4qCvY= Name: org/osgi/util/mobile/UserPromptCondition$UserPromptConditionFact ory.class SHA1-Digest: UkXouPizN6SV2w//wSK8opi48Dk= Name: org/osgi/service/power/PowerHandler.class SHA1-Digest: BiwuBikLpLyDPa8WTtO8XsJkJZU= Name: org/osgi/service/metatype/AttributeDefinition.class SHA1-Digest: E3JwATJWZnNft3rOmkxgxjELo1c= Name: OSGI-OPT/src/org/osgi/service/cm/package.html SHA1-Digest: FOvz+qmLvnmCbzbIcKGfqhc2dz0= Name: org/osgi/service/device/Driver.class SHA1-Digest: UNP8Wpr9+2xXWE02N/0fS8winPU= Name: OSGI-OPT/src/org/osgi/service/dmt/packageinfo SHA1-Digest: Z0ANiYPzpEBL/sc7NCPMynVT2XQ= Name: org/osgi/service/dmt/spi/ExecPlugin.class SHA1-Digest: 7yKNtzokinFIfOLVlAFs0kjaM3o= Name: OSGI-OPT/src/org/osgi/service/dmt/spi/ExecPlugin.java SHA1-Digest: MztbaI4607eRZOvEkF+XD5IWpIQ= Name: OSGI-OPT/src/org/osgi/service/provisioning/ProvisioningService.j ava SHA1-Digest: J2ysr94trQJPw1Oyr+AE8iqlEjI= Name: org/osgi/service/log/LogEntry.class SHA1-Digest: PbIvon1WBcXbKIS1bS1sztx8E0M= Name: org/osgi/util/measurement/packageinfo SHA1-Digest: 9UOhYLe+iBSnPRpW0mwl9TRhlUY= Name: org/osgi/service/metatype2/packageinfo SHA1-Digest: YL9MShQfQV7tH3eK7MA3xkY9f9E= Name: org/osgi/service/http/NamespaceException.class SHA1-Digest: zMkGPHixWnJxlOWFhWCFB1H9Shs= Name: org/osgi/service/obr/Repository.class SHA1-Digest: bYBpc12xjSMndlNOIeksbZFmLNE= Name: OSGI-OPT/src/org/osgi/service/obr/Resource.java SHA1-Digest: uOCxhqMNY+ROtLOCrwkipdQd2A4= Name: OSGI-OPT/src/org/osgi/service/metatype2/MetaDataListener.java SHA1-Digest: 8ijnM9ZLGHH+nZHO0+vNxCd/tVA= Name: OSGI-OPT/src/org/osgi/service/deploymentadmin/spi/ResourceProces sorException.java SHA1-Digest: sLk9fZi1yT40WzkytuH/5ucDDOE= Name: OSGI-OPT/src/org/osgi/framework/AllServiceListener.java SHA1-Digest: e6SWcFjY/C6JtEFIUxnw1O0gQY0= Name: org/osgi/service/event/TopicPermissionCollection.class SHA1-Digest: v8V76ZXZF4hnzkbzKiQbOIbgybs= Name: OSGI-OPT/src/org/osgi/service/event/EventConstants.java SHA1-Digest: +YQseaRQJ/jvvMSULTG75lc9yRA= Name: OSGI-OPT/src/org/osgi/service/device/Driver.java SHA1-Digest: lMvWU8dVylSPfLsvU8WkTH86/V8= Name: OSGI-OPT/src/org/osgi/service/cu/admin/package.html SHA1-Digest: +Rr5MzfzIaf26R+YXO1pDkOYGC4= Name: OSGI-OPT/src/org/osgi/service/useradmin/package.html SHA1-Digest: XzOtdTJAsxXjc0LLIYEqVfrL1GI= Name: org/osgi/service/power/DevicePower.class SHA1-Digest: rr6dE+xaTp4uLz+PeYiERjp0IA4= Name: OSGI-OPT/src/org/osgi/service/condpermadmin/Condition.java SHA1-Digest: 4SdtX9NEONvEkLDO5T78mn/WhC4= Name: org/osgi/service/dmt/packageinfo SHA1-Digest: B2G5iZAZ+nO5uZ0cLk2GJo6iHbY= Name: org/osgi/service/url/AbstractURLStreamHandlerService.class SHA1-Digest: e8qE6Zzsjn6RE6Jrf0E1oI3Cj3Q= Name: OSGI-OPT/src/org/osgi/service/application/package.html SHA1-Digest: NpmcCg3u4FBpczDrvwPaOOHk2v8= Name: OSGI-OPT/src/org/osgi/service/event/TopicPermission.java SHA1-Digest: HCyl9b0lFPzj7MFpGzEX6CGIPUU= Name: org/osgi/service/useradmin/Authorization.class SHA1-Digest: cmGH7WXm55IEmzpoHFss5Qq3/AU= Name: OSGI-OPT/src/org/osgi/service/cu/packageinfo SHA1-Digest: vpgm6eSOEE6n9FUX5b4KRRftKGU= Name: org/osgi/framework/packageinfo SHA1-Digest: WwDImiydH0ha5vuR+Y9D2ceYTTM= Name: org/osgi/service/cu/ControlUnit.class SHA1-Digest: P/ntHWajxFWQof+lSKt3OIfFF98= Name: OSGI-OPT/src/org/osgi/service/metatype/AttributeDefinition.java SHA1-Digest: fN0oYXhL7KdqpBbN8kqYJdR+C0I= Name: OSGI-OPT/src/org/osgi/service/power/DevicePower.java SHA1-Digest: PLdzVv3lunXHWwFWguQkJU+Cx1Y= Name: org/osgi/service/cm/ConfigurationPermissionCollection$1.class SHA1-Digest: yI/JFqFO44QPR0Tw1F7jJTD7yZU= Name: org/osgi/service/monitor/Monitorable.class SHA1-Digest: 9PLiKq3iaP/awRaXyuV0j82Prys= Name: org/osgi/framework/Version.class SHA1-Digest: a7ysntTLVnM/+Fwc6Q5ncBfRZOA= Name: org/osgi/service/wireadmin/WireAdminEvent.class SHA1-Digest: hifz0pym5EOsaPOaedV47RWOe1E= Name: org/osgi/service/cm/ConfigurationException.class SHA1-Digest: fe0kc2XVEUkHXDqAqEkhCVX3/es= Name: org/osgi/service/cu/admin/ControlUnitAdminException.class SHA1-Digest: QATzB4G/xxC31fVNuODcbTTlUlc= Name: OSGI-OPT/src/org/osgi/service/dmt/MetaNode.java SHA1-Digest: eO3FqwYH0219iRKOkCcswKGlBtQ= Name: org/osgi/service/url/packageinfo SHA1-Digest: ZsLD3JmMCGe6qadL32tR0BCYzgk= Name: OSGI-OPT/src/org/osgi/service/metatype/package.html SHA1-Digest: HRS7B594qaSE0p8IvqaMdIqBBys= Name: OSGI-OPT/src/org/osgi/service/device/Match.java SHA1-Digest: SxsuBJzijpBNO2DAfQ3n4QzaOjo= Name: OSGI-OPT/src/org/osgi/service/application/ApplicationHandle.java SHA1-Digest: 0TPxqYsK/qVAXZxb5pCxdmxdzAs= Name: OSGI-OPT/src/org/osgi/service/useradmin/UserAdminPermission.java SHA1-Digest: HHcWfDEoNR+RcXB89QEe7C4lDvk= Name: OSGI-OPT/src/org/osgi/service/metatype2/ActionDefinition.java SHA1-Digest: I9OnAlX3lQr3igUyuJwuu0XQC/s= Name: org/osgi/service/application/ScheduledApplication.class SHA1-Digest: VgSCcsgfZPsA8WEXd6/nXXWpzWA= Name: OSGI-OPT/src/org/osgi/service/dmt/Acl.java SHA1-Digest: ABWYp0r3JZRSAX0fFtlqwkDkssg= Name: OSGI-OPT/src/org/osgi/service/upnp/UPnPAction.java SHA1-Digest: iRBQa5/H/C0d31okvdUJCa50bDQ= Name: org/osgi/service/dmt/DmtException.class SHA1-Digest: GKdA0UTQXgw6eSSReO+B+MMr5MY= Name: OSGI-OPT/src/org/osgi/service/useradmin/UserAdmin.java SHA1-Digest: Nz6/JGxwGzsngmLCgQHT6Xi++9Q= Name: OSGI-OPT/src/org/osgi/service/device/Device.java SHA1-Digest: r8JXOW62Af72WPl9pGvOwOzPQIE= Name: OSGI-OPT/src/org/osgi/service/wireadmin/WirePermission.java SHA1-Digest: Dy8T3PorA7Sg4nFsBec9zGytghI= Name: OSGI-OPT/src/org/osgi/util/mobile/UserPromptCondition.java SHA1-Digest: 1bDa8wEvznUWgaDZC7JUNTU+IGg= Name: org/osgi/application/ApplicationServiceEvent.class SHA1-Digest: /c26oRC+nspfH/8hPzEXkoWzNVw= Name: OSGI-OPT/src/org/osgi/service/http/package.html SHA1-Digest: G6ohYZp0Ua+dfVXk1JcEsu9RKnM= Name: org/osgi/service/io/ConnectorService.class SHA1-Digest: VavkGpaWLx4EEuXzeKbZTOKgllA= Name: OSGI-OPT/src/org/osgi/service/startlevel/package.html SHA1-Digest: MFQ7fkXPac/yvAFeZIboTxTbT1M= Name: OSGI-OPT/src/org/osgi/service/application/ScheduledApplication.j ava SHA1-Digest: o+zkd1EkbFI7/AFscF7lGi4usMQ= Name: org/osgi/service/metatype/packageinfo SHA1-Digest: 12rYAKCuhPOR8UoeqXmJLChRNho= Name: org/osgi/service/dmt/spi/ReadWriteDataSession.class SHA1-Digest: yKiIP/rZmNSk9qIumF7FAehnU/M= Name: OSGI-OPT/src/org/osgi/service/event/package.html SHA1-Digest: 3sv3hQifkPNk1dbv9kHalClwQbo= Name: OSGI-OPT/src/org/osgi/framework/PackagePermission.java SHA1-Digest: XYhbVi1lS3DHP9aCI+gSZy9ciO0= Name: OSGI-OPT/src/org/osgi/service/deploymentadmin/DeploymentAdminPer mission.java SHA1-Digest: T3Ls66VqDZFomcjhcdeDx6izC2c= Name: org/osgi/service/cu/ControlUnitConstants.class SHA1-Digest: JnviKeITmy7nGASN3lcSPq7Y52k= Name: OSGI-OPT/src/org/osgi/service/component/ComponentContext.java SHA1-Digest: 9pTnoUKjVtRkS8jA5WXLtpkekAc= Name: org/osgi/framework/AdminPermission$1.class SHA1-Digest: mz7P0Otyu2h0HG3ki2DQui5WlrI= Name: OSGI-OPT/src/org/osgi/service/monitor/Monitorable.java SHA1-Digest: yHmA0yNZSGqvuOF/eLG8XOIFstA= Name: org/osgi/service/useradmin/UserAdminPermissionCollection.class SHA1-Digest: XupAJ6cd1uMu8e3tNZM1MJ+tUmk= Name: OSGI-OPT/src/org/osgi/service/permissionadmin/PermissionAdmin.ja va SHA1-Digest: oEjLG1gMLgiA2QU0MTV9H/0DeXM= Name: OSGI-OPT/src/org/osgi/service/obr/Capability.java SHA1-Digest: nyox6Pe5vwcyPxH/Hhi8rRmtwbw= Name: OSGI-OPT/src/org/osgi/service/upnp/package.html SHA1-Digest: ZkmZVB21qh+JCpNqy06CiFpMSmY= Name: org/osgi/service/condpermadmin/BundleSignerCondition$1.class SHA1-Digest: /N53rkETeJVKOxfFiODtOabmbT8= Name: org/osgi/service/cu/admin/spi/CUAdminCallback.class SHA1-Digest: EWsEEYP4Kf1ZIq0XFnu6oK+oY9o= Name: OSGI-OPT/src/org/osgi/service/dmt/spi/DataPlugin.java SHA1-Digest: SvSzSZAcNvmI7Hy4i3trwCqj0lU= Name: org/osgi/util/measurement/Measurement.class SHA1-Digest: guFlEYeHDiUafhDDZzIeS/+0RjE= Name: org/osgi/service/component/ComponentConstants.class SHA1-Digest: IznMX3uSAMUqSah0qxCO4rBQIX4= Name: org/osgi/service/event/EventAdmin.class SHA1-Digest: Xg8sitJGe08XQJwbwRwbEl+XVCA= Name: OSGI-OPT/src/org/osgi/util/position/packageinfo SHA1-Digest: AdxQwTNb1QuDyPLifIfxi/mNZMc= Name: OSGI-OPT/src/org/osgi/service/cm/ConfigurationPermission.java SHA1-Digest: mOGqzL7NlFwgN2XBEwnEzPikgYs= Name: org/osgi/service/cu/admin/spi/packageinfo SHA1-Digest: tAGXmhVqpTL/rAcGy2BpzkTxv28= Name: OSGI-OPT/src/org/osgi/util/measurement/packageinfo SHA1-Digest: LrE+4q8aGkvLK39jZoToYRkxpas= Name: OSGI-OPT/src/org/osgi/service/deploymentadmin/spi/DeploymentSess ion.java SHA1-Digest: JJopSgTxS+PE3i50HYC0UenjJ9I= Name: org/osgi/service/component/ComponentInstance.class SHA1-Digest: phLMerV1kAbfTzjy5iTEG7BpDhg= Name: org/osgi/service/power/PowerPermission.class SHA1-Digest: gjLlQtIFb/8R3p51AB91V4/N3bY= Name: org/osgi/framework/ServicePermissionCollection.class SHA1-Digest: OQwDkucwQpcRzLF6eeF93TQqkOw= Name: OSGI-OPT/src/org/osgi/service/prefs/Preferences.java SHA1-Digest: RmGY4mi004xeJhua+gFE6g2nQlU= Name: OSGI-OPT/src/org/osgi/framework/FrameworkListener.java SHA1-Digest: 6DJ3xzCHwfv8yH59c9Et4Dfd3vs= Name: org/osgi/service/wireadmin/Consumer.class SHA1-Digest: R2EfPMZ62DW3no7QQXZOudbH8js= Name: org/osgi/service/condpermadmin/ConditionalPermissionAdmin.class SHA1-Digest: nkHpXSx3k7g49g+Acm9uOhiGseQ= Name: org/osgi/service/deploymentadmin/spi/DeploymentCustomizerPermiss ion$1.class SHA1-Digest: /Zbz8KmOlcb2QxQkP04MMKYKuqQ= Name: org/osgi/framework/FrameworkEvent.class SHA1-Digest: xFeOstEiiBFej4mtD8yp85wHJJc= Name: org/osgi/service/cm/packageinfo SHA1-Digest: SSaveRLDphNF2i4reuPQlMtlHBc= Name: OSGI-OPT/src/org/osgi/framework/FrameworkEvent.java SHA1-Digest: fEEvrxpwikrLH1iOi1p5VOUXXlo= Name: org/osgi/service/device/Device.class SHA1-Digest: L4WX7Ne/13WpKrQorD985XDqFJQ= Name: OSGI-OPT/src/org/osgi/util/measurement/Measurement.java SHA1-Digest: R+ka1b07l02w56CUOtAj5yzesRQ= Name: OSGI-OPT/src/org/osgi/service/dmt/security/AlertPermission.java SHA1-Digest: JR07+7yRzPk7d+oukFXk86TXrWY= Name: org/osgi/service/cm/ConfigurationAdmin.class SHA1-Digest: yMXsmkbqaU3z1WIpL+WFRPRxzw4= Name: org/osgi/service/metatype/MetaTypeService.class SHA1-Digest: goHau7L6x6qHUEYMwqN2gVqNwIY= Name: OSGI-OPT/src/org/osgi/service/event/EventHandler.java SHA1-Digest: dqhgOCrJuUzFPF2POMNBpb/PIIg= Name: org/osgi/service/deploymentadmin/spi/packageinfo SHA1-Digest: j37sXUKnNExva0aaoDgsamgQBTo= Name: org/osgi/service/upnp/UPnPDevice.class SHA1-Digest: KQeCYy3kJx1u3WzwTC1swF92VLI= Name: OSGI-OPT/src/org/osgi/application/ApplicationServiceListener.jav a SHA1-Digest: l0+C8TifMs7pS2XqDNZr/DSlAaE= Name: org/osgi/service/cm/ConfigurationEvent.class SHA1-Digest: xylPsbmrunCJOYgZaMvDlAwqwNw= Name: org/osgi/framework/ServiceReference.class SHA1-Digest: XM81id3TKH2CC+l2J5pX6zGqHe0= Name: OSGI-OPT/src/org/osgi/service/power/PowerManager.java SHA1-Digest: SfoQwBBXQsSy1PS1zuj6YlGFIRQ= Name: OSGI-OPT/src/org/osgi/service/power/PowerPermission.java SHA1-Digest: qGJt+Qifuji0aazzCmATAqd0yaU= Name: OSGI-OPT/src/org/osgi/framework/package.html SHA1-Digest: 6LjsbUqDCkihDmXnk+Lefo13Ky4= Name: OSGI-OPT/src/org/osgi/util/measurement/package.html SHA1-Digest: 5DKUiSB1o8mFwQye6sL5vcy/rdA= Name: OSGI-OPT/src/org/osgi/service/wireadmin/BasicEnvelope.java SHA1-Digest: mI90KcFFqA3/4P3qThz/nmpfCgQ= Name: OSGI-OPT/src/org/osgi/service/url/package.html SHA1-Digest: O2D1mGYAGpLz2CqcLLfQu3IiHEY= Name: org/osgi/service/condpermadmin/ConditionInfo.class SHA1-Digest: 3I1jjoqCmG8h2xCAoVOqY65nnJg= Name: OSGI-OPT/src/org/osgi/service/http/HttpService.java SHA1-Digest: C8eyhdpsDk50AymILNUEZiRrsfk= Name: org/osgi/service/condpermadmin/Condition.class SHA1-Digest: lwHHRcwvBs2XuidM3KKKa5o95UM= Name: org/osgi/service/deploymentadmin/spi/ResourceProcessorException. class SHA1-Digest: cDjKPrKuMMI/rdc4HwF6mX3mZhY= Name: org/osgi/service/obr/CapabilityProvider.class SHA1-Digest: aoTJEN0jOkw6USeFqHU5koDKkSE= Name: OSGI-OPT/src/org/osgi/service/cu/diag/package.html SHA1-Digest: C3LVOlvIiHr9gQIzyldd2JdQ7X4= Name: OSGI-OPT/src/org/osgi/service/cu/admin/ControlUnitAdminListener. java SHA1-Digest: u+fOUZKh++oFX6i0rYZKnONp06c= Name: OSGI-OPT/src/org/osgi/service/packageadmin/package.html SHA1-Digest: Bj9GXlY07lWgrR3nRmivFopJT4c= Name: OSGI-OPT/src/org/osgi/service/obr/CapabilityProvider.java SHA1-Digest: CKV4bbnEKZIMLyZddvA7JE3CaBA= Name: org/osgi/application/packageinfo SHA1-Digest: pDqN9ClnwLizz545hj3c1EQ2j/s= Name: OSGI-OPT/src/org/osgi/service/packageadmin/PackageAdmin.java SHA1-Digest: jgKV28ixwXXFCtlaJbYIwWnpwIQ= Name: OSGI-OPT/src/org/osgi/service/useradmin/Group.java SHA1-Digest: FkSKO399q6MqDSiXQp+fWVGG+lU= Name: OSGI-OPT/src/org/osgi/util/gsm/IMEICondition.java SHA1-Digest: oopKje1PqJ1+rcChWbDxynbs0To= Name: org/osgi/service/wireadmin/Wire.class SHA1-Digest: iFZ0p2Z2aZ88LFqGjzFJL5GQjcQ= Name: OSGI-OPT/src/org/osgi/service/application/ApplicationException.j ava SHA1-Digest: RVsoxQ7c7N0pRywFWlP4NG+0vyE= Name: org/osgi/util/xml/XMLParserActivator.class SHA1-Digest: DUM/d7zvY3QIn8Y9AHjXZj9lXJg= Name: OSGI-OPT/src/org/osgi/service/url/URLStreamHandlerSetter.java SHA1-Digest: WoaFh3jFksKnJtowoOcGil1lfc0= Name: OSGI-OPT/src/org/osgi/service/url/URLConstants.java SHA1-Digest: uUkC7ksE30XHYJe98aK4xio7d0k= Name: org/osgi/service/provisioning/ProvisioningService.class SHA1-Digest: 2enwDQ0cdeGu1cEbB6DUlPlyXPM= Name: OSGI-OPT/src/org/osgi/framework/BundleContext.java SHA1-Digest: 4oGUg2gOAI1uDZYom8edrugS+X4= Name: OSGI-OPT/src/org/osgi/service/cm/Configuration.java SHA1-Digest: ZzcjFEfeszinFA5RYTyDBy+/J/w= Name: org/osgi/framework/BundleListener.class SHA1-Digest: i8nGydy6c5gllC1tJommNsg3g2E= Name: org/osgi/service/wireadmin/Envelope.class SHA1-Digest: 8XA42C+2d5zrhH2PiXJifei6Zlk= Name: OSGI-OPT/src/org/osgi/framework/BundleListener.java SHA1-Digest: v3fnfEdX8WQAWy5dq80Pjvkr7Ms= Name: OSGI-OPT/src/org/osgi/service/metatype/MetaTypeProvider.java SHA1-Digest: 6sTAm7idvShK7nzOGg0efZYzkwc= Name: OSGI-OPT/src/org/osgi/service/event/EventAdmin.java SHA1-Digest: 3qXULV8Kuy48mUOYBsoiArc76Is= Name: org/osgi/application/Framework.class SHA1-Digest: 8rVlWd6ctJ/vMbwVSbofWErF08k= Name: OSGI-OPT/src/org/osgi/service/useradmin/packageinfo SHA1-Digest: DDU8JQJkBb31PREu8WJ3V67uA2k= Name: org/osgi/service/application/ApplicationDescriptor$Delegate.clas s SHA1-Digest: WP95tngbuSNWDuH4sNmRw3wkhfA= Name: org/osgi/framework/ServiceRegistration.class SHA1-Digest: WGGc/8cwaDGT3xvg/H2uVmsR3uk= Name: org/osgi/service/deploymentadmin/spi/ResourceProcessor.class SHA1-Digest: hKDwQIEJJwIuUQuqI6Zb39xPYGQ= Name: org/osgi/service/startlevel/StartLevel.class SHA1-Digest: OXOGNIbAY73hufQm8C41jquJaP0= Name: org/osgi/service/packageadmin/packageinfo SHA1-Digest: q2e/6qm6oqzsS8+U/d1SBSePrGc= Name: OSGI-OPT/src/org/osgi/framework/ServiceFactory.java SHA1-Digest: SevWQu5+1ZTqNTg9/QZut/K4GkQ= Name: org/osgi/service/device/Match.class SHA1-Digest: MVluSSzzfjsSZFvs69Fr6E+KDZg= Name: OSGI-OPT/src/org/osgi/service/dmt/DmtAdmin.java SHA1-Digest: TGZLegm4o2lqhrz0Zr1DtdU6xsE= Name: org/osgi/service/application/ApplicationAdminPermission$SignerWr apper.class SHA1-Digest: bIyCXzb8nbxQZp5cMupUGR6AgSg= Name: org/osgi/service/http/packageinfo SHA1-Digest: GTsqAoL/9ZrepfbDEkYZwrDdlhE= Name: OSGI-OPT/src/org/osgi/service/http/NamespaceException.java SHA1-Digest: wiZS1BqoAyHyDYQCH3mlfDFqO+s= Name: OSGI-OPT/src/org/osgi/service/dmt/DmtSession.java SHA1-Digest: p/W9EgQwOATgpBOfnNOr+2xHcco= Name: org/osgi/service/deploymentadmin/spi/DeploymentSession.class SHA1-Digest: 9ztMVfqvwjY1XhC8/d34zwV3rlg= Name: OSGI-OPT/src/org/osgi/service/application/ApplicationAdminPermis sion.java SHA1-Digest: 14fUfFCitc31jFAroL3v6i/f3qo= Name: org/osgi/service/wireadmin/WirePermission.class SHA1-Digest: WEqqMnYEc/r00Q38Km01pmBmmGE= Name: org/osgi/framework/BundlePermissionCollection.class SHA1-Digest: g9vHhDMJy/zK0pFy8YQ816+9pEY= Name: org/osgi/service/dmt/spi/TransactionalDataSession.class SHA1-Digest: bQ3dZWz2U1L+nY815VYKHrxfq88= Name: OSGI-OPT/src/org/osgi/service/component/ComponentInstance.java SHA1-Digest: hWZT3nei1PmR5TVXzuziajDsdvs= Name: org/osgi/service/useradmin/packageinfo SHA1-Digest: rDwZ7MRtHDj7ssdYe2ua4dS2CnE= Name: org/osgi/service/cm/ConfigurationPlugin.class SHA1-Digest: 3cFVS8/+Wkgi1+vvXweRyHAwnGA= Name: OSGI-OPT/src/org/osgi/service/wireadmin/WireAdminListener.java SHA1-Digest: 6QMDWba+JyuX4QyBU4A9MmmKx+w= Name: xmlns/scr/scr.xsd SHA1-Digest: lcbTBKKglEkFKQA+rST+n5rG4JM= Name: org/osgi/util/tracker/ServiceTracker.class SHA1-Digest: /kTi20d1ULiX/sDElAP/6nOWKNA= Name: OSGI-OPT/src/org/osgi/service/dmt/package.html SHA1-Digest: 9VmdJG/Btsu1e+pEruR+I2OkU7o= Name: OSGI-OPT/src/org/osgi/service/condpermadmin/ConditionInfo.java SHA1-Digest: wdk6Bh8W1hxcoHWpt8dutdxHpi8= Name: OSGI-OPT/src/org/osgi/service/cu/diag/packageinfo SHA1-Digest: vxGu26whC2hV9Hed7gyKdkZ0Hhc= Name: OSGI-OPT/src/org/osgi/service/cu/admin/spi/package.html SHA1-Digest: mMC4YaOuU4MeeVHHq0/EVB2Xu3M= Name: OSGI-OPT/src/org/osgi/service/metatype/packageinfo SHA1-Digest: +OZYM1KMfpGbFKbbTDbz5KnAi+8= Name: OSGI-OPT/src/org/osgi/service/cu/ControlUnitConstants.java SHA1-Digest: sKzHhzRnbr+OKxtlarA5xRpvUhE= Name: org/osgi/service/log/LogListener.class SHA1-Digest: +/b/PIKC0rl0Von4ak1vrlviW7E= Name: org/osgi/service/upnp/UPnPIcon.class SHA1-Digest: q6uTRghnAVVMArMFN1uXuaCbWew= Name: org/osgi/service/monitor/MonitorPermission.class SHA1-Digest: HdYHWMHcNeL08rNNGzxUQu4yGGU= Name: OSGI-OPT/src/org/osgi/service/io/ConnectionFactory.java SHA1-Digest: TTTsymDChPwTHS5AreSlrZ1kfaU= Name: OSGI-OPT/src/org/osgi/service/cu/admin/packageinfo SHA1-Digest: VaFkKNyUSta4dlFZzAFv8p8x+GM= Name: org/osgi/framework/Constants.class SHA1-Digest: FYtBCi6mZX9IlIks5H8VhtZDTw0= Name: OSGI-OPT/src/org/osgi/service/cu/admin/spi/packageinfo SHA1-Digest: 32wRsfMZY5Pg2qliMTrDU1oqV8A= Name: org/osgi/service/condpermadmin/BundleLocationCondition.class SHA1-Digest: WDTfbd01QslgSJDIDOIjhqPsUf0= Name: OSGI-OPT/src/org/osgi/service/monitor/MonitoringJob.java SHA1-Digest: N7Ph2xj+E0ZoJ9Xwe7pN3wiP4Gw= Name: OSGI-OPT/src/org/osgi/util/xml/package.html SHA1-Digest: MtmCdy3UvVScIVKYKMvCRqptG70= Name: org/osgi/service/application/ApplicationAdminPermission.class SHA1-Digest: 3qX7d9NZ/KOq1JCdUrwygw+nr/I= Name: org/osgi/service/cm/ManagedService.class SHA1-Digest: FKEJqaxfU5mWlrEkJWq5pXK1VCI= Name: OSGI-OPT/src/org/osgi/framework/AdminPermission.java SHA1-Digest: uO/pQ74d6yeAU7x2Ny9pqiUsoU4= Name: OSGI-OPT/src/org/osgi/application/package.html SHA1-Digest: fROC41D1tr2Bo5dSEN2WiK/zSHk= Name: OSGI-OPT/src/org/osgi/service/url/AbstractURLStreamHandlerServic e.java SHA1-Digest: v0YYUu9Py5CGhygWmA9AwU/LMiY= Name: OSGI-OPT/src/org/osgi/framework/InvalidSyntaxException.java SHA1-Digest: mxYpCmLI7RoDHu2/WeGhLCN6g3Q= Name: OSGI-OPT/src/org/osgi/application/Framework.java SHA1-Digest: I0MrOyx7jmddAQDD38XvWdh4bS0= Name: OSGI-OPT/src/org/osgi/service/cu/ControlUnitException.java SHA1-Digest: nSGm679DX05aJz9hxfFrqHjCwsE= Name: OSGI-OPT/src/org/osgi/util/tracker/package.html SHA1-Digest: CyDeJ4TpFCwFnhHiV5UrMgc5TcU= Name: OSGI-OPT/src/org/osgi/service/metatype/ObjectClassDefinition.jav a SHA1-Digest: hS2wfMgUD1pXyGceaGHP6e7UVd8= Name: OSGI-OPT/src/org/osgi/service/application/ApplicationDescriptor. java SHA1-Digest: Lu8/lPf2aXO+BXdLjjX7afBFOKQ= Name: org/osgi/service/monitor/MonitoringJob.class SHA1-Digest: kWmz51DUngfq9R0XrhofymxXaZA= Name: org/osgi/service/application/ApplicationHandle$Delegate.class SHA1-Digest: t+1y5D4tgFLLvDMMFrcJ2bksnz4= Name: org/osgi/framework/BundleEvent.class SHA1-Digest: EGZVOfz48+NXaK0ptmnvVuLt+K0= Name: OSGI-OPT/src/org/osgi/service/event/Event.java SHA1-Digest: VySCXv7lv8vjDNSRz1lw0X9KTwM= Name: org/osgi/service/monitor/MonitorAdmin.class SHA1-Digest: mDhnFj4X+v4fZCMNl2dRM2tP5VM= Name: OSGI-OPT/src/org/osgi/util/position/Position.java SHA1-Digest: O8+ZoWQEUBDFupwWpOVvvSH1byw= Name: OSGI-OPT/src/org/osgi/service/condpermadmin/packageinfo SHA1-Digest: Rh3koJMOGykODlDQYP0UjRittzg= Name: OSGI-OPT/src/org/osgi/service/cm/ManagedServiceFactory.java SHA1-Digest: anATJOIuoZbsx3DVgbVcqzgq5MI= Name: xmlns/metatype/metatype.xsd SHA1-Digest: pLakeqsQDGYaHBY5WgD0JzJhKwQ= Name: org/osgi/service/dmt/DmtAdmin.class SHA1-Digest: X9dk2BI9y7LO/B2p0Rr4GJFTTF8= Name: org/osgi/service/upnp/UPnPStateVariable.class SHA1-Digest: k9Xlup9ysmQqWA4aK/Kuv1wWENU= Name: OSGI-OPT/src/org/osgi/application/ApplicationContext.java SHA1-Digest: fdQrIXbFHanUO8JMNefpWWKrEfQ= Name: org/osgi/service/device/DriverSelector.class SHA1-Digest: TrJ7mID5NHqKCQN0lQRBFIj7cgU= Name: OSGI-OPT/src/org/osgi/service/monitor/packageinfo SHA1-Digest: V/l67j6XY9B0YweADgKYQsqvR7o= Name: org/osgi/service/cu/admin/ControlUnitAdminListener.class SHA1-Digest: 3RjDxVxQhC/y349e2j2PzpZikIM= Name: OSGI-OPT/src/org/osgi/service/cu/diag/Status.java SHA1-Digest: SaElWrjun2ShYZWqK0gqPSpj+f8= Name: org/osgi/util/gsm/IMEICondition$1.class SHA1-Digest: is3Okyjv30rhAfiD7Ph31Vf0xoc= Name: org/osgi/service/cm/ConfigurationPermissionCollection.class SHA1-Digest: O1hmDkp9Px2gcL2rXsNr7/yKi0Y= Name: OSGI-OPT/src/org/osgi/service/obr/Resolver.java SHA1-Digest: z+U0OS3enkLupaq6Qpv2dZceP/E= Name: org/osgi/service/url/URLStreamHandlerService.class SHA1-Digest: L3Ka+RawluUaRfXbNG4mKxHfkYE= Name: org/osgi/service/cm/ManagedServiceFactory.class SHA1-Digest: Rmv3RC/v+kCEevjKkvwEDkiGXYU= Name: OSGI-OPT/src/org/osgi/service/component/ComponentException.java SHA1-Digest: cuBw8MU/eC1/EIiM1E2jw/moJdc= Name: org/osgi/util/xml/packageinfo SHA1-Digest: /Ht2bRt72LubFMTKzr4JnJMD+Qo= Name: org/osgi/service/dmt/DmtSession.class SHA1-Digest: 35TEUI09mT0eEf0muCgaTKDja+8= Name: org/osgi/service/obr/RepositoryPermission.class SHA1-Digest: 0CU6tJ/6HUnEcfrBvvJgAfX9azA= Name: OSGI-OPT/src/org/osgi/service/useradmin/User.java SHA1-Digest: cCNs+kCceR+2aVHt8D4LZ/hJyvo= Name: org/osgi/service/upnp/UPnPService.class SHA1-Digest: h0ZzY3KVds3j269MIh/cTI8UxVM= Name: OSGI-OPT/src/org/osgi/service/log/LogService.java SHA1-Digest: XlbhnzZeBa1+dgEaguyfS0dW/r8= Name: OSGI-OPT/src/org/osgi/framework/ServiceReference.java SHA1-Digest: fl5dekKBMcSyD/FpYa25wJe2Uwo= Name: org/osgi/framework/BundlePermission.class SHA1-Digest: QHvPmidiN/AsOxPqKvIKy3TCbTk= Name: OSGI-OPT/src/org/osgi/service/upnp/UPnPDevice.java SHA1-Digest: kaBFG7bcycA6aKjyvCHAQtEyGxs= Name: org/osgi/service/cu/diag/packageinfo SHA1-Digest: SBrzJur+yUG4AJqUayUYpurQ8OA= Name: OSGI-OPT/src/org/osgi/util/xml/XMLParserActivator.java SHA1-Digest: Hm4M9vUY8aoWtcRcHR2j2lg/P64= Name: org/osgi/framework/Configurable.class SHA1-Digest: 18qBACzFINu+0geD6D309P2V8fc= Name: OSGI-OPT/src/org/osgi/service/upnp/UPnPEventListener.java SHA1-Digest: gcwrDD7/TllNl6YMJs4hJ1oRNTM= Name: OSGI-OPT/src/org/osgi/service/component/package.html SHA1-Digest: FVFzVyTBztjPhks3ZErbap7jONg= Name: OSGI-OPT/src/org/osgi/service/wireadmin/Wire.java SHA1-Digest: GsmRY0oQzmqZxRRGe6bX9Yb8fRQ= Name: org/osgi/service/cu/admin/HierarchyListener.class SHA1-Digest: ixN/p9SW2jrS9xpDQH3cpEtWPI0= Name: org/osgi/framework/FrameworkUtil.class SHA1-Digest: O4Y3fXVSxHA/DH3AVOlXjs9WMPI= Name: OSGI-OPT/src/org/osgi/service/device/DriverSelector.java SHA1-Digest: 4MjbmbjLZ4jI3w9yJZNQnuwvQuQ= Name: OSGI-OPT/src/org/osgi/service/log/LogEntry.java SHA1-Digest: Dk6PD+JzyYQKTorjiQRnv/KQl70= Name: OSGI-OPT/src/org/osgi/framework/SynchronousBundleListener.java SHA1-Digest: GronbetjpoQOJBsTdUk5aGpgO+k= Name: org/osgi/service/packageadmin/RequiredBundle.class SHA1-Digest: hGBAbRrVCxPXttR8Y44dmc/z8tY= Name: OSGI-OPT/src/org/osgi/service/log/packageinfo SHA1-Digest: C/tTETCChTdUBkldeL8+qryXBZk= Name: org/osgi/service/io/ConnectionFactory.class SHA1-Digest: QkjPZFQudSk3QuyvasvZMGwPc/U= Name: org/osgi/service/metatype/MetaTypeInformation.class SHA1-Digest: ls7B5NDiw7jOnDI60Kpba4lkDvY= Name: OSGI-OPT/src/org/osgi/service/wireadmin/Consumer.java SHA1-Digest: 3CZpkRuq+H0rB78969bjlTisdYg= Name: org/osgi/framework/AllServiceListener.class SHA1-Digest: kunjsUR8Az5n9giVGX6gYbrwwt0= Name: OSGI-OPT/src/org/osgi/service/wireadmin/WireConstants.java SHA1-Digest: vaTEJ4ddTYZAG26Rnj1DqykTShw= Name: OSGI-OPT/src/org/osgi/service/cm/packageinfo SHA1-Digest: swJpbMwkcW17hegi+m8yZRfMNbs= Name: OSGI-OPT/src/org/osgi/service/log/package.html SHA1-Digest: TiBGjVA8OJBIMJXJvg/p4NMoDw4= Name: org/osgi/framework/InvalidSyntaxException.class SHA1-Digest: /zd42rwYZhn/pk3WyxEgkZC9GdM= Name: OSGI-OPT/src/org/osgi/framework/ServicePermission.java SHA1-Digest: Mv88hHvFRd11mm5LK6L5ckFbxQA= Name: OSGI-OPT/src/org/osgi/framework/BundleException.java SHA1-Digest: IYVD0TMxSMkZwD69cE9zXIcCH0M= Name: OSGI-OPT/src/org/osgi/service/metatype2/package.html SHA1-Digest: RznCGhpQn8A/x4icHmSBthZhtUw= Name: OSGI-OPT/src/org/osgi/service/url/packageinfo SHA1-Digest: 2aVYRfrBEJKl/MTFf+l3lNTomno= Name: org/osgi/service/prefs/Preferences.class SHA1-Digest: MOVdjuMvZJ+t+7apBqJ9LQp8mE8= Name: OSGI-OPT/src/org/osgi/service/monitor/StatusVariable.java SHA1-Digest: tG4cC1tYIU3iGPwyTlDCo3dCeQc= Name: org/osgi/service/cm/ConfigurationListener.class SHA1-Digest: lQw2EkJTROwX0e6GW4CvEALxSiU= Name: OSGI-OPT/src/org/osgi/service/io/package.html SHA1-Digest: l9OPf1+194HkSd+XgZVEBH4M9GU= Name: org/osgi/framework/ServicePermission.class SHA1-Digest: jKVa1SWXBnnERDA9iYwrDsX7c40= Name: OSGI-OPT/src/org/osgi/service/dmt/security/package.html SHA1-Digest: whoP8/d7jgzZNzoaHXuhxHCbTz8= Name: org/osgi/service/device/packageinfo SHA1-Digest: xjp+SemDrxc/cFDhJJuM4HbIwtM= Name: org/osgi/util/measurement/State.class SHA1-Digest: 9FG1LLRwkaM6b5rPCkItcWwPRvA= Name: OSGI-OPT/src/org/osgi/service/metatype2/ExtendedAttributeDefinit ion.java SHA1-Digest: xmHPTtybcejGwrJU9QNIahHY97I= Name: OSGI-OPT/src/org/osgi/service/dmt/DmtException.java SHA1-Digest: SK1HtdP5zAwlc6jwluOhIaTwblA= Name: org/osgi/util/gsm/IMSICondition.class SHA1-Digest: Z10wVPlxgZFmKsI3OyFtlnOvmBo= Name: org/osgi/service/deploymentadmin/DeploymentPackage.class SHA1-Digest: ozPSt9nZkN+/+wauFXWMlLEJZXA= Name: org/osgi/service/cu/ControlUnitException.class SHA1-Digest: unA4Q2AuLlI3gu+W/H3YmGonxK8= Name: org/osgi/service/url/URLConstants.class SHA1-Digest: 8QXjuK0scEr7CqSm85NWfekrUcI= Name: org/osgi/service/condpermadmin/BundleLocationCondition$1.class SHA1-Digest: y1/479NLdddu5BOaMNv35cMAwtw= Name: OSGI-OPT/src/org/osgi/service/obr/Requirement.java SHA1-Digest: FJaAlIC2mR543zWVI64F8a0LABE= Name: OSGI-OPT/src/org/osgi/service/component/packageinfo SHA1-Digest: 0hwHEtU5kg9gCJWcs96xkNyu3YM= Name: org/osgi/service/cm/Configuration.class SHA1-Digest: JNEiNov4hbxT16jDJJOuu8PlJX0= Name: org/osgi/application/ApplicationContext.class SHA1-Digest: Bj5kveptf1sqGYgjmvlvtWDrFiY= Name: org/osgi/service/event/Event.class SHA1-Digest: hZf/IsSprdeWA/b/rtgxfgkKp08= Name: org/osgi/service/useradmin/UserAdminListener.class SHA1-Digest: ecv3/d4I/yvOORq7tjHqoocGyLA= Name: org/osgi/service/condpermadmin/packageinfo SHA1-Digest: ET8wMtOgd8NVfSYfz6MsDw2VSqg= Name: OSGI-OPT/src/org/osgi/service/wireadmin/WireAdmin.java SHA1-Digest: KoNYbhGurbwGsS7jIbHpWJAQ4OU= Name: OSGI-OPT/src/org/osgi/service/deploymentadmin/BundleInfo.java SHA1-Digest: +ccZ6r7VnWgxhqIHhDcbrO42GPM= Name: OSGI-OPT/src/org/osgi/service/io/packageinfo SHA1-Digest: JhqNy4UqEDEoBh+4+NkGiioi8DE= Name: OSGI-OPT/src/org/osgi/service/deploymentadmin/spi/ResourceProces sor.java SHA1-Digest: Gt17M7sJWLpDXefsoLEPUyGKyIk= Name: OSGI-OPT/src/org/osgi/service/cu/ControlUnit.java SHA1-Digest: oFxMtfIkRcZKBcZs9ehzr+IdD+I= Name: org/osgi/util/position/packageinfo SHA1-Digest: PbtLlLbYEWE1O2wXjTc4nCrq+28= Name: OSGI-OPT/src/org/osgi/service/dmt/spi/ReadableDataSession.java SHA1-Digest: 2HrkfztxoAG7XhEWx/h4H7IMHXU= Name: OSGI-OPT/src/org/osgi/service/upnp/UPnPIcon.java SHA1-Digest: 5gLYKaLXvB9rZuVny5PivyLzChw= Name: OSGI-OPT/src/org/osgi/service/device/packageinfo SHA1-Digest: X7+h/C2aoEYpOu9Cr5EuPlpQapM= Name: OSGI-OPT/src/org/osgi/service/dmt/DmtData.java SHA1-Digest: F7OTBRKzlm8miPw0uu6HMvaNHIs= Name: org/osgi/service/log/packageinfo SHA1-Digest: jXICWyjXCCq72ZS6u+28DfBdV4Y= Name: org/osgi/service/http/HttpService.class SHA1-Digest: dwgIi9/mo+fjRq8Bj1dAnl12v9Q= Name: org/osgi/util/tracker/packageinfo SHA1-Digest: ++DQ3F6VKGd/ZYzeeF++C+Ugglk= Name: OSGI-OPT/src/org/osgi/service/condpermadmin/package.html SHA1-Digest: SwyyIqDL/0w/jFyUPg89gI3hHnM= Name: OSGI-OPT/src/org/osgi/service/packageadmin/ExportedPackage.java SHA1-Digest: lLpyQR7jUrl+9sFR4HrUAfKIvgo= Name: org/osgi/service/cu/StateVariableListener.class SHA1-Digest: H4GcoenoPIjwME7RfW+7NH3BZHA= Name: org/osgi/service/event/EventConstants.class SHA1-Digest: qHtQYR4PAHoUU4pIGJQlzpll3Vs= Name: org/osgi/service/power/PowerManager.class SHA1-Digest: znEPIP204IMvjlnhC5BckGq5GEM= Name: org/osgi/framework/AdminPermission.class SHA1-Digest: QSHxDZl8ck7ONdGwwYyZ7xblkrk= Name: org/osgi/service/dmt/security/DmtPrincipalPermissionCollection.c lass SHA1-Digest: fl5WO6H3vXo3A2nMJyseqBJ6Gj4= Name: OSGI-OPT/src/org/osgi/service/startlevel/StartLevel.java SHA1-Digest: PnrNPYmAK9D1m+5n3TOFlmt4ZFI= Name: org/osgi/service/log/LogReaderService.class SHA1-Digest: mQGpcQL435FFxMidZo1KHVerEvA= Name: OSGI-OPT/src/org/osgi/service/permissionadmin/packageinfo SHA1-Digest: lVo17PxbmNHUFsB4AkhWwquroU4= Name: OSGI-OPT/src/org/osgi/util/tracker/packageinfo SHA1-Digest: lBRPVvQYfrZPBkoHiQz7XvJEDXM= Name: OSGI-OPT/src/org/osgi/service/http/packageinfo SHA1-Digest: ezMsVTV7Bq/uEd6jzZecHXT/TWs= Name: OSGI-OPT/src/org/osgi/service/metatype/MetaTypeService.java SHA1-Digest: syvU3Du28E6aVDpByV8IuebtZfA= Name: org/osgi/service/condpermadmin/BundleSignerCondition.class SHA1-Digest: S2p7dtxvYf8InlXleS94xL2yzMc= Name: OSGI-OPT/src/org/osgi/application/packageinfo SHA1-Digest: 8w6jT9w+Qbw3WatJKUvk8RBmRrY= Name: OSGI-OPT/src/org/osgi/service/dmt/spi/TransactionalDataSession.j ava SHA1-Digest: o4ziOKuyVQUj8WTaBCG0G6/bhcc= Name: org/osgi/framework/PackagePermissionCollection.class SHA1-Digest: A+SE4xQ0MUIR0FdsVUb5sfh43to= Name: org/osgi/service/event/TopicPermission.class SHA1-Digest: ceU+SoJpJxvVe6COcubZF9Ouk9A= Name: org/osgi/service/wireadmin/WireAdmin.class SHA1-Digest: 3FDHgXnYzgty1GLYBSCnZj6xOwo= Name: OSGI-OPT/src/org/osgi/service/metatype/MetaTypeInformation.java SHA1-Digest: Sa2Pbp7dmu201yK0D5ctrKBTWDs= Name: org/osgi/service/dmt/security/DmtAlertPermissionCollection.class SHA1-Digest: I7DhtiDc4xKgLfhMFNdBYzzuIE4= Name: OSGI-OPT/src/org/osgi/service/deploymentadmin/packageinfo SHA1-Digest: BdNv3qU6clGeQ08Q/hEwQ5W2b5s= Name: OSGI-OPT/src/org/osgi/service/dmt/security/DmtPermission.java SHA1-Digest: LfHlLy17Qt5WHhYOwY+ZIWK+bFs= Name: OSGI-OPT/src/org/osgi/framework/BundlePermission.java SHA1-Digest: 7w2L+6vGpanXZbtQycuuRvjojdg= Name: OSGI-OPT/src/org/osgi/service/startlevel/packageinfo SHA1-Digest: ZtI4LPts+ej3ZKhkwzKl7k88X3Y= Name: org/osgi/service/prefs/packageinfo SHA1-Digest: NuBwiqg/aZ/iU0o/MUoquvFe1fY= Name: org/osgi/service/log/LogService.class SHA1-Digest: DtRCmfolGZ+xf3iRkZeKR17BV54= Name: org/osgi/service/metatype2/ActionDefinition.class SHA1-Digest: H2v0tkPQnLRs1O4zB7skwtVCKVU= Name: org/osgi/service/wireadmin/BasicEnvelope.class SHA1-Digest: nSosrAjvhFAvNPWc5tf0bPIvpHo= Name: org/osgi/service/application/ApplicationDescriptor$1.class SHA1-Digest: 5GP1mrViQ6evFo96tdcn6IV6auk= Name: OSGI-OPT/src/org/osgi/service/power/package.html SHA1-Digest: IiHn0SFlu3FXx6B5zvaR1MrELXo= Name: OSGI-OPT/src/org/osgi/service/deploymentadmin/package.html SHA1-Digest: jTT4VA+HdSHdVoB4+hOzIVPUH34= Name: org/osgi/service/dmt/security/DmtPermissionCollection.class SHA1-Digest: Q2uf4w3wM4EyhCwqwBiXrY5VWhA= Name: org/osgi/service/dmt/DmtData.class SHA1-Digest: wHi+2JSkwIExyDlljUpuvQFdZ3M= Name: org/osgi/service/monitor/MonitorListener.class SHA1-Digest: XITDc+NQ4PBKhl9mlYfy7131Sy4= Name: OSGI-OPT/src/org/osgi/service/event/packageinfo SHA1-Digest: 3djsz28O3PA4KQvnAoq/7U2WAE0= Name: OSGI-OPT/src/org/osgi/service/url/URLStreamHandlerService.java SHA1-Digest: Ba+UPH5X54xGSycPomy4gXtaN68= Name: org/osgi/util/tracker/ServiceTracker$Tracked.class SHA1-Digest: gbIKMJ4IygI4kQ0Emv/mrxZoOEU= bnd-1.50.0/biz.aQute.bndlib/src/test/signing/META-INF/test.RSA0000644000175000017500000000170211656076535023237 0ustar drazzibdrazzib0‚¾ *†H†÷  ‚¯0‚«10 *†H†÷ 0  *†H†÷  ‚^0‚Z0‚ÃCFG]0  *†H†÷ 0t1 0 UUS10 UTexas10 UAustin10U ACME Cert Authority10U ACME Inc10U John Smith0 051007100101Z 131224100101Z0t1 0 UUS10 UTexas10 UAustin10U ACME Cert Authority10U ACME Inc10U John Smith0Ÿ0  *†H†÷ 0‰«„¦Ù·öC0ˆÌ‰ÂF˜ ›iǼ·.û véÓž#8­![30E ØO1$"QõÒx{O9äÂëUrœ;™M£;Ú©‘iåî@>„‚€ß«ŽýO—“ç÷–ø±`G`d?©„z¿æ‹žoß÷Z(Ž3) Ã¦Ž‘ÐËP¤ÿÆO0  *†H†÷ …w/Š× "„œ¢HÜœÎ2- &ü0¾ìô;¢ âvi#Oöšøm‚k‰âŸmS‚ ƒÄ•bþØYe¿ŸêP¿¾U¸ïŒƒ£®7*æWš¤ê¾þR^µ5ÞEìŸ%EÚ P»}?8DúòÞŒ.Þ@ãùídº×©¦XL)Ájèbvn1‚%0‚!0|0t1 0 UUS10 UTexas10 UAustin10U ACME Cert Authority10U ACME Inc10U John SmithCFG]0 *†H†÷ 0  *†H†÷ €lþ•²€øù˜ñ§w£è?Ó” °"¸žu x×Õ ¼P¦LÙé2XexX|³ æî‰Ê5bË6É&îÈ‹õžcQµ¹õÇ-îÁ´b™‰…ÅFÇ: #ÈÑØEìZiãœ3ïVœešë¼:=å—Ó6£xjÒæz¨ bbxBŸZ …uê‡ý'Íê¡·6cú»˜­–`ð*c•ª5»RaVŸˆ8ߖƵš¨/1Ï Þß Os}r–žF Ä¡{)’/¿XIn§fI:HÈ÷[«–Õôà}“*ÞнcÃcO„÷Q@Û ÉÈ=õŠjaˆWn2¯é0û û0ÓB)ìHQe ¡þHx^d‘6“IfÀÉ,¦Ðï&€bFOãaØ«[V{’ÝèY4†|Õã\;V=eH\¥¬”Ìà(p°¼@îåºûCºOÎÔV|‘ØëøjŽpög£ìóÜWž´:C“BC»<LJ‹ÝFv6´–\qoÎS0£³vÑJùÛf…€/3ÿIXãL!l‘ܽʱ|Ìäl9d^3W2™ašPw 6mWè×VåÎÔNë ³N†øÕŸr%‰[·6/4饸iê¨-žþšJŠ—œ£²!ä.\*Û [f‚Ú[š×®‡6ùŽ~)Ö<¹}ØÞ; .sVG²]·v°Ôùß *Z`§¬£"á&ÛÔøÅΦV Ëuä.ÇÎs¬¤ejîæ]©#þ[ ý¼^±?/ÕÔ×gåé y”ÚtÞô(Wc% êœGùúTB ÏãÏ•yRœ§™£ìê%†ê‚ñ¨÷¿Ë–úwJA}Bo/*;ƒ:/­"Øc¤Èò×u[ j^“!âHŽÔÜAS+ÖÑ`ß!†wi³¶*úæËÀIía€´—Ï?Rvà3€È^ÜØW–…Pk겕j¥¿ê&é ÿ¼vàX.509^0‚Z0‚ÃCFG]0  *†H†÷ 0t1 0 UUS10 UTexas10 UAustin10U ACME Cert Authority10U ACME Inc10U John Smith0 051007100101Z 131224100101Z0t1 0 UUS10 UTexas10 UAustin10U ACME Cert Authority10U ACME Inc10U John Smith0Ÿ0  *†H†÷ 0‰«„¦Ù·öC0ˆÌ‰ÂF˜ ›iǼ·.û véÓž#8­![30E ØO1$"QõÒx{O9äÂëUrœ;™M£;Ú©‘iåî@>„‚€ß«ŽýO—“ç÷–ø±`G`d?©„z¿æ‹žoß÷Z(Ž3) Ã¦Ž‘ÐËP¤ÿÆO0  *†H†÷ …w/Š× "„œ¢HÜœÎ2- &ü0¾ìô;¢ âvi#Oöšøm‚k‰âŸmS‚ ƒÄ•bþØYe¿ŸêP¿¾U¸ïŒƒ£®7*æWš¤ê¾þR^µ5ÞEìŸ%EÚ P»}?8DúòÞŒ.Þ@ãùídº×©¦XL)Ájèbvn×(Möˆ»â¡r^B± ðÿ«bnd-1.50.0/biz.aQute.bndlib/src/test/signing/.cvsignore0000644000175000017500000000001311656076535022543 0ustar drazzibdrazzibosgi-s.jar bnd-1.50.0/biz.aQute.bndlib/src/test/ClassParserTest.java0000755000175000017500000002546311656076535023055 0ustar drazzibdrazzibpackage test; import java.io.*; import java.lang.reflect.*; import java.net.*; import java.util.*; import junit.framework.*; import aQute.bnd.service.*; import aQute.lib.io.*; import aQute.lib.osgi.*; import aQute.libg.generics.*; import aQute.libg.reporter.*; class ConstantValues { public static final boolean f = false; public static final boolean t = true; public static final byte bt = Byte.MAX_VALUE; public static final short shrt = Short.MAX_VALUE; public static final char chr = Character.MAX_VALUE; public static final int intgr = Integer.MAX_VALUE; public static final long lng = Long.MAX_VALUE; public static final float flt = Float.MAX_VALUE; public static final double dbl = Double.MAX_VALUE; public static final String strng = "blabla"; // Classes somehow are not treated as constants // public static final Class clss = Object.class; } interface WithGenerics { List baz2(); List field = null; WithGenerics x = null; } class Generics { Map baz() { return null; } Map baz1() { return null; } Map baz2() { return null; } List foo() { return null; } Map bar() { return null; } WithGenerics, Jar> xyz() { return null; } } class Implemented implements Plugin { public void setProperties(Map map) { } public void setReporter(Reporter processor) { } } public class ClassParserTest extends TestCase { /** * Test the constant values * * @throws Exception */ public void testConstantValues() throws Exception { final Map values = new HashMap(); Clazz c = new Clazz("ConstantValues", new FileResource(IO.getFile( new File("").getAbsoluteFile(), "bin/test/ConstantValues.class"))); c.parseClassFileWithCollector(new ClassDataCollector() { Clazz.FieldDef last; @Override public void field(Clazz.FieldDef referenced) { last = referenced; } @Override public void constant(Object value) { values.put(last.name, value); } }); assertEquals(1, values.get("t")); assertEquals(0, values.get("f")); assertEquals((int) Byte.MAX_VALUE, values.get("bt")); assertEquals((int) Short.MAX_VALUE, values.get("shrt")); assertEquals((int) Character.MAX_VALUE, values.get("chr")); assertEquals(Integer.MAX_VALUE, values.get("intgr")); assertEquals(Long.MAX_VALUE, values.get("lng")); assertEquals(Float.MAX_VALUE, values.get("flt")); assertEquals(Double.MAX_VALUE, values.get("dbl")); assertEquals("blabla", values.get("strng")); // Classes are special // assertEquals("java.lang.Object", ((Clazz.ClassConstant) values.get("clss")).getName()); } public void testGeneric() throws Exception { print(System.out, WithGenerics.class.getField("field").getGenericType()); System.out.println(); print(System.out, Class.class); System.out.println(); print(System.out, WithGenerics.class); System.out.println(); } public void print(Appendable sb, Type t) throws Exception { if (t instanceof ParameterizedType) { ParameterizedType pt = (ParameterizedType) t; Class c = (Class) pt.getRawType(); sb.append("L"); sb.append(c.getCanonicalName().replace('.', '/')); sb.append("<"); for (Type arg : pt.getActualTypeArguments()) { print(sb, arg); } sb.append(">"); sb.append(";"); return; } else if (t instanceof WildcardType) { sb.append("yyyy"); } else if (t instanceof GenericArrayType) { sb.append("[" + ((GenericArrayType) t).getGenericComponentType()); } else if (t instanceof TypeVariable) { TypeVariable tv = (TypeVariable) t; sb.append("T"); sb.append(tv.getName()); for (Type upper : tv.getBounds()) { if (upper != Object.class) { sb.append(":"); print(sb, upper); } } sb.append(";"); } else { Class c = (Class) t; sb.append("L"); sb.append(c.getCanonicalName().replace('.', '/')); if (c instanceof GenericDeclaration) { GenericDeclaration gd = (GenericDeclaration) c; if (gd.getTypeParameters().length != 0) { sb.append("<"); for (Type arg : gd.getTypeParameters()) { print(sb, arg); } sb.append(">"); } } sb.append(";"); } } /** * Included an aop alliance class that is not directly referenced. * */ public void testUnacceptableReference() throws Exception { Builder b = new Builder(); b.addClasspath(new File("jar/nl.fuji.general.jar")); b.addClasspath(new File("jar/spring.jar")); b.setProperty("Export-Package", "nl.fuji.log"); b.build(); assertFalse(b.getImports().containsKey("org.aopalliance.aop")); } public void testImplemented() throws Exception { Builder a = new Builder(); a.addClasspath(new File("bin")); a.setProperty("Private-Package", "test"); a.build(); Clazz c = a.getClassspace().get("test/Implemented.class"); Set s = Create.set(); Clazz.getImplementedPackages(s, a, c); assertTrue(s.contains("aQute.bnd.service")); } public void testWildcards() throws Exception { Clazz c = new Clazz("genericstest", null); c.parseClassFile(getClass().getResourceAsStream("WithGenerics.class")); System.out.println(c.getReferred()); assertEquals("size ", 5, c.getReferred().size()); assertTrue(c.getReferred().contains("aQute.lib.osgi")); assertTrue(c.getReferred().contains("java.util")); assertTrue(c.getReferred().contains("java.net")); assertTrue(c.getReferred().contains("java.lang")); } public void testGenericsSignature3() throws Exception { Clazz c = new Clazz("genericstest", null); c.parseClassFile(getClass().getResourceAsStream("Generics.class")); assertTrue(c.getReferred().contains("test")); assertTrue(c.getReferred().contains("aQute.lib.osgi")); } public void testGenericsSignature2() throws Exception { Clazz c = new Clazz("genericstest", new FileResource(new File("src/test/generics.clazz"))); c.parseClassFile(); assertTrue(c.getReferred().contains("javax.swing.table")); assertTrue(c.getReferred().contains("javax.swing")); } public void testGenericsSignature() throws Exception { Clazz c = new Clazz("genericstest", new FileResource(new File("src/test/generics.clazz"))); c.parseClassFile(); assertTrue(c.getReferred().contains("javax.swing.table")); assertTrue(c.getReferred().contains("javax.swing")); } /** * @Neil: I'm trying to use bnd to bundleize a library called JQuantLib, but * it causes an ArrayIndexOutOfBoundsException while parsing a class. * The problem is reproducible and I have even rebuilt the library * from source and get the same problem. * * Here's the stack trace: * * java.lang.ArrayIndexOutOfBoundsException: -29373 at * aQute.lib.osgi.Clazz.parseClassFile(Clazz.java:262) at * aQute.lib.osgi.Clazz.(Clazz.java:101) at * aQute.lib.osgi.Analyzer.analyzeJar(Analyzer.java:1647) at * aQute.lib.osgi.Analyzer.analyzeBundleClasspath(Analyzer.java:1563) * at aQute.lib.osgi.Analyzer.analyze(Analyzer.java:108) at * aQute.lib.osgi.Builder.analyze(Builder.java:192) at * aQute.lib.osgi.Builder.doConditional(Builder.java:158) at * aQute.lib.osgi.Builder.build(Builder.java:71) at * aQute.bnd.main.bnd.doBuild(bnd.java:379) at * aQute.bnd.main.bnd.run(bnd.java:130) at * aQute.bnd.main.bnd.main(bnd.java:39) * * @throws Exception */ public void testJQuantlib() throws Exception { Builder b = new Builder(); b.addClasspath(new File("test/jquantlib-0.1.2.jar")); b.setProperty("Export-Package", "*"); b.build(); } public void testMissingPackage2() throws Exception { InputStream in = getClass().getResourceAsStream("JobsService.clazz"); assertNotNull(in); Clazz clazz = new Clazz("test", null); clazz.parseClassFile(in); assertTrue(clazz.getReferred().contains("com.linkedin.member2.pub.profile.core.view")); } public void testMissingPackage1() throws Exception { InputStream in = getClass().getResourceAsStream("JobsService.clazz"); assertNotNull(in); Clazz clazz = new Clazz("test", null); clazz.parseClassFile(in); System.out.println(clazz.getReferred()); clazz.parseDescriptor("(IILcom/linkedin/member2/pub/profile/core/view/I18nPositionViews;)Lcom/linkedin/leo/cloud/overlap/api/OverlapQuery;"); assertTrue(clazz.getReferred().contains("com.linkedin.member2.pub.profile.core.view")); } public void testGeneratedClass() throws IOException { InputStream in = getClass().getResourceAsStream("XDbCmpXView.clazz"); assertNotNull(in); Clazz clazz = new Clazz("test", null); clazz.parseClassFile(in); clazz.getReferred(); } public void testParameterAnnotation() throws IOException { InputStream in = getClass().getResourceAsStream("Test2.jclass"); assertNotNull(in); Clazz clazz = new Clazz("test", null); clazz.parseClassFile(in); Set set = clazz.getReferred(); assertTrue(set.contains("test")); assertTrue(set.contains("test.annotations")); } public void testLargeClass2() throws IOException { try { URL url = new URL( "jar:file:jar/ecj_3.2.2.jar!/org/eclipse/jdt/internal/compiler/parser/Parser.class"); InputStream in = url.openStream(); assertNotNull(in); Clazz clazz = new Clazz("test", null); clazz.parseClassFile(in); } catch (Exception e) { e.printStackTrace(); fail(); } } /** * Still problems with the stuff in ecj */ public void testEcj() throws Exception { Builder builder = new Builder(); builder.setClasspath(new File[] { new File("jar/ecj_3.2.2.jar") }); builder.setProperty(Analyzer.EXPORT_PACKAGE, "org.eclipse.*"); builder.build(); System.out.println(builder.getErrors()); assertEquals(0, builder.getErrors().size()); assertEquals(0, builder.getWarnings().size()); System.out.println(builder.getErrors()); System.out.println(builder.getWarnings()); } /** * This class threw an exception because we were using skip instead of * skipBytes. skip is not guaranteed to real skip the amount of bytes, not * even if there are still bytes left. It seems to be able to stop skipping * if it is at the end of a buffer or so :-( Idiots. * * The DataInputStream.skipBytes works correctly. * * @throws IOException */ public void testLargeClass() throws IOException { InputStream in = getClass().getResourceAsStream("Parser.jclass"); assertNotNull(in); try { Clazz clazz = new Clazz("test", null); clazz.parseClassFile(in); } catch (Exception e) { e.printStackTrace(); fail(); } } public void testSimple() throws IOException { InputStream in = getClass().getResourceAsStream("WithAnnotations.jclass"); assertNotNull(in); Clazz clazz = new Clazz("test", null); clazz.parseClassFile(in); Set set = clazz.getReferred(); assertTrue(set.contains("test")); assertTrue(set.contains("test.annotations")); } } bnd-1.50.0/biz.aQute.bndlib/src/test/badproperties.prop0000755000175000017500000000024611656076535022665 0ustar drazzibdrazzibImport-Package: org.osgi.service.cm;version="[1.0.0, 2.0.0)", \ org.osgi.util.tracker;version="[1.0.0, 2.0.0)", \ my.package bnd-1.50.0/biz.aQute.bndlib/src/test/GroupsTest.java0000644000175000017500000000426511656076535022104 0ustar drazzibdrazzibpackage test; import java.io.*; import java.util.*; import junit.framework.*; import aQute.lib.collections.*; import aQute.lib.osgi.*; import static aQute.lib.collections.Logic.*; public class GroupsTest extends TestCase{ static class Group implements Comparable{ final Set name; final Set refs; public Group(Set key, Set value) { name = key; refs = value; } public int compareTo(Group o) { int n = o.name.size()-name.size(); if ( n != 0) return n; n = o.refs.size() - refs.size(); if ( n != 0) return n; String s1 = name.iterator().next(); String s2 = o.name.iterator().next(); return s1.compareTo(s2); } public String toString() { return name.toString(); } } public void testSimple() throws Exception { Builder b = new Builder(); // b.addClasspath(new File("../biz.aQute.bnd/tmp/biz.aQute.bnd.jar")); b.addClasspath(new File("jar/spring.jar")); // b.addClasspath(new File("/Ws/aQute.old/aQute.google/lib/gwt-dev-windows.jar")); b.setProperty("Private-Package", "*"); Jar build = b.build(); System.out.println(b.getUses()); MultiMap, String> x = b.getGroups(); SortedSet groups = new TreeSet(); for ( Map.Entry,Set> entry : x.entrySet()) { groups.add( new Group(entry.getKey(), entry.getValue())); } Iterator i = groups.iterator(); Group main = i.next(); System.out.println("Main " + main); while ( i.hasNext() ) { Group g = i.next(); System.out.println("Trying " + g); if ( !retain(main.refs,g.name).isEmpty()) { Collection newReferences = remove(g.refs, main.refs, main.name, g.name); if ( newReferences.isEmpty()) { System.out.println("merging " + g); main.name.addAll(g.name); i.remove(); } else System.out.println(" would add " + newReferences); } else System.out.println(" main does not refer"); } for ( Group g : groups) { System.out.println(g); } } } bnd-1.50.0/biz.aQute.bndlib/src/aQute/0000755000175000017500000000000011656076535017213 5ustar drazzibdrazzibbnd-1.50.0/biz.aQute.bndlib/src/aQute/lib/0000755000175000017500000000000011656076535017761 5ustar drazzibdrazzibbnd-1.50.0/biz.aQute.bndlib/src/aQute/lib/spring/0000755000175000017500000000000011656076535021263 5ustar drazzibdrazzibbnd-1.50.0/biz.aQute.bndlib/src/aQute/lib/spring/extract.xsl0000644000175000017500000000402211656076535023463 0ustar drazzibdrazzib bnd-1.50.0/biz.aQute.bndlib/src/aQute/lib/spring/XMLTypeProcessor.java0000644000175000017500000000160011656076535025325 0ustar drazzibdrazzibpackage aQute.lib.spring; import java.util.*; import aQute.bnd.service.*; import aQute.lib.osgi.*; public class XMLTypeProcessor implements AnalyzerPlugin { public boolean analyzeJar(Analyzer analyzer) throws Exception { List types = getTypes(analyzer); for ( XMLType type : types ) { type.analyzeJar(analyzer); } return false; } protected List getTypes(Analyzer analyzer) throws Exception { return new ArrayList(); } protected void process(List types, String resource, String paths, String pattern) throws Exception { Map> map = Processor.parseHeader(paths,null); for ( String path : map.keySet() ) { types.add( new XMLType( getClass().getResource(resource), path, pattern )); } } } bnd-1.50.0/biz.aQute.bndlib/src/aQute/lib/spring/SpringComponent.java0000644000175000017500000000564211656076535025262 0ustar drazzibdrazzibpackage aQute.lib.spring; import java.io.*; import java.util.*; import java.util.regex.*; import javax.xml.transform.*; import javax.xml.transform.stream.*; import aQute.bnd.service.*; import aQute.lib.osgi.*; /** * This component is called when we find a resource in the META-INF/*.xml * pattern. We parse the resource and and the imports to the builder. * * Parsing is done with XSLT (first time I see the use of having XML for the * Spring configuration files!). * * @author aqute * */ public class SpringComponent implements AnalyzerPlugin { static Transformer transformer; static Pattern SPRING_SOURCE = Pattern.compile("META-INF/spring/.*\\.xml"); static Pattern QN = Pattern.compile("[_A-Za-z$][_A-Za-z0-9$]*(\\.[_A-Za-z$][_A-Za-z0-9$]*)*"); public static Set analyze(InputStream in) throws Exception { if (transformer == null) { TransformerFactory tf = TransformerFactory.newInstance(); Source source = new StreamSource(SpringComponent.class .getResourceAsStream("extract.xsl")); transformer = tf.newTransformer(source); } Set refers = new HashSet(); ByteArrayOutputStream bout = new ByteArrayOutputStream(); Result r = new StreamResult(bout); Source s = new StreamSource(in); transformer.transform(s, r); ByteArrayInputStream bin = new ByteArrayInputStream(bout.toByteArray()); bout.close(); BufferedReader br = new BufferedReader(new InputStreamReader(bin, "UTF8")); String line = br.readLine(); while (line != null) { line = line.trim(); if (line.length() > 0) { String parts[] = line.split("\\s*,\\s*"); for (int i = 0; i < parts.length; i++) { int n = parts[i].lastIndexOf('.'); if (n > 0) { refers.add(parts[i].subSequence(0, n)); } } } line = br.readLine(); } br.close(); return refers; } @SuppressWarnings("unchecked") public boolean analyzeJar(Analyzer analyzer) throws Exception { Jar jar = analyzer.getJar(); Map dir = (Map) jar.getDirectories().get("META-INF/spring"); if ( dir == null || dir.isEmpty()) return false; for (Iterator i = dir.entrySet().iterator(); i.hasNext();) { Map.Entry entry = (Map.Entry) i.next(); String path = (String) entry.getKey(); Resource resource = (Resource) entry.getValue(); if (SPRING_SOURCE.matcher(path).matches()) { try { InputStream in = resource.openInputStream(); Set set = analyze(in); in.close(); for (Iterator r = set.iterator(); r.hasNext();) { String pack = (String) r.next(); if ( !QN.matcher(pack).matches()) analyzer.warning("Package does not seem a package in spring resource ("+path+"): " + pack ); if (!analyzer.getReferred().containsKey(pack)) analyzer.getReferred().put(pack, new LinkedHashMap()); } } catch( Exception e ) { analyzer.error("Unexpected exception in processing spring resources("+path+"): " + e ); } } } return false; } } bnd-1.50.0/biz.aQute.bndlib/src/aQute/lib/spring/SpringXMLType.java0000644000175000017500000000156511656076535024622 0ustar drazzibdrazzibpackage aQute.lib.spring; import java.util.*; import aQute.lib.osgi.*; /** * This component is called when we find a resource in the META-INF/*.xml * pattern. We parse the resource and and the imports to the builder. * * Parsing is done with XSLT (first time I see the use of having XML for the * Spring configuration files!). * * @author aqute * */ public class SpringXMLType extends XMLTypeProcessor { protected List getTypes(Analyzer analyzer) throws Exception { List types = new ArrayList(); String header = analyzer.getProperty("Bundle-Blueprint", "META-INF/blueprint"); process(types,"extract.xsl", header, ".*\\.xml"); header = analyzer.getProperty("Spring-Context", "META-INF/spring"); process(types,"extract.xsl", header, ".*\\.xml"); return types; } } bnd-1.50.0/biz.aQute.bndlib/src/aQute/lib/spring/jpa.xsl0000644000175000017500000000307611656076535022573 0ustar drazzibdrazzib bnd-1.50.0/biz.aQute.bndlib/src/aQute/lib/spring/JPAComponent.java0000644000175000017500000000126711656076535024431 0ustar drazzibdrazzibpackage aQute.lib.spring; import java.util.ArrayList; import java.util.List; import aQute.lib.osgi.Analyzer; /** * This component is called when we find a resource in the META-INF/*.xml * pattern. We parse the resource and and the imports to the builder. * * Parsing is done with XSLT (first time I see the use of having XML for the * Spring configuration files!). * * @author aqute * */ public class JPAComponent extends XMLTypeProcessor { protected List getTypes(Analyzer analyzer) throws Exception { List types = new ArrayList(); process(types,"jpa.xsl", "META-INF", "persistence.xml"); return types; } } bnd-1.50.0/biz.aQute.bndlib/src/aQute/lib/spring/hibernate.xsl0000644000175000017500000000221311656076535023752 0ustar drazzibdrazzib bnd-1.50.0/biz.aQute.bndlib/src/aQute/lib/spring/XMLType.java0000644000175000017500000000721411656076535023434 0ustar drazzibdrazzibpackage aQute.lib.spring; import java.io.*; import java.net.*; import java.util.*; import java.util.regex.*; import javax.xml.transform.*; import javax.xml.transform.stream.*; import aQute.lib.osgi.*; public class XMLType { Transformer transformer; Pattern paths; String root; static Pattern QN = Pattern .compile("[_A-Za-z$][_A-Za-z0-9$]*(\\.[_A-Za-z$][_A-Za-z0-9$]*)*"); public XMLType(URL source, String root, String paths ) throws Exception { transformer = getTransformer(source); this.paths = Pattern.compile(paths); this.root = root; } public Set analyze(InputStream in) throws Exception { Set refers = new HashSet(); ByteArrayOutputStream bout = new ByteArrayOutputStream(); Result r = new StreamResult(bout); Source s = new StreamSource(in); transformer.transform(s, r); ByteArrayInputStream bin = new ByteArrayInputStream(bout.toByteArray()); bout.close(); BufferedReader br = new BufferedReader(new InputStreamReader(bin, "UTF8")); String line = br.readLine(); while (line != null) { line = line.trim(); if (line.length() > 0) { String parts[] = line.split("\\s*,\\s*"); for (int i = 0; i < parts.length; i++) { int n = parts[i].lastIndexOf('.'); if (n > 0) { refers.add(parts[i].subSequence(0, n).toString()); } } } line = br.readLine(); } br.close(); return refers; } public boolean analyzeJar(Analyzer analyzer) throws Exception { Jar jar = analyzer.getJar(); Map dir = jar.getDirectories().get(root); if (dir == null || dir.isEmpty()) { Resource resource = jar.getResource(root); if ( resource != null ) process(analyzer, root, resource); return false; } for (Iterator> i = dir.entrySet().iterator(); i.hasNext();) { Map.Entry entry = i.next(); String path = entry.getKey(); Resource resource = entry.getValue(); if (paths.matcher(path).matches()) { process(analyzer, path, resource); } } return false; } private void process(Analyzer analyzer, String path, Resource resource) { try { InputStream in = resource.openInputStream(); Set set = analyze(in); in.close(); for (Iterator r = set.iterator(); r.hasNext();) { String pack = r.next(); if (!QN.matcher(pack).matches()) analyzer .warning("Package does not seem a package in spring resource (" + path + "): " + pack); if (!analyzer.getReferred().containsKey(pack)) analyzer.getReferred().put(pack, new LinkedHashMap()); } } catch (Exception e) { analyzer .error("Unexpected exception in processing spring resources(" + path + "): " + e); } } protected Transformer getTransformer(java.net.URL url) throws Exception { TransformerFactory tf = TransformerFactory.newInstance(); Source source = new StreamSource(url.openStream()); return tf.newTransformer(source); } } bnd-1.50.0/biz.aQute.bndlib/src/aQute/lib/jardiff/0000755000175000017500000000000011656076535021366 5ustar drazzibdrazzibbnd-1.50.0/biz.aQute.bndlib/src/aQute/lib/jardiff/Diff.java0000644000175000017500000001165111656076535023105 0ustar drazzibdrazzibpackage aQute.lib.jardiff; import java.io.*; import java.util.*; import java.util.jar.*; import aQute.lib.osgi.*; public class Diff { /** * Compare two JAR files with each other. * * @param a * @param b * @param strict * @return * @throws IOException */ public Map diff(Jar a, Jar b, boolean strict) throws Exception { Map different = new TreeMap(); compareManifest(different, a.getManifest(), b.getManifest(), strict); diff(different, a.getResources().keySet(), b.getResources().keySet()); Set shared = new HashSet(a.getResources().keySet()); shared.retainAll(b.getResources().keySet()); for (String path : a.getResources().keySet()) { Resource ra = a.getResource(path); Resource rb = a.getResource(path); if (rb != null) { if (ra.getClass() != rb.getClass()) { different.put(path, "Different types: " + a.getClass().getName() + " : " + b.getClass().getName()); } else { if (path.endsWith(".jar")) { Jar aa = new Jar(path, ra.openInputStream()); Jar bb = new Jar(path, rb.openInputStream()); try { Map result = diff(aa, bb, strict); if (!result.isEmpty()) different.put(path, result); } finally { aa.close(); bb.close(); } } else { String cmp = diff(ra.openInputStream(), rb .openInputStream()); if (cmp != null) different.put(path, cmp); } } } } return different; } String diff(InputStream a, InputStream b) throws IOException { int n = 0; int binary = 0; StringBuffer sb = new StringBuffer(); while (true) { int ac = a.read(); int bc = b.read(); if (ac < 0) { if (bc < 0) return null; return "a is smaller"; } else if (bc < 0) { return "b is smaller"; } if (ac != bc) { String s = "Difference at pos: " + n; if (binary == 0 && sb.length() > 5) { s = s + "Context: " + sb.substring(sb.length() - 5); } } if (ac >= ' ' && ac <= '~') sb.append((char) ac); else binary++; n++; } } void diff(Map different, Set a, Set b) { Set onlyInA = new HashSet(a); onlyInA.removeAll(b); Set onlyInB = new HashSet(b); onlyInB.removeAll(a); for (Object element : onlyInA) { different.put(element.toString(), "a"); } for (Object element : onlyInB) { different.put(element.toString(), "b"); } } public void compareManifest(Map different, Manifest a, Manifest b, boolean strict) { if (a == null || b == null) { different.put("Manifest null", (a == null ? "a=null" : "a exists") + " " + (b == null ? "b=null" : "b exists")); return; } Attributes attrs = a.getMainAttributes(); Attributes bttrs = b.getMainAttributes(); diff(different, attrs.keySet(), bttrs.keySet()); for (Object element : attrs.keySet()) { Attributes.Name name = (Attributes.Name) element; String av = attrs.getValue(name); String bv = bttrs.getValue(name); if (bv != null) { if (!av.equals(bv)) different.put(name.toString(), "M:" + name + ":" + av + "!=" + bv); } } } @SuppressWarnings("unchecked") public void print(PrintStream pout, Map map, int indent) { for (Map.Entry entry : map.entrySet()) { for (int j = 0; j < indent; j++) { pout.print(" "); } String key = entry.getKey(); pout.print(key); for (int j = 0; j < 70 - indent - key.length(); j++) { pout.print(" "); } if (entry.getValue() instanceof Map) { pout.println(); print(pout, (Map) entry.getValue(), indent + 1); } else pout.println(entry.getValue()); } } public void close() { } } bnd-1.50.0/biz.aQute.bndlib/src/aQute/lib/osgi/0000755000175000017500000000000011656076535020722 5ustar drazzibdrazzibbnd-1.50.0/biz.aQute.bndlib/src/aQute/lib/osgi/JarResource.java0000755000175000017500000000142011656076535024011 0ustar drazzibdrazzibpackage aQute.lib.osgi; import java.io.*; public class JarResource implements Resource { Jar jar; String extra; public JarResource(Jar jar ) { this.jar = jar; } public String getExtra() { return extra; } public long lastModified() { return jar.lastModified(); } public void write(OutputStream out) throws Exception { jar.write(out); } public InputStream openInputStream() throws Exception { ByteArrayOutputStream out = new ByteArrayOutputStream(); write(out); out.close(); ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray()); return in; } public void setExtra(String extra) { this.extra = extra; } public Jar getJar() { return jar; } public String toString() { return ":" + jar.getName() + ":"; } } bnd-1.50.0/biz.aQute.bndlib/src/aQute/lib/osgi/InstructionFilter.java0000644000175000017500000000170211656076535025254 0ustar drazzibdrazzibpackage aQute.lib.osgi; import java.io.*; import java.util.regex.*; public class InstructionFilter implements FileFilter { private Instruction instruction; private boolean recursive; private Pattern doNotCopy; public InstructionFilter (Instruction instruction, boolean recursive, Pattern doNotCopy) { this.instruction = instruction; this.recursive = recursive; this.doNotCopy = doNotCopy; } public InstructionFilter (Instruction instruction, boolean recursive) { this(instruction, recursive, Pattern.compile(Constants.DEFAULT_DO_NOT_COPY)); } public boolean isRecursive() { return recursive; } public boolean accept(File pathname) { if (doNotCopy != null && doNotCopy.matcher(pathname.getName()).matches()) { return false; } if (pathname.isDirectory() && isRecursive()) { return true; } if (instruction == null) { return true; } return !instruction.isNegated() == instruction.matches(pathname.getName()); } } bnd-1.50.0/biz.aQute.bndlib/src/aQute/lib/osgi/TagResource.java0000644000175000017500000000205411656076535024011 0ustar drazzibdrazzibpackage aQute.lib.osgi; import java.io.*; import aQute.lib.io.*; import aQute.lib.tag.*; public class TagResource implements Resource { final Tag tag; String extra; public TagResource(Tag tag) { this.tag = tag; } public InputStream openInputStream() throws Exception { final PipedInputStream pin = new PipedInputStream(); final PipedOutputStream pout = new PipedOutputStream(pin); Processor.getExecutor().execute(new Runnable() { public void run() { try { write(pout); } catch (Exception e) { e.printStackTrace(); // ignore } IO.close(pout); } }); return pin; } public void write(OutputStream out) throws UnsupportedEncodingException { OutputStreamWriter ow = new OutputStreamWriter(out, "UTF-8"); PrintWriter pw = new PrintWriter(ow); pw.println(""); try { tag.print(0, pw); } finally { pw.flush(); } } public long lastModified() { return 0; } public void setExtra(String extra) { this.extra = extra; } public String getExtra() { return extra; } } bnd-1.50.0/biz.aQute.bndlib/src/aQute/lib/osgi/EmbeddedResource.java0000755000175000017500000000415111656076535024772 0ustar drazzibdrazzibpackage aQute.lib.osgi; import java.io.*; import java.util.zip.*; public class EmbeddedResource implements Resource { byte data[]; long lastModified; String extra; public EmbeddedResource(byte data[], long lastModified) { this.data = data; this.lastModified = lastModified; } public InputStream openInputStream() throws FileNotFoundException { return new ByteArrayInputStream(data); } public void write(OutputStream out) throws IOException { out.write(data); } public String toString() { return ":" + data.length + ":"; } public static void build(Jar jar, InputStream in, long lastModified) throws IOException { ZipInputStream jin = new ZipInputStream(in); ZipEntry entry = jin.getNextEntry(); while (entry != null) { if (!entry.isDirectory()) { byte data[] = collect(jin); jar.putResource(entry.getName(), new EmbeddedResource(data, lastModified), true); } entry = jin.getNextEntry(); } jin.close(); } /** * Convenience method to turn an inputstream into a byte array. The method * uses a recursive algorithm to minimize memory usage. * * @param in stream with data * @param offset where we are in the stream * @returns byte array filled with data */ static byte[] collect(InputStream in) throws IOException { ByteArrayOutputStream out = new ByteArrayOutputStream(); copy(in,out); return out.toByteArray(); } static void copy(InputStream in, OutputStream out) throws IOException { int available = in.available(); if ( available <= 10000) available = 64000; byte [] buffer = new byte[available]; int size; while ( (size=in.read(buffer))>0) out.write(buffer,0,size); } public long lastModified() { return lastModified; } public static void build(Jar sub, Resource resource) throws Exception { InputStream in = resource.openInputStream(); build(sub,in, resource.lastModified()); in.close(); } public String getExtra() { return extra; } public void setExtra(String extra) { this.extra = extra; } public long size() { return data.length; } } bnd-1.50.0/biz.aQute.bndlib/src/aQute/lib/osgi/Clazz.java0000755000175000017500000012021711656076535022656 0ustar drazzibdrazzibpackage aQute.lib.osgi; import java.io.*; import java.lang.annotation.*; import java.nio.*; import java.util.*; import java.util.regex.*; import aQute.bnd.annotation.*; import aQute.libg.generics.*; public class Clazz { public class ClassConstant { int cname; public ClassConstant(int class_index) { this.cname = class_index; } public String getName() { return (String) pool[cname]; } } public static enum JAVA { UNKNOWN(Integer.MAX_VALUE), OpenJDK7(51), J2S6(50), J2SE5(49), JDK1_4(48), JDK1_3(47), JDK1_2( 46), JDK1_1(45); final int major; JAVA(int major) { this.major = major; } static JAVA format(int n) { for (JAVA e : JAVA.values()) if (e.major == n) return e; return UNKNOWN; } public int getMajor() { return major; } public boolean hasAnnotations() { return major >= J2SE5.major; } public boolean hasGenerics() { return major >= J2SE5.major; } public boolean hasEnums() { return major >= J2SE5.major; } }; public static enum QUERY { IMPLEMENTS, EXTENDS, IMPORTS, NAMED, ANY, VERSION, CONCRETE, ABSTRACT, PUBLIC, ANNOTATION, RUNTIMEANNOTATIONS, CLASSANNOTATIONS }; public static EnumSet HAS_ARGUMENT = EnumSet.of(QUERY.IMPLEMENTS, QUERY.EXTENDS, QUERY.IMPORTS, QUERY.NAMED, QUERY.VERSION, QUERY.ANNOTATION); /** *
	 * ACC_PUBLIC 0x0001 Declared public; may be accessed from outside its
	 * package. 
	 * ACC_FINAL 0x0010 Declared final; no subclasses allowed.
	 * ACC_SUPER 0x0020 Treat superclass methods specially when invoked by the
	 * invokespecial instruction. 
	 * ACC_INTERFACE 0x0200 Is an interface, not a
	 * class. 
	 * ACC_ABSTRACT 0x0400 Declared abstract; may not be instantiated.
	 * 
* * @param mod */ final static int ACC_PUBLIC = 0x0001; // Declared // public; // may // be // accessed // from outside its package. final static int ACC_FINAL = 0x0010; // Declared // final; // no // subclasses // allowed. final static int ACC_SUPER = 0x0020; // Treat // superclass // methods // specially when invoked by the // invokespecial instruction. final static int ACC_INTERFACE = 0x0200; // Is // an // interface, // not // a // classs final static int ACC_ABSTRACT = 0x0400; // Declared // abstract; // may // not // be // instantiated. final static int ACC_ENUM = 0x04000; static protected class Assoc { Assoc(byte tag, int a, int b) { this.tag = tag; this.a = a; this.b = b; } byte tag; int a; int b; } static public class FieldDef implements Comparable { public FieldDef(int access, String clazz, String name, String descriptor) { this.access = access; this.clazz = clazz.replace('/', '.'); this.name = name; this.descriptor = descriptor; } final public int access; final public String clazz; final public String name; final public String descriptor; public String signature; public Object constant; public boolean equals(Object other) { if (!(other instanceof MethodDef)) return false; FieldDef m = (FieldDef) other; return clazz.equals(m.clazz) && name.equals(m.name) && descriptor.equals(m.descriptor); } public int hashCode() { return clazz.hashCode() ^ name.hashCode() ^ descriptor.hashCode(); } public int compareTo(FieldDef o) { int result = clazz.compareTo(o.clazz); if (result == 0) { result = name.compareTo(o.name); if (result == 0) { result = descriptor.compareTo(o.descriptor); } } return result; } public String getPretty() { return name; } public String toString() { return getPretty(); } public boolean isEnum() { return (access & ACC_ENUM) != 0; } } static public class MethodDef extends FieldDef { Pattern METHOD_DESCRIPTOR = Pattern.compile("\\((.*)\\)(.+)"); public MethodDef(int access, String clazz, String method, String descriptor) { super(access, clazz, method, descriptor); } public boolean isConstructor() { return name.equals("") || name.equals(""); } public String getReturnType() { String use = descriptor; if (signature != null) use = signature; Matcher m = METHOD_DESCRIPTOR.matcher(use); if (!m.matches()) throw new IllegalArgumentException("Not a valid method descriptor: " + descriptor); String returnType = m.group(2); return objectDescriptorToFQN(returnType); } public String getPretty() { StringBuilder sb = new StringBuilder(); sb.append(descriptor.charAt(0)); int index = 1; String del = ""; while (index < descriptor.length() && descriptor.charAt(index) != ')') { sb.append(del); index = printParameter(sb, descriptor, index); del = ","; } sb.append(descriptor.charAt(index++)); StringBuilder sb2 = new StringBuilder(); if (isConstructor()) { sb2.append(getShortName(clazz)); index++; // skip the V } else { printParameter(sb2, descriptor, index); sb2.append(" "); sb2.append(getShortName(clazz)); sb2.append("."); sb2.append(name); } sb2.append(sb); return sb2.toString(); } private int printParameter(StringBuilder sb, CharSequence descriptor, int index) { char c = descriptor.charAt(index++); switch (c) { case 'B': sb.append("byte"); break; case 'C': sb.append("char"); break; case 'D': sb.append("double"); break; case 'F': sb.append("float"); break; case 'I': sb.append("int"); break; case 'J': sb.append("long"); break; case 'S': sb.append("short"); break; case 'Z': sb.append("boolean"); break; case 'V': sb.append("void"); break; case 'L': index = reference(sb, descriptor, index); break; case '[': index = array(sb, descriptor, index); break; } return index; } private int reference(StringBuilder sb, CharSequence descriptor, int index) { int n = sb.length(); int lastSlash = n; while (index < descriptor.length() && descriptor.charAt(index) != ';') { char c = descriptor.charAt(index++); if (c == '/') { c = '.'; lastSlash = sb.length() + 1; } sb.append(c); } if (lastSlash != n) { sb.delete(n, lastSlash); } return ++index; } private int array(StringBuilder sb, CharSequence descriptor, int index) { int n = 1; while (index < descriptor.length() && descriptor.charAt(index) == '[') { index++; } index = printParameter(sb, descriptor, index); while (n-- > 0) { sb.append("[]"); } return index; } } final static byte SkipTable[] = { 0, // 0 non existent -1, // 1 CONSTANT_utf8 UTF 8, handled in // method -1, // 2 4, // 3 CONSTANT_Integer 4, // 4 CONSTANT_Float 8, // 5 CONSTANT_Long (index +=2!) 8, // 6 CONSTANT_Double (index +=2!) -1, // 7 CONSTANT_Class 2, // 8 CONSTANT_String 4, // 9 CONSTANT_FieldRef 4, // 10 CONSTANT_MethodRef 4, // 11 CONSTANT_InterfaceMethodRef 4, // 12 CONSTANT_NameAndType }; boolean isAbstract; boolean isPublic; boolean isEnum; boolean hasRuntimeAnnotations; boolean hasClassAnnotations; String className; Object pool[]; int intPool[]; Set imports = Create.set(); String path; int minor = 0; int major = 0; int access = 0; String sourceFile; Set xref; Set classes; Set descriptors; Set annotations; int forName = 0; int class$ = 0; String[] interfaces; String zuper; ClassDataCollector cd = null; Resource resource; FieldDef last = null; public Clazz(String path, Resource resource) { this.path = path; this.resource = resource; } public Set parseClassFile() throws Exception { return parseClassFileWithCollector(null); } public Set parseClassFile(InputStream in) throws IOException { return parseClassFile(in, null); } public Set parseClassFileWithCollector(ClassDataCollector cd) throws Exception { InputStream in = resource.openInputStream(); try { return parseClassFile(in, cd); } finally { in.close(); } } public Set parseClassFile(InputStream in, ClassDataCollector cd) throws IOException { DataInputStream din = new DataInputStream(in); try { this.cd = cd; return parseClassFile(din); } finally { cd = null; din.close(); } } Set parseClassFile(DataInputStream in) throws IOException { xref = new HashSet(); classes = new HashSet(); descriptors = new HashSet(); boolean crawl = cd != null; // Crawl the byte code if we have a // collector int magic = in.readInt(); if (magic != 0xCAFEBABE) throw new IOException("Not a valid class file (no CAFEBABE header)"); minor = in.readUnsignedShort(); // minor version major = in.readUnsignedShort(); // major version int count = in.readUnsignedShort(); pool = new Object[count]; intPool = new int[count]; process: for (int poolIndex = 1; poolIndex < count; poolIndex++) { byte tag = in.readByte(); switch (tag) { case 0: break process; case 1: constantUtf8(in, poolIndex); break; case 3: constantInteger(in, poolIndex); break; case 4: constantFloat(in, poolIndex); break; // For some insane optimization reason are // the long and the double two entries in the // constant pool. See 4.4.5 case 5: constantLong(in, poolIndex); poolIndex++; break; case 6: constantDouble(in, poolIndex); poolIndex++; break; case 7: constantClass(in, poolIndex); break; case 8: constantString(in, poolIndex); break; case 10: // Method ref case 11: // Interface Method ref methodRef(in, poolIndex); break; // Name and Type case 12: nameAndType(in, poolIndex, tag); break; // We get the skip count for each record type // from the SkipTable. This will also automatically // abort when default: if (tag == 2) throw new IOException("Invalid tag " + tag); in.skipBytes(SkipTable[tag]); break; } } pool(pool, intPool); /* * Parse after the constant pool, code thanks to Hans Christian * Falkenberg */ int access_flags = in.readUnsignedShort(); // access isAbstract = (access_flags & ACC_ABSTRACT) != 0; isPublic = (access_flags & ACC_PUBLIC) != 0; isEnum = (access_flags & ACC_ENUM) != 0; int this_class = in.readUnsignedShort(); className = (String) pool[intPool[this_class]]; try { if (cd != null) { if (!cd.classStart(access_flags, className)) return null; } int super_class = in.readUnsignedShort(); zuper = (String) pool[intPool[super_class]]; if (zuper != null) { String pack = getPackage(zuper); packageReference(pack); if (cd != null) cd.extendsClass(zuper); } int interfacesCount = in.readUnsignedShort(); if (interfacesCount > 0) { interfaces = new String[interfacesCount]; for (int i = 0; i < interfacesCount; i++) interfaces[i] = (String) pool[intPool[in.readUnsignedShort()]]; if (cd != null) cd.implementsInterfaces(interfaces); } int fieldsCount = in.readUnsignedShort(); for (int i = 0; i < fieldsCount; i++) { access_flags = in.readUnsignedShort(); // skip access flags int name_index = in.readUnsignedShort(); int descriptor_index = in.readUnsignedShort(); // Java prior to 1.5 used a weird // static variable to hold the com.X.class // result construct. If it did not find it // it would create a variable class$com$X // that would be used to hold the class // object gotten with Class.forName ... // Stupidly, they did not actively use the // class name for the field type, so bnd // would not see a reference. We detect // this case and add an artificial descriptor String name = pool[name_index].toString(); // name_index if (name.startsWith("class$")) { crawl = true; } if (cd != null) cd.field(last = new FieldDef(access_flags, className, name, pool[descriptor_index].toString())); descriptors.add(new Integer(descriptor_index)); doAttributes(in, ElementType.FIELD, false); } // // Check if we have to crawl the code to find // the ldc(_w) invokestatic Class.forName // if so, calculate the method ref index so we // can do this efficiently // if (crawl) { forName = findMethodReference("java/lang/Class", "forName", "(Ljava/lang/String;)Ljava/lang/Class;"); class$ = findMethodReference(className, "class$", "(Ljava/lang/String;)Ljava/lang/Class;"); } else if (major == 48) { forName = findMethodReference("java/lang/Class", "forName", "(Ljava/lang/String;)Ljava/lang/Class;"); if (forName > 0) { crawl = true; class$ = findMethodReference(className, "class$", "(Ljava/lang/String;)Ljava/lang/Class;"); } } // // Handle the methods // int methodCount = in.readUnsignedShort(); for (int i = 0; i < methodCount; i++) { access_flags = in.readUnsignedShort(); int name_index = in.readUnsignedShort(); int descriptor_index = in.readUnsignedShort(); descriptors.add(new Integer(descriptor_index)); String name = pool[name_index].toString(); String descriptor = pool[descriptor_index].toString(); if (cd != null) { MethodDef mdef = new MethodDef(access_flags, className, name, descriptor); last = mdef; cd.method(mdef); } if ("".equals(name)) { doAttributes(in, ElementType.CONSTRUCTOR, crawl); } else { doAttributes(in, ElementType.METHOD, crawl); } } doAttributes(in, ElementType.TYPE, false); // // Now iterate over all classes we found and // parse those as well. We skip duplicates // for (int n : classes) { String clazz = (String) pool[n]; if (clazz.endsWith(";") || clazz.startsWith("[")) parseReference(clazz, 0); else { String pack = getPackage(clazz); packageReference(pack); } } // // Parse all the descriptors we found // for (Iterator e = descriptors.iterator(); e.hasNext();) { Integer index = e.next(); String prototype = (String) pool[index.intValue()]; if (prototype != null) parseDescriptor(prototype); else System.err.println("Unrecognized descriptor: " + index); } Set xref = this.xref; reset(); return xref; } finally { if (cd != null) cd.classEnd(); } } private void constantFloat(DataInputStream in, int poolIndex) throws IOException { if (cd != null) pool[poolIndex] = in.readFloat(); // ALU else in.skipBytes(4); } private void constantInteger(DataInputStream in, int poolIndex) throws IOException { intPool[poolIndex] = in.readInt(); if (cd != null) pool[poolIndex] = intPool[poolIndex]; } protected void pool(Object[] pool, int[] intPool) { } /** * @param in * @param poolIndex * @param tag * @throws IOException */ protected void nameAndType(DataInputStream in, int poolIndex, byte tag) throws IOException { int name_index = in.readUnsignedShort(); int descriptor_index = in.readUnsignedShort(); descriptors.add(new Integer(descriptor_index)); pool[poolIndex] = new Assoc(tag, name_index, descriptor_index); } /** * @param in * @param poolIndex * @param tag * @throws IOException */ private void methodRef(DataInputStream in, int poolIndex) throws IOException { int class_index = in.readUnsignedShort(); int name_and_type_index = in.readUnsignedShort(); pool[poolIndex] = new Assoc((byte) 10, class_index, name_and_type_index); } /** * @param in * @param poolIndex * @throws IOException */ private void constantString(DataInputStream in, int poolIndex) throws IOException { int string_index = in.readUnsignedShort(); intPool[poolIndex] = string_index; } /** * @param in * @param poolIndex * @throws IOException */ protected void constantClass(DataInputStream in, int poolIndex) throws IOException { int class_index = in.readUnsignedShort(); classes.add(new Integer(class_index)); intPool[poolIndex] = class_index; ClassConstant c = new ClassConstant(class_index); pool[poolIndex] = c; } /** * @param in * @throws IOException */ protected void constantDouble(DataInputStream in, int poolIndex) throws IOException { if (cd != null) pool[poolIndex] = in.readDouble(); else in.skipBytes(8); } /** * @param in * @throws IOException */ protected void constantLong(DataInputStream in, int poolIndex) throws IOException { if (cd != null) { pool[poolIndex] = in.readLong(); } else in.skipBytes(8); } /** * @param in * @param poolIndex * @throws IOException */ protected void constantUtf8(DataInputStream in, int poolIndex) throws IOException { // CONSTANT_Utf8 String name = in.readUTF(); xref.add(name); pool[poolIndex] = name; } /** * Find a method reference in the pool that points to the given class, * methodname and descriptor. * * @param clazz * @param methodname * @param descriptor * @return index in constant pool */ private int findMethodReference(String clazz, String methodname, String descriptor) { for (int i = 1; i < pool.length; i++) { if (pool[i] instanceof Assoc) { Assoc methodref = (Assoc) pool[i]; if (methodref.tag == 10) { // Method ref int class_index = methodref.a; int class_name_index = intPool[class_index]; if (clazz.equals(pool[class_name_index])) { int name_and_type_index = methodref.b; Assoc name_and_type = (Assoc) pool[name_and_type_index]; if (name_and_type.tag == 12) { // Name and Type int name_index = name_and_type.a; int type_index = name_and_type.b; if (methodname.equals(pool[name_index])) { if (descriptor.equals(pool[type_index])) { return i; } } } } } } } return -1; } /** * Called for each attribute in the class, field, or method. * * @param in * The stream * @throws IOException */ private void doAttributes(DataInputStream in, ElementType member, boolean crawl) throws IOException { int attributesCount = in.readUnsignedShort(); for (int j = 0; j < attributesCount; j++) { // skip name CONSTANT_Utf8 pointer doAttribute(in, member, crawl); } } /** * Process a single attribute, if not recognized, skip it. * * @param in * the data stream * @throws IOException */ private void doAttribute(DataInputStream in, ElementType member, boolean crawl) throws IOException { int attribute_name_index = in.readUnsignedShort(); String attributeName = (String) pool[attribute_name_index]; long attribute_length = in.readInt(); attribute_length &= 0xFFFFFFFF; if ("RuntimeVisibleAnnotations".equals(attributeName)) doAnnotations(in, member, RetentionPolicy.RUNTIME); else if ("RuntimeVisibleParameterAnnotations".equals(attributeName)) doParameterAnnotations(in, member, RetentionPolicy.RUNTIME); else if ("RuntimeInvisibleAnnotations".equals(attributeName)) doAnnotations(in, member, RetentionPolicy.CLASS); else if ("RuntimeInvisibleParameterAnnotations".equals(attributeName)) doParameterAnnotations(in, member, RetentionPolicy.CLASS); else if ("InnerClasses".equals(attributeName)) doInnerClasses(in); else if ("EnclosingMethod".equals(attributeName)) doEnclosingMethod(in); else if ("SourceFile".equals(attributeName)) doSourceFile(in); else if ("Code".equals(attributeName) && crawl) doCode(in); else if ("Signature".equals(attributeName)) doSignature(in, member); else if ("ConstantValue".equals(attributeName)) doConstantValue(in); else { if (attribute_length > 0x7FFFFFFF) { throw new IllegalArgumentException("Attribute > 2Gb"); } in.skipBytes((int) attribute_length); } } /** *
	 * EnclosingMethod_attribute { 
	 * 	u2 attribute_name_index; 
	 * 	u4 attribute_length; 
	 * 	u2 class_index
	 * 	u2 method_index;
	 * }
	 * 
* * * @param in * @throws IOException */ private void doEnclosingMethod(DataInputStream in) throws IOException { int cIndex = in.readShort(); int mIndex = in.readShort(); if (cd != null) { int nameIndex = intPool[cIndex]; String cName = (String) pool[nameIndex]; String mName = null; String mDescriptor = null; if (mIndex != 0) { Assoc nameAndType = (Assoc) pool[mIndex]; mName = (String) pool[nameAndType.a]; mDescriptor = (String) pool[nameAndType.b]; } cd.enclosingMethod(cName, mName, mDescriptor); } } /** *
	 * InnerClasses_attribute {
	 * 	u2 attribute_name_index; 
	 * 	u4 attribute_length; 
	 * 	u2 number_of_classes; {	
	 * 		u2 inner_class_info_index;
	 * 		u2 outer_class_info_index; 
	 * 		u2 inner_name_index; 
	 * 		u2 inner_class_access_flags;
	 * 	} classes[number_of_classes];
	 * }
	 * 
* * @param in * @throws IOException */ private void doInnerClasses(DataInputStream in) throws IOException { int number_of_classes = in.readShort(); for (int i = 0; i < number_of_classes; i++) { int inner_class_info_index = in.readShort(); int outer_class_info_index = in.readShort(); int inner_name_index = in.readShort(); int inner_class_access_flags = in.readShort() & 0xFFFF; if (cd != null) { String innerClass = null; String outerClass = null; String innerName = null; if (inner_class_info_index != 0) { int nameIndex = intPool[inner_class_info_index]; innerClass = (String) pool[nameIndex]; } if (outer_class_info_index != 0) { int nameIndex = intPool[outer_class_info_index]; outerClass = (String) pool[nameIndex]; } if (inner_name_index != 0) innerName = (String) pool[inner_name_index]; cd.innerClass(innerClass, outerClass, innerName, inner_class_access_flags); } } } /** * Handle a signature * *
	 * Signature_attribute { 
	 *     u2 attribute_name_index; 
	 *     u4 attribute_length; 
	 *     u2 signature_index; 
	 *     }
	 * 
* * @param member */ void doSignature(DataInputStream in, ElementType member) throws IOException { int signature_index = in.readUnsignedShort(); String signature = (String) pool[signature_index]; // System.out.println("Signature " + signature ); // The type signature is kind of weird, // lets skip it for now. Seems to be some kind of // type variable name index but it does not seem to // conform to the language specification. if (member != ElementType.TYPE) parseDescriptor(signature); if (last != null) last.signature = signature; if (cd != null) cd.signature(signature); } /** * Handle a constant value call the data collector with it */ void doConstantValue(DataInputStream in) throws IOException { int constantValue_index = in.readUnsignedShort(); if (cd == null) return; Object object = pool[constantValue_index]; if (object == null) object = pool[intPool[constantValue_index]]; last.constant = object; cd.constant(object); } /** *
	 * Code_attribute {
	 * 		u2 attribute_name_index;
	 * 		u4 attribute_length;
	 * 		u2 max_stack;
	 * 		u2 max_locals;
	 * 		u4 code_length;
	 * 		u1 code[code_length];
	 * 		u2 exception_table_length;
	 * 		{    	u2 start_pc;
	 * 		      	u2 end_pc;
	 * 		      	u2  handler_pc;
	 * 		      	u2  catch_type;
	 * 		}	exception_table[exception_table_length];
	 * 		u2 attributes_count;
	 * 		attribute_info attributes[attributes_count];
	 * 	}
	 * 
* * @param in * @param pool * @throws IOException */ private void doCode(DataInputStream in) throws IOException { /* int max_stack = */in.readUnsignedShort(); /* int max_locals = */in.readUnsignedShort(); int code_length = in.readInt(); byte code[] = new byte[code_length]; in.readFully(code); crawl(code); int exception_table_length = in.readUnsignedShort(); in.skipBytes(exception_table_length * 8); doAttributes(in, ElementType.METHOD, false); } /** * We must find Class.forName references ... * * @param code */ protected void crawl(byte[] code) { ByteBuffer bb = ByteBuffer.wrap(code); bb.order(ByteOrder.BIG_ENDIAN); int lastReference = -1; while (bb.remaining() > 0) { int instruction = 0xFF & bb.get(); switch (instruction) { case OpCodes.ldc: lastReference = 0xFF & bb.get(); break; case OpCodes.ldc_w: lastReference = 0xFFFF & bb.getShort(); break; case OpCodes.invokespecial: { int mref = 0xFFFF & bb.getShort(); if (cd != null) cd.reference(getMethodDef(0, mref)); break; } case OpCodes.invokevirtual: { int mref = 0xFFFF & bb.getShort(); if (cd != null) cd.reference(getMethodDef(0, mref)); break; } case OpCodes.invokeinterface: { int mref = 0xFFFF & bb.getShort(); if (cd != null) cd.reference(getMethodDef(0, mref)); break; } case OpCodes.invokestatic: { int methodref = 0xFFFF & bb.getShort(); if (cd != null) cd.reference(getMethodDef(0, methodref)); if ((methodref == forName || methodref == class$) && lastReference != -1 && pool[intPool[lastReference]] instanceof String) { String clazz = (String) pool[intPool[lastReference]]; if (clazz.startsWith("[") || clazz.endsWith(";")) parseReference(clazz, 0); else { int n = clazz.lastIndexOf('.'); if (n > 0) packageReference(clazz.substring(0, n)); } } break; } case OpCodes.tableswitch: // Skip to place divisible by 4 while ((bb.position() & 0x3) != 0) bb.get(); /* int deflt = */ bb.getInt(); int low = bb.getInt(); int high = bb.getInt(); try { bb.position(bb.position() + (high - low + 1) * 4); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } lastReference = -1; break; case OpCodes.lookupswitch: // Skip to place divisible by 4 while ((bb.position() & 0x3) != 0) bb.get(); /* deflt = */ bb.getInt(); int npairs = bb.getInt(); bb.position(bb.position() + npairs * 8); lastReference = -1; break; default: lastReference = -1; bb.position(bb.position() + OpCodes.OFFSETS[instruction]); } } } private void doSourceFile(DataInputStream in) throws IOException { int sourcefile_index = in.readUnsignedShort(); this.sourceFile = pool[sourcefile_index].toString(); } private void doParameterAnnotations(DataInputStream in, ElementType member, RetentionPolicy policy) throws IOException { int num_parameters = in.readUnsignedByte(); for (int p = 0; p < num_parameters; p++) { if (cd != null) cd.parameter(p); doAnnotations(in, member, policy); } } private void doAnnotations(DataInputStream in, ElementType member, RetentionPolicy policy) throws IOException { int num_annotations = in.readUnsignedShort(); // # of annotations for (int a = 0; a < num_annotations; a++) { if (cd == null) doAnnotation(in, member, policy, false); else { Annotation annotion = doAnnotation(in, member, policy, true); cd.annotation(annotion); } } } private Annotation doAnnotation(DataInputStream in, ElementType member, RetentionPolicy policy, boolean collect) throws IOException { int type_index = in.readUnsignedShort(); if (annotations == null) annotations = new HashSet(); annotations.add(pool[type_index].toString()); if (policy == RetentionPolicy.RUNTIME) { descriptors.add(new Integer(type_index)); hasRuntimeAnnotations = true; } else { hasClassAnnotations = true; } String name = (String) pool[type_index]; int num_element_value_pairs = in.readUnsignedShort(); Map elements = null; for (int v = 0; v < num_element_value_pairs; v++) { int element_name_index = in.readUnsignedShort(); String element = (String) pool[element_name_index]; Object value = doElementValue(in, member, policy, collect); if (collect) { if (elements == null) elements = new LinkedHashMap(); elements.put(element, value); } } if (collect) return new Annotation(name, elements, member, policy); else return null; } private Object doElementValue(DataInputStream in, ElementType member, RetentionPolicy policy, boolean collect) throws IOException { char tag = (char) in.readUnsignedByte(); switch (tag) { case 'B': // Byte case 'C': // Character case 'I': // Integer case 'S': // Short int const_value_index = in.readUnsignedShort(); return intPool[const_value_index]; case 'D': // Double case 'F': // Float case 's': // String case 'J': // Long const_value_index = in.readUnsignedShort(); return pool[const_value_index]; case 'Z': // Boolean const_value_index = in.readUnsignedShort(); return pool[const_value_index] == null || pool[const_value_index].equals(0) ? false : true; case 'e': // enum constant int type_name_index = in.readUnsignedShort(); if (policy == RetentionPolicy.RUNTIME) descriptors.add(new Integer(type_name_index)); int const_name_index = in.readUnsignedShort(); return pool[const_name_index]; case 'c': // Class int class_info_index = in.readUnsignedShort(); if (policy == RetentionPolicy.RUNTIME) descriptors.add(new Integer(class_info_index)); return pool[class_info_index]; case '@': // Annotation type return doAnnotation(in, member, policy, collect); case '[': // Array int num_values = in.readUnsignedShort(); Object[] result = new Object[num_values]; for (int i = 0; i < num_values; i++) { result[i] = doElementValue(in, member, policy, collect); } return result; default: throw new IllegalArgumentException("Invalid value for Annotation ElementValue tag " + tag); } } /** * Add a new package reference. * * @param pack * A '.' delimited package name */ void packageReference(String pack) { imports.add(pack); } /** * This method parses a descriptor and adds the package of the descriptor to * the referenced packages. * * The syntax of the descriptor is: * *
	 *   descriptor ::= ( '(' reference * ')' )? reference
	 *   reference  ::= 'L' classname ( '<' references '>' )? ';' | 'B' | 'Z' | ... | '+' | '-' | '['
	 * 
* * This methods uses heavy recursion to parse the descriptor and a roving * pointer to limit the creation of string objects. * * @param descriptor * The to be parsed descriptor * @param rover * The pointer to start at */ public void parseDescriptor(String descriptor) { // Some descriptors are weird, they start with a generic // declaration that contains ':', not sure what they mean ... if (descriptor.charAt(0) == '<') return; int rover = 0; if (descriptor.charAt(rover) == '(') { rover = parseReferences(descriptor, rover + 1, ')'); rover++; } parseReferences(descriptor, rover, (char) 0); } /** * Parse a sequence of references. A sequence ends with a given character or * when the string ends. * * @param descriptor * The whole descriptor. * @param rover * The index in the descriptor * @param delimiter * The end character or 0 * @return the last index processed, one character after the delimeter */ int parseReferences(String descriptor, int rover, char delimiter) { while (rover < descriptor.length() && descriptor.charAt(rover) != delimiter) { rover = parseReference(descriptor, rover); } return rover; } /** * Parse a single reference. This can be a single character or an object * reference when it starts with 'L'. * * @param descriptor * The descriptor * @param rover * The place to start * @return The return index after the reference */ int parseReference(String descriptor, int rover) { char c = descriptor.charAt(rover); while (c == '[') c = descriptor.charAt(++rover); if (c == '<') { rover = parseReferences(descriptor, rover + 1, '>'); } else if (c == 'T') { // Type variable name rover++; while (descriptor.charAt(rover) != ';') rover++; } else if (c == 'L') { StringBuilder sb = new StringBuilder(); rover++; int lastSlash = -1; while ((c = descriptor.charAt(rover)) != ';') { if (c == '<') { rover = parseReferences(descriptor, rover + 1, '>'); } else if (c == '/') { lastSlash = sb.length(); sb.append('.'); } else sb.append(c); rover++; } if (cd != null) cd.addReference(sb.toString()); if (lastSlash > 0) packageReference(sb.substring(0, lastSlash)); } else { if ("+-*BCDFIJSZV".indexOf(c) < 0) ;// System.out.println("Should not skip: " + c); } // this skips a lot of characters // [, *, +, -, B, etc. return rover + 1; } public static String getPackage(String clazz) { int n = clazz.lastIndexOf('/'); if (n < 0) { n = clazz.lastIndexOf('.'); if (n < 0) return "."; } return clazz.substring(0, n).replace('/', '.'); } public Set getReferred() { return imports; } String getClassName() { if (className == null) return "NOCLASSNAME"; return className; } public String getPath() { return path; } public String getSourceFile() { return sourceFile; } /** * .class construct for different compilers * * sun 1.1 Detect static variable class$com$acme$MyClass 1.2 " 1.3 " 1.4 " * 1.5 ldc_w (class) 1.6 " * * eclipse 1.1 class$0, ldc (string), invokestatic Class.forName 1.2 " 1.3 " * 1.5 ldc (class) 1.6 " * * 1.5 and later is not an issue, sun pre 1.5 is easy to detect the static * variable that decodes the class name. For eclipse, the class$0 gives away * we have a reference encoded in a string. * compilerversions/compilerversions.jar contains test versions of all * versions/compilers. */ public void reset() { pool = null; intPool = null; xref = null; classes = null; descriptors = null; } public boolean is(QUERY query, Instruction instr, Analyzer analyzer) throws Exception { switch (query) { case ANY: return true; case NAMED: if (instr.matches(getClassName())) return !instr.isNegated(); return false; case VERSION: String v = major + "/" + minor; if (instr.matches(v)) return !instr.isNegated(); return false; case IMPLEMENTS: for (int i = 0; interfaces != null && i < interfaces.length; i++) { if (instr.matches(interfaces[i])) return !instr.isNegated(); } break; case EXTENDS: if (zuper == null) return false; if (instr.matches(zuper)) return !instr.isNegated(); break; case PUBLIC: return !isPublic; case CONCRETE: return !isAbstract; case ANNOTATION: if (annotations == null) return false; if (annotations.contains(instr.getPattern())) return true; for (String annotation : annotations) { if (instr.matches(annotation)) return !instr.isNegated(); } return false; case RUNTIMEANNOTATIONS: return hasClassAnnotations; case CLASSANNOTATIONS: return hasClassAnnotations; case ABSTRACT: return isAbstract; case IMPORTS: for (String imp : imports) { if (instr.matches(imp.replace('.', '/'))) return !instr.isNegated(); } } if (zuper == null) return false; Clazz clazz = analyzer.findClass(zuper + ".class"); if (clazz == null) return false; return clazz.is(query, instr, analyzer); } public String toString() { return getFQN(); } public String getFQN() { String s = getClassName().replace('/', '.'); return s; } /** * Return a list of packages implemented by this class. * * @param implemented * @param classspace * @param clazz * @throws Exception */ @SuppressWarnings("deprecation") final static String USEPOLICY = toDescriptor(UsePolicy.class); final static String PROVIDERPOLICY = toDescriptor(ProviderType.class); public static void getImplementedPackages(Set implemented, Analyzer analyzer, Clazz clazz) throws Exception { if (clazz.interfaces != null) { for (String interf : clazz.interfaces) { interf = interf + ".class"; Clazz c = analyzer.getClassspace().get(interf); // If not found, actually parse the imported // class file to check for implementation policy. if (c == null) c = analyzer.findClass(interf); if (c != null) { boolean consumer = false; Set annotations = c.annotations; if (annotations != null) // Override if we marked the interface as a consumer // interface consumer = annotations.contains(USEPOLICY) || annotations.contains(PROVIDERPOLICY); if (!consumer) implemented.add(getPackage(interf)); getImplementedPackages(implemented, analyzer, c); } else implemented.add(getPackage(interf)); } } if (clazz.zuper != null) { Clazz c = analyzer.getClassspace().get(clazz.zuper); if (c != null) { getImplementedPackages(implemented, analyzer, c); } } } // String RNAME = "LaQute/bnd/annotation/UsePolicy;"; public static String toDescriptor(Class clazz) { StringBuilder sb = new StringBuilder(); sb.append('L'); sb.append(clazz.getName().replace('.', '/')); sb.append(';'); return sb.toString(); } MethodDef getMethodDef(int access, int methodRefPoolIndex) { Object o = pool[methodRefPoolIndex]; if (o != null && o instanceof Assoc) { Assoc assoc = (Assoc) o; if (assoc.tag == 10) { int string_index = intPool[assoc.a]; String className = (String) pool[string_index]; int name_and_type_index = assoc.b; Assoc name_and_type = (Assoc) pool[name_and_type_index]; if (name_and_type.tag == 12) { // Name and Type int name_index = name_and_type.a; int type_index = name_and_type.b; String method = (String) pool[name_index]; String descriptor = (String) pool[type_index]; return new MethodDef(access, className, method, descriptor); } else throw new IllegalArgumentException( "Invalid class file (or parsing is wrong), assoc is not type + name (12)"); } else throw new IllegalArgumentException( "Invalid class file (or parsing is wrong), Assoc is not method ref! (10)"); } else throw new IllegalArgumentException( "Invalid class file (or parsing is wrong), Not an assoc at a method ref"); } public static String getShortName(String cname) { int n = cname.lastIndexOf('.'); if (n < 0) return cname; return cname.substring(n + 1, cname.length()); } public static String fqnToPath(String dotted) { return dotted.replace('.', '/') + ".class"; } public static String fqnToBinary(String dotted) { return "L" + dotted.replace('.', '/') + ";"; } public static String pathToFqn(String path) { return path.replace('/', '.').substring(0, path.length() - 6); } public boolean isPublic() { return isPublic; } public boolean isEnum() { return isEnum; } public JAVA getFormat() { return JAVA.format(major); } public static String objectDescriptorToFQN(String string) { if (string.startsWith("L") && string.endsWith(";")) return string.substring(1, string.length() - 1).replace('/', '.'); switch (string.charAt(0)) { case 'V': return "void"; case 'B': return "byte"; case 'C': return "char"; case 'I': return "int"; case 'S': return "short"; case 'D': return "double"; case 'F': return "float"; case 'J': return "long"; case 'Z': return "boolean"; case '[': // Array return objectDescriptorToFQN(string.substring(1)) + "[]"; } throw new IllegalArgumentException("Invalid type character in descriptor " + string); } public static String internalToFqn(String string) { return string.replace('/', '.'); } public static String unCamel(String id) { StringBuilder out = new StringBuilder(); for (int i = 0; i < id.length(); i++) { char c = id.charAt(i); if (c == '_' || c == '$' || c == '.') { if (out.length() > 0 && !Character.isWhitespace(out.charAt(out.length() - 1))) out.append(' '); continue; } int n = i; while (n < id.length() && Character.isUpperCase(id.charAt(n))) { n++; } if (n == i) out.append(id.charAt(i)); else { boolean tolower = (n - i) == 1; if (i > 0 && !Character.isWhitespace(out.charAt(out.length() - 1))) out.append(' '); for (; i < n;) { if (tolower) out.append(Character.toLowerCase(id.charAt(i))); else out.append(id.charAt(i)); i++; } i--; } } if (id.startsWith(".")) out.append(" *"); out.replace(0, 1, Character.toUpperCase(out.charAt(0)) + ""); return out.toString(); } } bnd-1.50.0/biz.aQute.bndlib/src/aQute/lib/osgi/About.java0000755000175000017500000000370411656076535022646 0ustar drazzibdrazzibpackage aQute.lib.osgi; /** * This package contains a number of classes that assists by analyzing JARs and * constructing bundles. * * The Analyzer class can be used to analyze an existing bundle and can create a * manifest specification from proposed (wildcard) Export-Package, * Bundle-Includes, and Import-Package headers. * * The Builder class can use the headers to construct a JAR from the classpath. * * The Verifier class can take an existing JAR and verify that all headers are * correctly set. It will verify the syntax of the headers, match it against the * proper contents, and verify imports and exports. * * A number of utility classes are available. * * Jar, provides an abstraction of a Jar file. It has constructors for creating * a Jar from a stream, a directory, or a jar file. A Jar, keeps a collection * Resource's. There are Resource implementations for File, from ZipFile, or from * a stream (which copies the data). The Jar tries to minimize the work during * build up so that it is cheap to use. The Resource's can be used to iterate * over the names and later read the resources when needed. * * Clazz, provides a parser for the class files. This will be used to define the * imports and exports. * * A key component in this library is the Map. Headers are translated to Maps of Maps. OSGi * header syntax is like: *
 * 	  header = clause ( ',' clause ) *
 *    clause = file ( ';' file ) * ( parameter ) *
 *    param  = attr '=' value | directive ':=' value
 * 
* These headers are translated to a Map that contains all headers (the order is * maintained). Each additional file in a header definition will have its own * entry (only native code does not work this way). The clause is represented * as another map. The ':' of directives is considered part of the name. This * allows attributes and directives to be maintained in the clause map. * * @version $Revision: 1.2 $ */ public class About { } bnd-1.50.0/biz.aQute.bndlib/src/aQute/lib/osgi/WriteResource.java0000644000175000017500000000175411656076535024376 0ustar drazzibdrazzibpackage aQute.lib.osgi; import java.io.*; public abstract class WriteResource implements Resource { long lastModified; String extra; public InputStream openInputStream() throws Exception { PipedInputStream pin = new PipedInputStream(); final PipedOutputStream pout = new PipedOutputStream(pin); Thread t = new Thread() { public void run() { try { write(pout); } catch (Exception e) { e.printStackTrace(); } finally { try { pout.close(); } catch (IOException e) { // Ignore } } } }; t.start(); return pin; } public abstract void write(OutputStream out) throws IOException, Exception; public abstract long lastModified(); public String getExtra() { return extra; } public void setExtra(String extra) { this.extra = extra; } } bnd-1.50.0/biz.aQute.bndlib/src/aQute/lib/osgi/PreprocessResource.java0000644000175000017500000000224611656076535025426 0ustar drazzibdrazzibpackage aQute.lib.osgi; import java.io.*; public class PreprocessResource extends AbstractResource { final Resource resource; final Processor processor; public PreprocessResource(Processor processor, Resource r) { super(r.lastModified()); this.processor = processor; this.resource = r; extra = resource.getExtra(); } protected byte[] getBytes() throws Exception { ByteArrayOutputStream bout = new ByteArrayOutputStream(2000); OutputStreamWriter osw = new OutputStreamWriter(bout, Constants.DEFAULT_CHARSET); PrintWriter pw = new PrintWriter(osw); InputStream in = resource.openInputStream(); try { BufferedReader rdr = new BufferedReader(new InputStreamReader(in,"UTF8")); String line = rdr.readLine(); while (line != null) { line = processor.getReplacer().process(line); pw.println(line); line = rdr.readLine(); } pw.flush(); byte [] data= bout.toByteArray(); return data; } finally { in.close(); } } } bnd-1.50.0/biz.aQute.bndlib/src/aQute/lib/osgi/Jar.java0000755000175000017500000004253611656076535022316 0ustar drazzibdrazzibpackage aQute.lib.osgi; import static aQute.lib.io.IO.*; import java.io.*; import java.security.*; import java.util.*; import java.util.jar.*; import java.util.regex.*; import java.util.zip.*; import aQute.lib.base64.*; import aQute.libg.reporter.*; public class Jar implements Closeable { public static final Object[] EMPTY_ARRAY = new Jar[0]; Map resources = new TreeMap(); Map> directories = new TreeMap>(); Manifest manifest; boolean manifestFirst; String name; File source; ZipFile zipFile; long lastModified; String lastModifiedReason; Reporter reporter; boolean doNotTouchManifest; boolean nomanifest; public Jar(String name) { this.name = name; } public Jar(String name, File dirOrFile, Pattern doNotCopy) throws ZipException, IOException { this(name); source = dirOrFile; if (dirOrFile.isDirectory()) FileResource.build(this, dirOrFile, doNotCopy); else if (dirOrFile.isFile()) { zipFile = ZipResource.build(this, dirOrFile); } else { throw new IllegalArgumentException("A Jar can only accept a valid file or directory: " + dirOrFile); } } public Jar(String name, InputStream in, long lastModified) throws IOException { this(name); EmbeddedResource.build(this, in, lastModified); } public Jar(String name, String path) throws IOException { this(name); File f = new File(path); InputStream in = new FileInputStream(f); EmbeddedResource.build(this, in, f.lastModified()); in.close(); } public Jar(File f) throws IOException { this(getName(f), f, null); } /** * Make the JAR file name the project name if we get a src or bin directory. * * @param f * @return */ private static String getName(File f) { f = f.getAbsoluteFile(); String name = f.getName(); if (name.equals("bin") || name.equals("src")) return f.getParentFile().getName(); else { if (name.endsWith(".jar")) name = name.substring(0, name.length() - 4); return name; } } public Jar(String string, InputStream resourceAsStream) throws IOException { this(string, resourceAsStream, 0); } public Jar(String string, File file) throws ZipException, IOException { this(string, file, Pattern.compile(Constants.DEFAULT_DO_NOT_COPY)); } public void setName(String name) { this.name = name; } public String toString() { return "Jar:" + name; } public boolean putResource(String path, Resource resource) { return putResource(path, resource, true); } public boolean putResource(String path, Resource resource, boolean overwrite) { updateModified(resource.lastModified(), path); while (path.startsWith("/")) path = path.substring(1); if (path.equals("META-INF/MANIFEST.MF")) { manifest = null; if (resources.isEmpty()) manifestFirst = true; } String dir = getDirectory(path); Map s = directories.get(dir); if (s == null) { s = new TreeMap(); directories.put(dir, s); int n = dir.lastIndexOf('/'); while (n > 0) { String dd = dir.substring(0, n); if (directories.containsKey(dd)) break; directories.put(dd, null); n = dd.lastIndexOf('/'); } } boolean duplicate = s.containsKey(path); if (!duplicate || overwrite) { resources.put(path, resource); s.put(path, resource); } return duplicate; } public Resource getResource(String path) { return resources.get(path); } private String getDirectory(String path) { int n = path.lastIndexOf('/'); if (n < 0) return ""; return path.substring(0, n); } public Map> getDirectories() { return directories; } public Map getResources() { return resources; } public boolean addDirectory(Map directory, boolean overwrite) { boolean duplicates = false; if (directory == null) return false; for (Map.Entry entry : directory.entrySet()) { String key = entry.getKey(); if (!key.endsWith(".java")) { duplicates |= putResource(key, (Resource) entry.getValue(), overwrite); } } return duplicates; } public Manifest getManifest() throws Exception { if (manifest == null) { Resource manifestResource = getResource("META-INF/MANIFEST.MF"); if (manifestResource != null) { InputStream in = manifestResource.openInputStream(); manifest = new Manifest(in); in.close(); } } return manifest; } public boolean exists(String path) { return resources.containsKey(path); } public void setManifest(Manifest manifest) { manifestFirst = true; this.manifest = manifest; } public void write(File file) throws Exception { try { OutputStream out = new FileOutputStream(file); write(out); out.close(); return; } catch (Exception t) { file.delete(); throw t; } } public void write(String file) throws Exception { write(new File(file)); } public void write(OutputStream out) throws Exception { ZipOutputStream jout = nomanifest || doNotTouchManifest ? new ZipOutputStream(out) : new JarOutputStream(out); Set done = new HashSet(); Set directories = new HashSet(); if (doNotTouchManifest) { Resource r = getResource("META-INF/MANIFEST.MF"); if (r != null) { writeResource(jout, directories, "META-INF/MANIFEST.MF", r); done.add("META-INF/MANIFEST.MF"); } } else doManifest(done, jout); for (Map.Entry entry : getResources().entrySet()) { // Skip metainf contents if (!done.contains(entry.getKey())) writeResource(jout, directories, (String) entry.getKey(), (Resource) entry.getValue()); } jout.finish(); } private void doManifest(Set done, ZipOutputStream jout) throws Exception { if (nomanifest) return; JarEntry ze = new JarEntry("META-INF/MANIFEST.MF"); jout.putNextEntry(ze); writeManifest(jout); jout.closeEntry(); done.add(ze.getName()); } /** * Cleanup the manifest for writing. Cleaning up consists of adding a space * after any \n to prevent the manifest to see this newline as a delimiter. * * @param out * Output * @throws IOException */ public void writeManifest(OutputStream out) throws Exception { writeManifest(getManifest(), out); } public static void writeManifest(Manifest manifest, OutputStream out) throws IOException { if (manifest == null) return; manifest = clean(manifest); outputManifest(manifest, out); } /** * Unfortunately we have to write our own manifest :-( because of a stupid * bug in the manifest code. It tries to handle UTF-8 but the way it does it * it makes the bytes platform dependent. * * So the following code outputs the manifest. * * A Manifest consists of * *
	 *   'Manifest-Version: 1.0\r\n'
	 *   main-attributes *
	 *   \r\n
	 *   name-section
	 *   
	 *   main-attributes ::= attributes
	 *   attributes      ::= key ': ' value '\r\n'
	 *   name-section    ::= 'Name: ' name '\r\n' attributes
	 * 
* * Lines in the manifest should not exceed 72 bytes (! this is where the * manifest screwed up as well when 16 bit unicodes were used). * *

* As a bonus, we can now sort the manifest! */ static byte[] CONTINUE = new byte[] {'\r','\n', ' '}; /** * Main function to output a manifest properly in UTF-8. * * @param manifest * The manifest to output * @param out * The output stream * @throws IOException * when something fails */ public static void outputManifest(Manifest manifest, OutputStream out) throws IOException { writeEntry(out, "Manifest-Version", "1.0"); attributes(manifest.getMainAttributes(), out); TreeSet keys = new TreeSet(); for (Object o : manifest.getEntries().keySet()) keys.add(o.toString()); for (String key : keys) { write(out, 0, "\r\n"); writeEntry(out, "Name", key); attributes(manifest.getAttributes(key), out); } } /** * Write out an entry, handling proper unicode and line length constraints * */ private static void writeEntry(OutputStream out, String name, String value) throws IOException { int n = write(out, 0, name + ": "); n = write(out, n, value); write(out, 0, "\r\n"); } /** * Convert a string to bytes with UTF8 and then output in max 72 bytes * * @param out * the output string * @param i * the current width * @param s * the string to output * @return the new width * @throws IOException * when something fails */ private static int write(OutputStream out, int i, String s) throws IOException { byte[] bytes = s.getBytes("UTF8"); return write(out, i, bytes); } /** * Write the bytes but ensure that the line length does not exceed 72 * characters. If it is more than 70 characters, we just put a cr/lf + * space. * * @param out * The output stream * @param width * The nr of characters output in a line before this method * started * @param bytes * the bytes to output * @return the nr of characters in the last line * @throws IOException * if something fails */ private static int write(OutputStream out, int width, byte[] bytes) throws IOException { for (int i = 0; i < bytes.length; i++) { if (width >= 72) { // we need to add the \n\r! out.write(CONTINUE); width = 1; } out.write(bytes[i]); width++; } return width; } /** * Output an Attributes map. We will sort this map before outputing. * * @param value * the attrbutes * @param out * the output stream * @throws IOException * when something fails */ private static void attributes(Attributes value, OutputStream out) throws IOException { TreeMap map = new TreeMap(String.CASE_INSENSITIVE_ORDER); for (Map.Entry entry : value.entrySet()) { map.put(entry.getKey().toString(), entry.getValue().toString()); } map.remove("Manifest-Version"); // get rid of // manifest // version for (Map.Entry entry : map.entrySet()) { writeEntry(out, entry.getKey(), entry.getValue()); } } private static Manifest clean(Manifest org) { Manifest result = new Manifest(); for (Map.Entry entry : org.getMainAttributes().entrySet()) { String nice = clean((String) entry.getValue()); result.getMainAttributes().put(entry.getKey(), nice); } for (String name : org.getEntries().keySet()) { Attributes attrs = result.getAttributes(name); if (attrs == null) { attrs = new Attributes(); result.getEntries().put(name, attrs); } for (Map.Entry entry : org.getAttributes(name).entrySet()) { String nice = clean((String) entry.getValue()); attrs.put((Attributes.Name) entry.getKey(), nice); } } return result; } private static String clean(String s) { if (s.indexOf('\n') < 0) return s; StringBuffer sb = new StringBuffer(s); for (int i = 0; i < sb.length(); i++) { if (sb.charAt(i) == '\n') sb.insert(++i, ' '); } return sb.toString(); } private void writeResource(ZipOutputStream jout, Set directories, String path, Resource resource) throws Exception { if (resource == null) return; createDirectories(directories, jout, path); ZipEntry ze = new ZipEntry(path); ze.setMethod(ZipEntry.DEFLATED); long lastModified = resource.lastModified(); if (lastModified == 0L) { lastModified = System.currentTimeMillis(); } ze.setTime(lastModified); if (resource.getExtra() != null) ze.setExtra(resource.getExtra().getBytes()); jout.putNextEntry(ze); resource.write(jout); jout.closeEntry(); } void createDirectories(Set directories, ZipOutputStream zip, String name) throws IOException { int index = name.lastIndexOf('/'); if (index > 0) { String path = name.substring(0, index); if (directories.contains(path)) return; createDirectories(directories, zip, path); ZipEntry ze = new ZipEntry(path + '/'); zip.putNextEntry(ze); zip.closeEntry(); directories.add(path); } } public String getName() { return name; } /** * Add all the resources in the given jar that match the given filter. * * @param sub * the jar * @param filter * a pattern that should match the resoures in sub to be added */ public boolean addAll(Jar sub, Instruction filter) { return addAll(sub, filter, ""); } /** * Add all the resources in the given jar that match the given filter. * * @param sub * the jar * @param filter * a pattern that should match the resoures in sub to be added */ public boolean addAll(Jar sub, Instruction filter, String destination) { boolean dupl = false; for (String name : sub.getResources().keySet()) { if ("META-INF/MANIFEST.MF".equals(name)) continue; if (filter == null || filter.matches(name) != filter.isNegated()) dupl |= putResource(Processor.appendPath(destination, name), sub.getResource(name), true); } return dupl; } public void close() { if (zipFile != null) try { zipFile.close(); } catch (IOException e) { // Ignore } resources = null; directories = null; manifest = null; source = null; } public long lastModified() { return lastModified; } public void updateModified(long time, String reason) { if (time > lastModified) { lastModified = time; lastModifiedReason = reason; } } public void setReporter(Reporter reporter) { this.reporter = reporter; } public boolean hasDirectory(String path) { return directories.get(path) != null; } public List getPackages() { List list = new ArrayList(directories.size()); for (Map.Entry> i : directories.entrySet()) { if (i.getValue() != null) { String path = i.getKey(); String pack = path.replace('/', '.'); list.add(pack); } } return list; } public File getSource() { return source; } public boolean addAll(Jar src) { return addAll(src, null); } public boolean rename(String oldPath, String newPath) { Resource resource = remove(oldPath); if (resource == null) return false; return putResource(newPath, resource); } public Resource remove(String path) { Resource resource = resources.remove(path); String dir = getDirectory(path); Map mdir = directories.get(dir); // must be != null mdir.remove(path); return resource; } /** * Make sure nobody touches the manifest! If the bundle is signed, we do not * want anybody to touch the manifest after the digests have been * calculated. */ public void setDoNotTouchManifest() { doNotTouchManifest = true; } /** * Calculate the checksums and set them in the manifest. */ public void calcChecksums(String algorithms[]) throws Exception { if (algorithms == null) algorithms = new String[] { "SHA", "MD5" }; Manifest m = getManifest(); if ( m == null) { m= new Manifest(); setManifest(m); } MessageDigest digests[] = new MessageDigest[algorithms.length]; int n = 0; for (String algorithm : algorithms) digests[n++] = MessageDigest.getInstance(algorithm); byte buffer[] = new byte[30000]; for (Map.Entry entry : resources.entrySet()) { // Skip the manifest if (entry.getKey().equals("META-INF/MANIFEST.MF")) continue; Resource r = entry.getValue(); Attributes attributes = m.getAttributes(entry.getKey()); if (attributes == null) { attributes = new Attributes(); getManifest().getEntries().put(entry.getKey(), attributes); } InputStream in = r.openInputStream(); try { for (MessageDigest d : digests) d.reset(); int size = in.read(buffer); while (size > 0) { for (MessageDigest d : digests) d.update(buffer, 0, size); size = in.read(buffer); } } finally { in.close(); } for (MessageDigest d : digests) attributes.putValue(d.getAlgorithm() + "-Digest", Base64.encodeBase64(d.digest())); } } Pattern BSN = Pattern.compile("\\s*([-\\w\\d\\._]+)\\s*;?.*"); public String getBsn() throws Exception { Manifest m = getManifest(); if (m == null) return null; String s = m.getMainAttributes().getValue(Constants.BUNDLE_SYMBOLICNAME); Matcher matcher = BSN.matcher(s); if (matcher.matches()) { return matcher.group(1); } return null; } public String getVersion() throws Exception { Manifest m = getManifest(); if (m == null) return null; String s = m.getMainAttributes().getValue(Constants.BUNDLE_VERSION); if (s == null) return null; return s.trim(); } /** * Expand the JAR file to a directory. * * @param dir * the dst directory, is not required to exist * @throws Exception * if anything does not work as expected. */ public void expand(File dir) throws Exception { dir = dir.getAbsoluteFile(); dir.mkdirs(); if (!dir.isDirectory()) { throw new IllegalArgumentException("Not a dir: " + dir.getAbsolutePath()); } for (Map.Entry entry : getResources().entrySet()) { File f = getFile(dir, entry.getKey()); f.getParentFile().mkdirs(); copy(entry.getValue().openInputStream(), f); } } /** * Make sure we have a manifest * @throws Exception */ public void ensureManifest() throws Exception { if ( getManifest() != null) return; manifest = new Manifest(); } } bnd-1.50.0/biz.aQute.bndlib/src/aQute/lib/osgi/Analyzer.java0000755000175000017500000020257211656076535023365 0ustar drazzibdrazzibpackage aQute.lib.osgi; /** * This class can calculate the required headers for a (potential) JAR file. It * analyzes a directory or JAR for the packages that are contained and that are * referred to by the bytecodes. The user can the use regular expressions to * define the attributes and directives. The matching is not fully regex for * convenience. A * and ? get a . prefixed and dots are escaped. * *

 *                                                             			*;auto=true				any		
 *                                                             			org.acme.*;auto=true    org.acme.xyz
 *                                                             			org.[abc]*;auto=true    org.acme.xyz
 * 
* * Additional, the package instruction can start with a '=' or a '!'. The '!' * indicates negation. Any matching package is removed. The '=' is literal, the * expression will be copied verbatim and no matching will take place. * * Any headers in the given properties are used in the output properties. */ import java.io.*; import java.net.*; import java.util.*; import java.util.Map.Entry; import java.util.jar.*; import java.util.jar.Attributes.Name; import java.util.regex.*; import aQute.bnd.annotation.*; import aQute.bnd.service.*; import aQute.lib.base64.*; import aQute.lib.collections.*; import aQute.lib.filter.*; import aQute.lib.hex.*; import aQute.lib.io.*; import aQute.lib.osgi.Clazz.QUERY; import aQute.libg.cryptography.*; import aQute.libg.generics.*; import aQute.libg.header.*; import aQute.libg.tarjan.*; import aQute.libg.version.Version; public class Analyzer extends Processor { static String version; static Pattern versionPattern = Pattern .compile("(\\d+\\.\\d+)\\.\\d+.*"); final Map> contained = newHashMap(); // package final Map> referred = newHashMap(); // refers // package final Map> uses = newHashMap(); // package Map classspace; Map importedClassesCache = newMap(); Map> exports; Map> imports; Map> bundleClasspath; // Bundle final Map> ignored = newHashMap(); // Ignored // packages Jar dot; Map> classpathExports; String activator; final List classpath = newList(); static Properties bndInfo; boolean analyzed; String bsn; String versionPolicyUses; String versionPolicyImplemented; boolean diagnostics = false; SortedSet formats = new TreeSet(); private boolean inited; public Analyzer(Processor parent) { super(parent); } public Analyzer() { } /** * Specifically for Maven * * @param properties * the properties */ public static Properties getManifest(File dirOrJar) throws Exception { Analyzer analyzer = new Analyzer(); try { analyzer.setJar(dirOrJar); Properties properties = new Properties(); properties.put(IMPORT_PACKAGE, "*"); properties.put(EXPORT_PACKAGE, "*"); analyzer.setProperties(properties); Manifest m = analyzer.calcManifest(); Properties result = new Properties(); for (Iterator i = m.getMainAttributes().keySet().iterator(); i.hasNext();) { Attributes.Name name = (Attributes.Name) i.next(); result.put(name.toString(), m.getMainAttributes().getValue(name)); } return result; } finally { analyzer.close(); } } /** * Calculates the data structures for generating a manifest. * * @throws IOException */ public void analyze() throws Exception { if (!analyzed) { analyzed = true; activator = getProperty(BUNDLE_ACTIVATOR); bundleClasspath = parseHeader(getProperty(BUNDLE_CLASSPATH)); analyzeClasspath(); classspace = analyzeBundleClasspath(dot, bundleClasspath, contained, referred, uses); for (AnalyzerPlugin plugin : getPlugins(AnalyzerPlugin.class)) { if (plugin instanceof AnalyzerPlugin) { AnalyzerPlugin analyzer = (AnalyzerPlugin) plugin; try { boolean reanalyze = analyzer.analyzeJar(this); if (reanalyze) classspace = analyzeBundleClasspath(dot, bundleClasspath, contained, referred, uses); } catch (Exception e) { error("Plugin Analyzer " + analyzer + " throws exception " + e); e.printStackTrace(); } } } if (activator != null) { // Add the package of the activator to the set // of referred classes. This must be done before we remove // contained set. int n = activator.lastIndexOf('.'); if (n > 0) { referred.put(activator.substring(0, n), new LinkedHashMap()); } } referred.keySet().removeAll(contained.keySet()); if (referred.containsKey(".")) { error("The default package '.' is not permitted by the Import-Package syntax. \n" + " This can be caused by compile errors in Eclipse because Eclipse creates \n" + "valid class files regardless of compile errors.\n" + "The following package(s) import from the default package " + getUsedBy(".")); } Map> exportInstructions = parseHeader(getProperty(EXPORT_PACKAGE)); Map> additionalExportInstructions = parseHeader(getProperty(EXPORT_CONTENTS)); exportInstructions.putAll(additionalExportInstructions); Map> importInstructions = parseHeader(getImportPackages()); Map> dynamicImports = parseHeader(getProperty(DYNAMICIMPORT_PACKAGE)); if (dynamicImports != null) { // Remove any dynamic imports from the referred set. referred.keySet().removeAll(dynamicImports.keySet()); } Map> superfluous = newHashMap(); // Tricky! for (Iterator i = exportInstructions.keySet().iterator(); i.hasNext();) { String instr = i.next(); if (!instr.startsWith("!")) superfluous.put(instr, exportInstructions.get(instr)); } exports = merge("export-package", exportInstructions, contained, superfluous.keySet(), null); // disallow export of default package exports.remove("."); for (Iterator>> i = superfluous.entrySet() .iterator(); i.hasNext();) { // It is possible to mention metadata directories in the export // explicitly, they are then exported and removed from the // warnings. Note that normally metadata directories are not // exported. Map.Entry> entry = i.next(); String pack = entry.getKey(); if (isDuplicate(pack)) i.remove(); else if (isMetaData(pack)) { exports.put(pack, entry.getValue()); i.remove(); } } if (!superfluous.isEmpty()) { warning("Superfluous export-package instructions: " + superfluous.keySet()); } // Add all exports that do not have an -noimport: directive // to the imports. Map> referredAndExported = newMap(referred); referredAndExported.putAll(doExportsToImports(exports)); // match the imports to the referred and exported packages, // merge the info for matching packages Set extra = new TreeSet(importInstructions.keySet()); imports = merge("import-package", importInstructions, referredAndExported, extra, ignored); // Instructions that have not been used could be superfluous // or if they do not contain wildcards, should be added // as extra imports, the user knows best. for (Iterator i = extra.iterator(); i.hasNext();) { String p = i.next(); if (p.startsWith("!") || p.indexOf('*') >= 0 || p.indexOf('?') >= 0 || p.indexOf('[') >= 0) { if (!isResourceOnly() && !(p.equals("*"))) warning("Did not find matching referal for " + p); } else { Map map = importInstructions.get(p); imports.put(p, map); } } // See what information we can find to augment the // exports. I.e. look on the classpath augmentExports(); // See what information we can find to augment the // imports. I.e. look on the classpath augmentImports(); // Add the uses clause to the exports doUses(exports, uses, imports); } } /** * Copy the input collection into an output set but skip names that have * been marked as duplicates or are optional. * * @param superfluous * @return */ Set removeMarkedDuplicates(Collection superfluous) { Set result = new HashSet(); for (Iterator i = superfluous.iterator(); i.hasNext();) { Instruction instr = (Instruction) i.next(); if (!isDuplicate(instr.getPattern()) && !instr.isOptional()) result.add(instr); } return result; } /** * Analyzer has an empty default but the builder has a * as default. * * @return */ protected String getImportPackages() { return getProperty(IMPORT_PACKAGE); } /** * * @return */ boolean isResourceOnly() { return isTrue(getProperty(RESOURCEONLY)); } /** * Answer the list of packages that use the given package. */ Set getUsedBy(String pack) { Set set = newSet(); for (Iterator>> i = uses.entrySet().iterator(); i.hasNext();) { Map.Entry> entry = i.next(); Set used = entry.getValue(); if (used.contains(pack)) set.add(entry.getKey()); } return set; } /** * One of the main workhorses of this class. This will analyze the current * setp and calculate a new manifest according to this setup. This method * will also set the manifest on the main jar dot * * @return * @throws IOException */ public Manifest calcManifest() throws Exception { analyze(); Manifest manifest = new Manifest(); Attributes main = manifest.getMainAttributes(); main.put(Attributes.Name.MANIFEST_VERSION, "1.0"); main.putValue(BUNDLE_MANIFESTVERSION, "2"); boolean noExtraHeaders = "true".equalsIgnoreCase(getProperty(NOEXTRAHEADERS)); if (!noExtraHeaders) { main.putValue(CREATED_BY, System.getProperty("java.version") + " (" + System.getProperty("java.vendor") + ")"); main.putValue(TOOL, "Bnd-" + getBndVersion()); main.putValue(BND_LASTMODIFIED, "" + System.currentTimeMillis()); } String exportHeader = printClauses(exports, true); if (exportHeader.length() > 0) main.putValue(EXPORT_PACKAGE, exportHeader); else main.remove(EXPORT_PACKAGE); Map> temp = removeKeys(imports, "java."); if (!temp.isEmpty()) { main.putValue(IMPORT_PACKAGE, printClauses(temp)); } else { main.remove(IMPORT_PACKAGE); } temp = newMap(contained); temp.keySet().removeAll(exports.keySet()); if (!temp.isEmpty()) main.putValue(PRIVATE_PACKAGE, printClauses(temp)); else main.remove(PRIVATE_PACKAGE); if (!ignored.isEmpty()) { main.putValue(IGNORE_PACKAGE, printClauses(ignored)); } else { main.remove(IGNORE_PACKAGE); } if (bundleClasspath != null && !bundleClasspath.isEmpty()) main.putValue(BUNDLE_CLASSPATH, printClauses(bundleClasspath)); else main.remove(BUNDLE_CLASSPATH); doNamesection(dot, manifest); for (Enumeration h = getProperties().propertyNames(); h.hasMoreElements();) { String header = (String) h.nextElement(); if (header.trim().length() == 0) { warning("Empty property set with value: " + getProperties().getProperty(header)); continue; } if (isMissingPlugin(header.trim())) { error("Missing plugin for command %s", header); } if (!Character.isUpperCase(header.charAt(0))) { if (header.charAt(0) == '@') doNameSection(manifest, header); continue; } if (header.equals(BUNDLE_CLASSPATH) || header.equals(EXPORT_PACKAGE) || header.equals(IMPORT_PACKAGE)) continue; if (header.equalsIgnoreCase("Name")) { error("Your bnd file contains a header called 'Name'. This interferes with the manifest name section."); continue; } if (Verifier.HEADER_PATTERN.matcher(header).matches()) { String value = getProperty(header); if (value != null && main.getValue(header) == null) { if (value.trim().length() == 0) main.remove(header); else if (value.trim().equals(EMPTY_HEADER)) main.putValue(header, ""); else main.putValue(header, value); } } else { // TODO should we report? } } // // Calculate the bundle symbolic name if it is // not set. // 1. set // 2. name of properties file (must be != bnd.bnd) // 3. name of directory, which is usualy project name // String bsn = getBsn(); if (main.getValue(BUNDLE_SYMBOLICNAME) == null) { main.putValue(BUNDLE_SYMBOLICNAME, bsn); } // // Use the same name for the bundle name as BSN when // the bundle name is not set // if (main.getValue(BUNDLE_NAME) == null) { main.putValue(BUNDLE_NAME, bsn); } if (main.getValue(BUNDLE_VERSION) == null) main.putValue(BUNDLE_VERSION, "0"); // Copy old values into new manifest, when they // exist in the old one, but not in the new one merge(manifest, dot.getManifest()); // Remove all the headers mentioned in -removeheaders Map> removes = parseHeader(getProperty(REMOVEHEADERS)); Set matchers = Instruction.replaceWithInstruction(removes).keySet(); Collection toBeRemoved = Instruction.select(matchers, main.keySet()); Iterator i = main.keySet().iterator(); while (i.hasNext()) if (toBeRemoved.contains(i.next())) i.remove(); dot.setManifest(manifest); return manifest; } /** * Parse the namesection as instructions and then match them against the * current set of resources * * For example: * *
	 * 	-namesection: *;baz=true, abc/def/bar/X.class=3
	 * 
* * The raw value of {@link Constants#NAMESECTION} is used but the values of * the attributes are replaced where @ is set to the resource name. This * allows macro to operate on the resource * */ private void doNamesection(Jar dot, Manifest manifest) { Map> namesection = parseHeader(getProperties().getProperty( NAMESECTION)); Set>> instructions = Instruction .replaceWithInstruction(namesection).entrySet(); Set> resources = new HashSet>(dot .getResources().entrySet()); // // For each instruction, iterator over the resources and filter // them. If a resource matches, it must be removed even if the // instruction is negative. If positive, add a name section // to the manifest for the given resource name. Then add all // attributes from the instruction to that name section. // for (Map.Entry> instr : instructions) { boolean matched = false; // For each instruction for (Iterator> it = resources.iterator(); it.hasNext();) { // For each resource Map.Entry next = it.next(); if (instr.getKey().matches(next.getKey())) { // Instruction matches the resource matched = true; if (!instr.getKey().isNegated()) { // Positive match, add the attributes Attributes attrs = manifest.getAttributes(next.getKey()); if (attrs == null) { attrs = new Attributes(); manifest.getEntries().put(next.getKey(), attrs); } // // Add all the properties from the instruction to the // name section // for (Map.Entry property : instr.getValue().entrySet()) { setProperty("@", next.getKey()); try { String processed = getReplacer().process(property.getValue()); attrs.putValue(property.getKey(), processed); } finally { unsetProperty("@"); } } } it.remove(); } } if (!matched) warning("The instruction %s in %s did not match any resources", instr.getKey(), NAMESECTION); } } /** * This method is called when the header starts with a @, signifying a name * section header. The name part is defined by replacing all the @ signs to * a /, removing the first and the last, and using the last part as header * name: * *
	 * @org@osgi@service@event@Implementation-Title
	 * 
* * This will be the header Implementation-Title in the * org/osgi/service/event named section. * * @param manifest * @param header */ private void doNameSection(Manifest manifest, String header) { String path = header.replace('@', '/'); int n = path.lastIndexOf('/'); // Must succeed because we start with @ String name = path.substring(n + 1); // Skip first / path = path.substring(1, n); if (name.length() != 0 && path.length() != 0) { Attributes attrs = manifest.getAttributes(path); if (attrs == null) { attrs = new Attributes(); manifest.getEntries().put(path, attrs); } attrs.putValue(name, getProperty(header)); } else { warning("Invalid header (starts with @ but does not seem to be for the Name section): %s", header); } } /** * Clear the key part of a header. I.e. remove everything from the first ';' * * @param value * @return */ public String getBsn() { String value = getProperty(BUNDLE_SYMBOLICNAME); if (value == null) { if (getPropertiesFile() != null) value = getPropertiesFile().getName(); String projectName = getBase().getName(); if (value == null || value.equals("bnd.bnd")) { value = projectName; } else if (value.endsWith(".bnd")) { value = value.substring(0, value.length() - 4); if (!value.startsWith(getBase().getName())) value = projectName + "." + value; } } if (value == null) return "untitled"; int n = value.indexOf(';'); if (n > 0) value = value.substring(0, n); return value.trim(); } public String _bsn(String args[]) { return getBsn(); } /** * Calculate an export header solely based on the contents of a JAR file * * @param bundle * The jar file to analyze * @return */ public String calculateExportsFromContents(Jar bundle) { String ddel = ""; StringBuffer sb = new StringBuffer(); Map> map = bundle.getDirectories(); for (Iterator i = map.keySet().iterator(); i.hasNext();) { String directory = (String) i.next(); if (directory.equals("META-INF") || directory.startsWith("META-INF/")) continue; if (directory.equals("OSGI-OPT") || directory.startsWith("OSGI-OPT/")) continue; if (directory.equals("/")) continue; if (directory.endsWith("/")) directory = directory.substring(0, directory.length() - 1); directory = directory.replace('/', '.'); sb.append(ddel); sb.append(directory); ddel = ","; } return sb.toString(); } public Map> getBundleClasspath() { return bundleClasspath; } public Map> getContained() { return contained; } public Map> getExports() { return exports; } public Map> getImports() { return imports; } public Jar getJar() { return dot; } public Map> getReferred() { return referred; } /** * Return the set of unreachable code depending on exports and the bundle * activator. * * @return */ public Set getUnreachable() { Set unreachable = new HashSet(uses.keySet()); // all for (Iterator r = exports.keySet().iterator(); r.hasNext();) { String packageName = r.next(); removeTransitive(packageName, unreachable); } if (activator != null) { String pack = activator.substring(0, activator.lastIndexOf('.')); removeTransitive(pack, unreachable); } return unreachable; } public Map> getUses() { return uses; } /** * Get the version for this bnd * * @return version or unknown. */ public String getBndVersion() { return getBndInfo("version", "1.42.1"); } public long getBndLastModified() { String time = getBndInfo("modified", "0"); try { return Long.parseLong(time); } catch (Exception e) { } return 0; } public String getBndInfo(String key, String defaultValue) { if (bndInfo == null) { bndInfo = new Properties(); try { InputStream in = Analyzer.class.getResourceAsStream("bnd.info"); if (in != null) { bndInfo.load(in); in.close(); } } catch (IOException ioe) { warning("Could not read bnd.info in " + Analyzer.class.getPackage() + ioe); } } return bndInfo.getProperty(key, defaultValue); } /** * Merge the existing manifest with the instructions. * * @param manifest * The manifest to merge with * @throws IOException */ public void mergeManifest(Manifest manifest) throws IOException { if (manifest != null) { Attributes attributes = manifest.getMainAttributes(); for (Iterator i = attributes.keySet().iterator(); i.hasNext();) { Name name = (Name) i.next(); String key = name.toString(); // Dont want instructions if (key.startsWith("-")) continue; if (getProperty(key) == null) setProperty(key, (String) attributes.get(name)); } } } public void setBase(File file) { super.setBase(file); getProperties().put("project.dir", getBase().getAbsolutePath()); } /** * Set the classpath for this analyzer by file. * * @param classpath * @throws IOException */ public void setClasspath(File[] classpath) throws IOException { List list = new ArrayList(); for (int i = 0; i < classpath.length; i++) { if (classpath[i].exists()) { Jar current = new Jar(classpath[i]); list.add(current); } else { error("Missing file on classpath: %s", classpath[i]); } } for (Iterator i = list.iterator(); i.hasNext();) { addClasspath(i.next()); } } public void setClasspath(Jar[] classpath) { for (int i = 0; i < classpath.length; i++) { addClasspath(classpath[i]); } } public void setClasspath(String[] classpath) { for (int i = 0; i < classpath.length; i++) { Jar jar = getJarFromName(classpath[i], " setting classpath"); if (jar != null) addClasspath(jar); } } /** * Set the JAR file we are going to work in. This will read the JAR in * memory. * * @param jar * @return * @throws IOException */ public Jar setJar(File jar) throws IOException { Jar jarx = new Jar(jar); addClose(jarx); return setJar(jarx); } /** * Set the JAR directly we are going to work on. * * @param jar * @return */ public Jar setJar(Jar jar) { this.dot = jar; return jar; } protected void begin() { if (inited == false) { inited = true; super.begin(); updateModified(getBndLastModified(), "bnd last modified"); verifyManifestHeadersCase(getProperties()); } } /** * Check if the given class or interface name is contained in the jar. * * @param interfaceName * @return */ public boolean checkClass(String interfaceName) { String path = Clazz.fqnToPath(interfaceName); if (classspace.containsKey(path)) return true; if (interfaceName.startsWith("java.")) return true; if (imports != null && !imports.isEmpty()) { String pack = interfaceName; int n = pack.lastIndexOf('.'); if (n > 0) pack = pack.substring(0, n); else pack = "."; if (imports.containsKey(pack)) return true; } int n = interfaceName.lastIndexOf('.'); if (n > 0 && n + 1 < interfaceName.length() && Character.isUpperCase(interfaceName.charAt(n + 1))) { return checkClass(interfaceName.substring(0, n) + '$' + interfaceName.substring(n + 1)); } return false; } /** * Try to get a Jar from a file name/path or a url, or in last resort from * the classpath name part of their files. * * @param name * URL or filename relative to the base * @param from * Message identifying the caller for errors * @return null or a Jar with the contents for the name */ Jar getJarFromName(String name, String from) { File file = new File(name); if (!file.isAbsolute()) file = new File(getBase(), name); if (file.exists()) try { Jar jar = new Jar(file); addClose(jar); return jar; } catch (Exception e) { error("Exception in parsing jar file for " + from + ": " + name + " " + e); } // It is not a file ... try { // Lets try a URL URL url = new URL(name); Jar jar = new Jar(fileName(url.getPath())); addClose(jar); URLConnection connection = url.openConnection(); InputStream in = connection.getInputStream(); long lastModified = connection.getLastModified(); if (lastModified == 0) // We assume the worst :-( lastModified = System.currentTimeMillis(); EmbeddedResource.build(jar, in, lastModified); in.close(); return jar; } catch (IOException ee) { // Check if we have files on the classpath // that have the right name, allows us to specify those // names instead of the full path. for (Iterator cp = getClasspath().iterator(); cp.hasNext();) { Jar entry = cp.next(); if (entry.source != null && entry.source.getName().equals(name)) { return entry; } } // error("Can not find jar file for " + from + ": " + name); } return null; } private String fileName(String path) { int n = path.lastIndexOf('/'); if (n > 0) return path.substring(n + 1); return path; } /** * * @param manifests * @throws Exception */ void merge(Manifest result, Manifest old) throws IOException { if (old != null) { for (Iterator> e = old.getMainAttributes().entrySet() .iterator(); e.hasNext();) { Map.Entry entry = e.next(); Attributes.Name name = (Attributes.Name) entry.getKey(); String value = (String) entry.getValue(); if (name.toString().equalsIgnoreCase("Created-By")) name = new Attributes.Name("Originally-Created-By"); if (!result.getMainAttributes().containsKey(name)) result.getMainAttributes().put(name, value); } // do not overwrite existing entries Map oldEntries = old.getEntries(); Map newEntries = result.getEntries(); for (Iterator> e = oldEntries.entrySet().iterator(); e .hasNext();) { Map.Entry entry = e.next(); if (!newEntries.containsKey(entry.getKey())) { newEntries.put(entry.getKey(), entry.getValue()); } } } } String stem(String name) { int n = name.lastIndexOf('.'); if (n > 0) return name.substring(0, n); else return name; } /** * Bnd is case sensitive for the instructions so we better check people are * not using an invalid case. We do allow this to set headers that should * not be processed by us but should be used by the framework. * * @param properties * Properties to verify. */ void verifyManifestHeadersCase(Properties properties) { for (Iterator i = properties.keySet().iterator(); i.hasNext();) { String header = (String) i.next(); for (int j = 0; j < headers.length; j++) { if (!headers[j].equals(header) && headers[j].equalsIgnoreCase(header)) { warning("Using a standard OSGi header with the wrong case (bnd is case sensitive!), using: " + header + " and expecting: " + headers[j]); break; } } } } /** * We will add all exports to the imports unless there is a -noimport * directive specified on an export. This directive is skipped for the * manifest. * * We also remove any version parameter so that augmentImports can do the * version policy. * * The following method is really tricky and evolved over time. Coming from * the original background of OSGi, it was a weird idea for me to have a * public package that should not be substitutable. I was so much convinced * that this was the right rule that I rücksichtlos imported them all. Alas, * the real world was more subtle than that. It turns out that it is not a * good idea to always import. First, there must be a need to import, i.e. * there must be a contained package that refers to the exported package for * it to make use importing that package. Second, if an exported package * refers to an internal package than it should not be imported. * * Additionally, it is necessary to treat the exports in groups. If an * exported package refers to another exported packages than it must be in * the same group. A framework can only substitute exports for imports for * the whole of such a group. WHY????? Not clear anymore ... * */ /** * I could no longer argue why the groups are needed :-( See what happens * ... The getGroups calculated the groups and then removed the imports from * there. Now we only remove imports that have internal references. Using * internal code for an exported package means that a bundle cannot import * that package from elsewhere because its assumptions might be violated if * it receives a substitution. // */ Map> doExportsToImports(Map> exports) { // private packages = contained - exported. Set privatePackages = new HashSet(contained.keySet()); privatePackages.removeAll(exports.keySet()); // private references = ∀ p : private packages | uses(p) Set privateReferences = newSet(); for (String p : privatePackages) { Set uses = this.uses.get(p); if (uses != null) privateReferences.addAll(uses); } // Assume we are going to export all exported packages Set toBeImported = new HashSet(exports.keySet()); // Remove packages that are not referenced privately toBeImported.retainAll(privateReferences); // Not necessary to import anything that is already // imported in the Import-Package statement. if (imports != null) toBeImported.removeAll(imports.keySet()); // Remove exported packages that are referring to // private packages. // Each exported package has a uses clause. We just use // the used packages for each exported package to find out // if it refers to an internal package. // for (Iterator i = toBeImported.iterator(); i.hasNext();) { Set usedByExportedPackage = this.uses.get(i.next()); for (String privatePackage : privatePackages) { if (usedByExportedPackage.contains(privatePackage)) { i.remove(); break; } } } // Clean up attributes and generate result map Map> result = newMap(); for (Iterator i = toBeImported.iterator(); i.hasNext();) { String ep = i.next(); Map parameters = exports.get(ep); String noimport = parameters.get(NO_IMPORT_DIRECTIVE); if (noimport != null && noimport.equalsIgnoreCase("true")) continue; // // we can't substitute when there is no version // String version = parameters.get(VERSION_ATTRIBUTE); // if (version == null) { // if (isPedantic()) // warning( // "Cannot automatically import exported package %s because it has no version defined", // ep); // continue; // } parameters = newMap(parameters); parameters.remove(VERSION_ATTRIBUTE); result.put(ep, parameters); } return result; } private boolean intersects(Collection aa, Collection bb) { if (aa.equals(bb)) return true; if (aa.size() > bb.size()) return intersects(bb, aa); for (T t : aa) if (bb.contains(t)) return true; return false; } public boolean referred(String packageName) { // return true; for (Map.Entry> contained : uses.entrySet()) { if (!contained.getKey().equals(packageName)) { if (contained.getValue().contains(packageName)) return true; } } return false; } /** * Create the imports/exports by parsing * * @throws IOException */ void analyzeClasspath() throws Exception { classpathExports = newHashMap(); for (Iterator c = getClasspath().iterator(); c.hasNext();) { Jar current = c.next(); checkManifest(current); for (Iterator j = current.getDirectories().keySet().iterator(); j.hasNext();) { String dir = j.next(); Resource resource = current.getResource(dir + "/packageinfo"); if (resource != null) { InputStream in = resource.openInputStream(); try { String version = parsePackageInfo(in); setPackageInfo(dir, VERSION_ATTRIBUTE, version); } finally { in.close(); } } } } } /** * * @param jar */ void checkManifest(Jar jar) { try { Manifest m = jar.getManifest(); if (m != null) { String exportHeader = m.getMainAttributes().getValue(EXPORT_PACKAGE); if (exportHeader != null) { Map> exported = parseHeader(exportHeader); if (exported != null) { for (Map.Entry> entry : exported.entrySet()) { if (!classpathExports.containsKey(entry.getKey())) { classpathExports.put(entry.getKey(), entry.getValue()); } } } } } } catch (Exception e) { warning("Erroneous Manifest for " + jar + " " + e); } } /** * Find some more information about imports in manifest and other places. */ void augmentImports() { for (String packageName : imports.keySet()) { setProperty(CURRENT_PACKAGE, packageName); try { Map importAttributes = imports.get(packageName); Map exporterAttributes = classpathExports.get(packageName); if (exporterAttributes == null) exporterAttributes = exports.get(packageName); if (exporterAttributes != null) { augmentVersion(importAttributes, exporterAttributes); augmentMandatory(importAttributes, exporterAttributes); if (exporterAttributes.containsKey(IMPORT_DIRECTIVE)) importAttributes.put(IMPORT_DIRECTIVE, exporterAttributes.get(IMPORT_DIRECTIVE)); } fixupAttributes(importAttributes); removeAttributes(importAttributes); } finally { unsetProperty(CURRENT_PACKAGE); } } } /** * Provide any macro substitutions and versions for exported packages. */ void augmentExports() { for (String packageName : exports.keySet()) { setProperty(CURRENT_PACKAGE, packageName); try { Map attributes = exports.get(packageName); Map exporterAttributes = classpathExports.get(packageName); if (exporterAttributes == null) continue; for (Map.Entry entry : exporterAttributes.entrySet()) { String key = entry.getKey(); if (key.equalsIgnoreCase(SPECIFICATION_VERSION)) key = VERSION_ATTRIBUTE; if (!key.endsWith(":") && !attributes.containsKey(key)) { attributes.put(key, entry.getValue()); } } fixupAttributes(attributes); removeAttributes(attributes); } finally { unsetProperty(CURRENT_PACKAGE); } } } /** * Fixup Attributes * * Execute any macros on an export and */ void fixupAttributes(Map attributes) { // Convert any attribute values that have macros. for (String key : attributes.keySet()) { String value = attributes.get(key); if (value.indexOf('$') >= 0) { value = getReplacer().process(value); attributes.put(key, value); } } } /* * Remove the attributes mentioned in the REMOVE_ATTRIBUTE_DIRECTIVE. */ void removeAttributes(Map attributes) { // You can add a remove-attribute: directive with a regular // expression for attributes that need to be removed. We also // remove all attributes that have a value of !. This allows // you to use macros with ${if} to remove values. String remove = attributes.remove(REMOVE_ATTRIBUTE_DIRECTIVE); Instruction removeInstr = null; if (remove != null) removeInstr = Instruction.getPattern(remove); for (Iterator> i = attributes.entrySet().iterator(); i.hasNext();) { Map.Entry entry = i.next(); if (entry.getValue().equals("!")) i.remove(); else if (removeInstr != null && removeInstr.matches((String) entry.getKey())) i.remove(); else { // Not removed ... } } } /** * If we use an import with mandatory attributes we better all use them * * @param currentAttributes * @param exporter */ private void augmentMandatory(Map currentAttributes, Map exporter) { String mandatory = (String) exporter.get("mandatory:"); if (mandatory != null) { String[] attrs = mandatory.split("\\s*,\\s*"); for (int i = 0; i < attrs.length; i++) { if (!currentAttributes.containsKey(attrs[i])) currentAttributes.put(attrs[i], exporter.get(attrs[i])); } } } /** * Check if we can augment the version from the exporter. * * We allow the version in the import to specify a @ which is replaced with * the exporter's version. * * @param currentAttributes * @param exporter */ private void augmentVersion(Map currentAttributes, Map exporter) { String exportVersion = (String) exporter.get(VERSION_ATTRIBUTE); if (exportVersion == null) return; exportVersion = cleanupVersion(exportVersion); String importRange = currentAttributes.get(VERSION_ATTRIBUTE); boolean impl = isTrue(currentAttributes.get(PROVIDE_DIRECTIVE)); try { setProperty("@", exportVersion); if (importRange != null) { importRange = cleanupVersion(importRange); importRange = getReplacer().process(importRange); } else importRange = getVersionPolicy(impl); } finally { unsetProperty("@"); } // See if we can borrow the version // we must replace the ${@} with the version we // found this can be useful if you want a range to start // with the found version. currentAttributes.put(VERSION_ATTRIBUTE, importRange); } /** * Calculate a version from a version policy. * * @param version * The actual exported version * @param impl * true for implementations and false for clients */ String calculateVersionRange(String version, boolean impl) { setProperty("@", version); try { return getVersionPolicy(impl); } finally { unsetProperty("@"); } } /** * Add the uses clauses. This method iterates over the exports and cal * * @param exports * @param uses * @throws MojoExecutionException */ void doUses(Map> exports, Map> uses, Map> imports) { if ("true".equalsIgnoreCase(getProperty(NOUSES))) return; for (Iterator i = exports.keySet().iterator(); i.hasNext();) { String packageName = i.next(); setProperty(CURRENT_PACKAGE, packageName); try { doUses(packageName, exports, uses, imports); } finally { unsetProperty(CURRENT_PACKAGE); } } } /** * @param packageName * @param exports * @param uses * @param imports */ protected void doUses(String packageName, Map> exports, Map> uses, Map> imports) { Map clause = exports.get(packageName); // Check if someone already set the uses: directive String override = clause.get(USES_DIRECTIVE); if (override == null) override = USES_USES; // Get the used packages Set usedPackages = uses.get(packageName); if (usedPackages != null) { // Only do a uses on exported or imported packages // and uses should also not contain our own package // name Set sharedPackages = new HashSet(); sharedPackages.addAll(imports.keySet()); sharedPackages.addAll(exports.keySet()); usedPackages.retainAll(sharedPackages); usedPackages.remove(packageName); StringBuffer sb = new StringBuffer(); String del = ""; for (Iterator u = usedPackages.iterator(); u.hasNext();) { String usedPackage = u.next(); if (!usedPackage.startsWith("java.")) { sb.append(del); sb.append(usedPackage); del = ","; } } if (override.indexOf('$') >= 0) { setProperty(CURRENT_USES, sb.toString()); override = getReplacer().process(override); unsetProperty(CURRENT_USES); } else // This is for backward compatibility 0.0.287 // can be deprecated over time override = override.replaceAll(USES_USES, sb.toString()).trim(); if (override.endsWith(",")) override = override.substring(0, override.length() - 1); if (override.startsWith(",")) override = override.substring(1); if (override.length() > 0) { clause.put(USES_DIRECTIVE, override); } } } /** * Transitively remove all elemens from unreachable through the uses link. * * @param name * @param unreachable */ void removeTransitive(String name, Set unreachable) { if (!unreachable.contains(name)) return; unreachable.remove(name); Set ref = uses.get(name); if (ref != null) { for (Iterator r = ref.iterator(); r.hasNext();) { String element = (String) r.next(); removeTransitive(element, unreachable); } } } /** * Helper method to set the package info * * @param dir * @param key * @param value */ void setPackageInfo(String dir, String key, String value) { if (value != null) { String pack = dir.replace('/', '.'); Map map = classpathExports.get(pack); if (map == null) { map = new HashMap(); classpathExports.put(pack, map); } if (!map.containsKey(VERSION_ATTRIBUTE)) map.put(key, value); else if (!map.get(VERSION_ATTRIBUTE).equals(value)) { // System.out.println("duplicate version info for " + dir + " " // + value + " and " + map.get(VERSION_ATTRIBUTE)); } } } public void close() { if (diagnostics) { PrintStream out = System.out; out.printf("Current directory : %s\n", new File("").getAbsolutePath()); out.println("Classpath used"); for (Jar jar : getClasspath()) { out.printf("File : %s\n", jar.getSource()); out.printf("File abs path : %s\n", jar.getSource() .getAbsolutePath()); out.printf("Name : %s\n", jar.getName()); Map> dirs = jar.getDirectories(); for (Map.Entry> entry : dirs.entrySet()) { Map dir = entry.getValue(); String name = entry.getKey().replace('/', '.'); if (dir != null) { out.printf(" %-30s %d\n", name, dir.size()); } else { out.printf(" %-30s <>\n", name); } } } } super.close(); if (dot != null) dot.close(); if (classpath != null) for (Iterator j = classpath.iterator(); j.hasNext();) { Jar jar = j.next(); jar.close(); } } /** * Findpath looks through the contents of the JAR and finds paths that end * with the given regular expression * * ${findpath (; reg-expr (; replacement)? )? } * * @param args * @return */ public String _findpath(String args[]) { return findPath("findpath", args, true); } public String _findname(String args[]) { return findPath("findname", args, false); } String findPath(String name, String[] args, boolean fullPathName) { if (args.length > 3) { warning("Invalid nr of arguments to " + name + " " + Arrays.asList(args) + ", syntax: ${" + name + " (; reg-expr (; replacement)? )? }"); return null; } String regexp = ".*"; String replace = null; switch (args.length) { case 3: replace = args[2]; case 2: regexp = args[1]; } StringBuffer sb = new StringBuffer(); String del = ""; Pattern expr = Pattern.compile(regexp); for (Iterator e = dot.getResources().keySet().iterator(); e.hasNext();) { String path = e.next(); if (!fullPathName) { int n = path.lastIndexOf('/'); if (n >= 0) { path = path.substring(n + 1); } } Matcher m = expr.matcher(path); if (m.matches()) { if (replace != null) path = m.replaceAll(replace); sb.append(del); sb.append(path); del = ", "; } } return sb.toString(); } public void putAll(Map additional, boolean force) { for (Iterator> i = additional.entrySet().iterator(); i.hasNext();) { Map.Entry entry = i.next(); if (force || getProperties().get(entry.getKey()) == null) setProperty((String) entry.getKey(), (String) entry.getValue()); } } boolean firstUse = true; public List getClasspath() { if (firstUse) { firstUse = false; String cp = getProperty(CLASSPATH); if (cp != null) for (String s : split(cp)) { Jar jar = getJarFromName(s, "getting classpath"); if (jar != null) addClasspath(jar); else warning("Cannot find entry on -classpath: %s", s); } } return classpath; } public void addClasspath(Jar jar) { if (isPedantic() && jar.getResources().isEmpty()) warning("There is an empty jar or directory on the classpath: " + jar.getName()); classpath.add(jar); } public void addClasspath(File cp) throws IOException { if (!cp.exists()) warning("File on classpath that does not exist: " + cp); Jar jar = new Jar(cp); addClose(jar); classpath.add(jar); } public void clear() { classpath.clear(); } public Jar getTarget() { return dot; } protected Map analyzeBundleClasspath(Jar dot, Map> bundleClasspath, Map> contained, Map> referred, Map> uses) throws Exception { Map classSpace = new HashMap(); Set hide = Create.set(); boolean containsDirectory = false; for (String path : bundleClasspath.keySet()) { if (dot.getDirectories().containsKey(path)) { containsDirectory = true; break; } } if (bundleClasspath.isEmpty()) { analyzeJar(dot, "", classSpace, contained, referred, uses, hide, true); } else { for (String path : bundleClasspath.keySet()) { Map info = bundleClasspath.get(path); if (path.equals(".")) { analyzeJar(dot, "", classSpace, contained, referred, uses, hide, !containsDirectory); continue; } // // There are 3 cases: // - embedded JAR file // - directory // - error // Resource resource = dot.getResource(path); if (resource != null) { try { Jar jar = new Jar(path); addClose(jar); EmbeddedResource.build(jar, resource); analyzeJar(jar, "", classSpace, contained, referred, uses, hide, true); } catch (Exception e) { warning("Invalid bundle classpath entry: " + path + " " + e); } } else { if (dot.getDirectories().containsKey(path)) { // if directories are used, we should not have dot as we // would have the classes in these directories on the // class // path twice. if (bundleClasspath.containsKey(".")) warning("Bundle-ClassPath uses a directory '%s' as well as '.', this implies the directory is seen \n" + "twice by the class loader. bnd assumes that the classes are only " + "loaded from '%s'. It is better to unroll the directory to create a flat bundle.", path, path); analyzeJar(dot, Processor.appendPath(path) + "/", classSpace, contained, referred, uses, hide, true); } else { if (!"optional".equals(info.get(RESOLUTION_DIRECTIVE))) warning("No sub JAR or directory " + path); } } } for (Clazz c : classSpace.values()) { formats.add(c.getFormat()); } } return classSpace; } /** * We traverse through all the classes that we can find and calculate the * contained and referred set and uses. This method ignores the Bundle * classpath. * * @param jar * @param contained * @param referred * @param uses * @throws IOException */ private void analyzeJar(Jar jar, String prefix, Map classSpace, Map> contained, Map> referred, Map> uses, Set hide, boolean reportWrongPath) throws Exception { next: for (String path : jar.getResources().keySet()) { if (path.startsWith(prefix) /* && !hide.contains(path) */) { hide.add(path); String relativePath = path.substring(prefix.length()); // // TODO this check (and the whole hide) is likely redundant // // it only protects against repeated checks for non-class // // bundle resources, but should not affect results otherwise. // if (!hide.add(relativePath)) { // continue; // } // Check if we'd already had this one. // Notice that we're flattening the space because // this is what class loaders do. if (classSpace.containsKey(relativePath)) continue; String pack = getPackage(relativePath); if (pack != null && !contained.containsKey(pack)) { // For each package we encounter for the first // time if (!isMetaData(relativePath)) { Map info = newMap(); contained.put(pack, info); Resource pinfo = jar.getResource(prefix + pack.replace('.', '/') + "/packageinfo"); if (pinfo != null) { InputStream in = pinfo.openInputStream(); String version; try { version = parsePackageInfo(in); } finally { in.close(); } if (version != null) info.put(VERSION_ATTRIBUTE, version); } } } // Check class resources, we need to analyze them if (path.endsWith(".class")) { Resource resource = jar.getResource(path); Clazz clazz; try { InputStream in = resource.openInputStream(); clazz = new Clazz(relativePath, resource); try { // Check if we have a package-info if (relativePath.endsWith("/package-info.class")) { // package-info can contain an Export annotation Map info = contained.get(pack); parsePackageInfoClass(clazz, info); } else { // Otherwise we just parse it simply clazz.parseClassFile(); } } finally { in.close(); } } catch (Throwable e) { error("Invalid class file: " + relativePath, e); e.printStackTrace(); continue next; } String calculatedPath = clazz.getClassName() + ".class"; if (!calculatedPath.equals(relativePath)) { if (!isNoBundle() && reportWrongPath) { error("Class in different directory than declared. Path from class name is " + calculatedPath + " but the path in the jar is " + relativePath + " from '" + jar + "'"); } } classSpace.put(relativePath, clazz); // Look at the referred packages // and copy them to our baseline for (String p : clazz.getReferred()) { Map attrs = referred.get(p); if (attrs == null) { attrs = newMap(); referred.put(p, attrs); } } // Add all the used packages // to this package Set t = uses.get(pack); if (t == null) uses.put(pack, t = new LinkedHashSet()); t.addAll(clazz.getReferred()); t.remove(pack); } } } } static Pattern OBJECT_REFERENCE = Pattern.compile("L([^/]+/)*([^;]+);"); private void parsePackageInfoClass(final Clazz clazz, final Map info) throws Exception { clazz.parseClassFileWithCollector(new ClassDataCollector() { @Override public void annotation(Annotation a) { if (a.name.equals(Clazz.toDescriptor(aQute.bnd.annotation.Version.class))) { // Check version String version = a.get("value"); if (!info.containsKey(Constants.VERSION_ATTRIBUTE)) { if (version != null) { version = getReplacer().process(version); if (Verifier.VERSION.matcher(version).matches()) info.put(VERSION_ATTRIBUTE, version); else error("Export annotatio in %s has invalid version info: %s", clazz, version); } } else { // Verify this matches with packageinfo String presentVersion = info.get(VERSION_ATTRIBUTE); try { Version av = new Version(presentVersion); Version bv = new Version(version); if (!av.equals(bv)) { error("Version from annotation for %s differs with packageinfo or Manifest", Clazz.getPackage(clazz.className)); } } catch (Exception e) { // Ignore } } } else if (a.name.equals(Clazz.toDescriptor(Export.class))) { // Check mandatory attributes Map attrs = doAttrbutes((Object[]) a.get(Export.MANDATORY), clazz, getReplacer()); if (!attrs.isEmpty()) { info.putAll(attrs); info.put(MANDATORY_DIRECTIVE, Processor.join(attrs.keySet())); } // Check optional attributes attrs = doAttrbutes((Object[]) a.get(Export.OPTIONAL), clazz, getReplacer()); if (!attrs.isEmpty()) { info.putAll(attrs); } // Check Included classes Object[] included = a.get(Export.INCLUDE); if (included != null && included.length > 0) { StringBuilder sb = new StringBuilder(); String del = ""; for (Object i : included) { Matcher m = OBJECT_REFERENCE.matcher((String) i); if (m.matches()) { sb.append(del); sb.append(m.group(2)); del = ","; } } info.put(INCLUDE_DIRECTIVE, sb.toString()); } // Check Excluded classes Object[] excluded = a.get(Export.EXCLUDE); if (excluded != null && excluded.length > 0) { StringBuilder sb = new StringBuilder(); String del = ""; for (Object i : excluded) { Matcher m = OBJECT_REFERENCE.matcher((String) i); if (m.matches()) { sb.append(del); sb.append(m.group(2)); del = ","; } } info.put(EXCLUDE_DIRECTIVE, sb.toString()); } // Check Uses Object[] uses = a.get(Export.USES); if (uses != null && uses.length > 0) { String old = info.get(USES_DIRECTIVE); if (old == null) old = ""; StringBuilder sb = new StringBuilder(old); String del = sb.length() == 0 ? "" : ","; for (Object use : uses) { sb.append(del); sb.append(use); del = ","; } info.put(USES_DIRECTIVE, sb.toString()); } } } }); } /** * Clean up version parameters. Other builders use more fuzzy definitions of * the version syntax. This method cleans up such a version to match an OSGi * version. * * @param VERSION_STRING * @return */ static Pattern fuzzyVersion = Pattern .compile( "(\\d+)(\\.(\\d+)(\\.(\\d+))?)?([^a-zA-Z0-9](.*))?", Pattern.DOTALL); static Pattern fuzzyVersionRange = Pattern .compile( "(\\(|\\[)\\s*([-\\da-zA-Z.]+)\\s*,\\s*([-\\da-zA-Z.]+)\\s*(\\]|\\))", Pattern.DOTALL); static Pattern fuzzyModifier = Pattern.compile("(\\d+[.-])*(.*)", Pattern.DOTALL); static Pattern nummeric = Pattern.compile("\\d*"); static public String cleanupVersion(String version) { Matcher m = Verifier.VERSIONRANGE.matcher(version); if (m.matches()) { return version; } m = fuzzyVersionRange.matcher(version); if (m.matches()) { String prefix = m.group(1); String first = m.group(2); String last = m.group(3); String suffix = m.group(4); return prefix + cleanupVersion(first) + "," + cleanupVersion(last) + suffix; } else { m = fuzzyVersion.matcher(version); if (m.matches()) { StringBuffer result = new StringBuffer(); String major = removeLeadingZeroes(m.group(1)); String minor = removeLeadingZeroes(m.group(3)); String micro = removeLeadingZeroes(m.group(5)); String qualifier = m.group(7); if (major != null) { result.append(major); if (minor != null) { result.append("."); result.append(minor); if (micro != null) { result.append("."); result.append(micro); if (qualifier != null) { result.append("."); cleanupModifier(result, qualifier); } } else if (qualifier != null) { result.append(".0."); cleanupModifier(result, qualifier); } } else if (qualifier != null) { result.append(".0.0."); cleanupModifier(result, qualifier); } return result.toString(); } } } return version; } private static String removeLeadingZeroes(String group) { int n = 0; while (group != null && n < group.length() - 1 && group.charAt(n) == '0') n++; if (n == 0) return group; return group.substring(n); } static void cleanupModifier(StringBuffer result, String modifier) { Matcher m = fuzzyModifier.matcher(modifier); if (m.matches()) modifier = m.group(2); for (int i = 0; i < modifier.length(); i++) { char c = modifier.charAt(i); if ((c >= '0' && c <= '9') || (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '_' || c == '-') result.append(c); } } /** * Decide if the package is a metadata package. * * @param pack * @return */ boolean isMetaData(String pack) { for (int i = 0; i < METAPACKAGES.length; i++) { if (pack.startsWith(METAPACKAGES[i])) return true; } return false; } public String getPackage(String clazz) { int n = clazz.lastIndexOf('/'); if (n < 0) return "."; return clazz.substring(0, n).replace('/', '.'); } // // We accept more than correct OSGi versions because in a later // phase we actually cleanup maven versions. But it is a bit yucky // static String parsePackageInfo(InputStream jar) throws IOException { try { Properties p = new Properties(); p.load(jar); jar.close(); if (p.containsKey("version")) { return p.getProperty("version"); } } catch (Exception e) { e.printStackTrace(); } return null; } final static String DEFAULT_PROVIDER_POLICY = "${range;[==,=+)}"; final static String DEFAULT_CONSUMER_POLICY = "${range;[==,+)}"; @SuppressWarnings("deprecation") public String getVersionPolicy(boolean implemented) { if (implemented) { String s = getProperty(PROVIDER_POLICY); if (s != null) return s; s = getProperty(VERSIONPOLICY_IMPL); if (s != null) return s; return getProperty(VERSIONPOLICY, DEFAULT_PROVIDER_POLICY); } else { String s = getProperty(CONSUMER_POLICY); if (s != null) return s; s = getProperty(VERSIONPOLICY_USES); if (s != null) return s; return getProperty(VERSIONPOLICY, DEFAULT_CONSUMER_POLICY); } // String vp = implemented ? getProperty(VERSIONPOLICY_IMPL) : // getProperty(VERSIONPOLICY_USES); // // if (vp != null) // return vp; // // if (implemented) // return getProperty(VERSIONPOLICY_IMPL, "{$range;[==,=+}"); // else // return getProperty(VERSIONPOLICY, "${range;[==,+)}"); } /** * The extends macro traverses all classes and returns a list of class names * that extend a base class. */ static String _classesHelp = "${classes;'implementing'|'extending'|'importing'|'named'|'version'|'any';}, Return a list of class fully qualified class names that extend/implement/import any of the contained classes matching the pattern\n"; public String _classes(String... args) throws Exception { // Macro.verifyCommand(args, _classesHelp, new // Pattern[]{null,Pattern.compile("(implementing|implements|extending|extends|importing|imports|any)"), // null}, 3,3); Collection matched = getClasses(args); if (matched.isEmpty()) return ""; return join(matched); } public Collection getClasses(String... args) throws Exception { Set matched = new HashSet(classspace.values()); for (int i = 1; i < args.length; i++) { if (args.length < i + 1) throw new IllegalArgumentException( "${classes} macro must have odd number of arguments. " + _classesHelp); String typeName = args[i]; if (typeName.equalsIgnoreCase("extending")) typeName = "extends"; else if (typeName.equalsIgnoreCase("importing")) typeName = "imports"; else if (typeName.equalsIgnoreCase("implementing")) typeName = "implements"; Clazz.QUERY type = Clazz.QUERY.valueOf(typeName.toUpperCase()); if (type == null) throw new IllegalArgumentException("${classes} has invalid type: " + typeName + ". " + _classesHelp); Instruction instr = null; if (Clazz.HAS_ARGUMENT.contains(type)) { StringBuilder sb = new StringBuilder(); String s = args[++i]; if (type == QUERY.ANNOTATION) { // Annotations use the descriptor format ... // But at least they're always an object sb.append("L"); for (int ci = 0; ci < s.length(); ci++) { char c = s.charAt(ci); if (c == '.') sb.append("/"); else sb.append(c); } sb.append(';'); } else { // The argument is declared as a dotted name but the classes // use a slashed named. So convert the name before we make // it a instruction. We also have to take into account // that some classes are nested and use $ for separator for (int ci = 0; ci < s.length(); ci++) { char c = s.charAt(ci); if (c == '.') sb.append("(/|\\$)"); else sb.append(c); } } instr = Instruction.getPattern(sb.toString()); } for (Iterator c = matched.iterator(); c.hasNext();) { Clazz clazz = c.next(); if (!clazz.is(type, instr, this)) { c.remove(); } } } return matched; } /** * Get the exporter of a package ... */ public String _exporters(String args[]) throws Exception { Macro.verifyCommand( args, "${exporters;}, returns the list of jars that export the given package", null, 2, 2); StringBuilder sb = new StringBuilder(); String del = ""; String pack = args[1].replace('.', '/'); for (Jar jar : classpath) { if (jar.getDirectories().containsKey(pack)) { sb.append(del); sb.append(jar.getName()); } } return sb.toString(); } public Map getClassspace() { return classspace; } /** * Locate a resource on the class path. * * @param path * Path of the reosurce * @return A resource or null */ public Resource findResource(String path) { for (Jar entry : getClasspath()) { Resource r = entry.getResource(path); if (r != null) return r; } return null; } /** * Find a clazz on the class path. This class has been parsed. * * @param path * @return */ public Clazz findClass(String path) throws Exception { Clazz c = classspace.get(path); if (c != null) return c; c = importedClassesCache.get(path); if (c != null) return c; Resource r = findResource(path); if (r != null) { c = new Clazz(path, r); c.parseClassFile(); importedClassesCache.put(path, c); } return c; } /** * Answer the bundle version. * * @return */ public String getVersion() { String version = getProperty(BUNDLE_VERSION); if (version == null) version = "0.0.0"; return version; } public boolean isNoBundle() { return isTrue(getProperty(RESOURCEONLY)) || isTrue(getProperty(NOMANIFEST)); } public void referTo(String impl) { String pack = Clazz.getPackage(impl); if (!referred.containsKey(pack)) referred.put(pack, new LinkedHashMap()); } /** * Calculate the groups inside the bundle. A group consists of packages that * have a reference to each other. */ public MultiMap, String> getGroups() { MultiMap map = new MultiMap(); Set keys = uses.keySet(); for (Map.Entry> entry : uses.entrySet()) { Set newSet = new HashSet(entry.getValue()); newSet.retainAll(keys); map.put(entry.getKey(), newSet); } // Calculate strongly connected packages Set> scc = Tarjan.tarjan(map); MultiMap, String> grouped = new MultiMap, String>(); for (Set group : scc) { for (String p : group) { grouped.addAll(group, uses.get(p)); } } return grouped; } /** * Ensure that we are running on the correct bnd. */ void doRequireBnd() { Map require = OSGiHeader.parseProperties(getProperty(REQUIRE_BND)); if (require == null || require.isEmpty()) return; Hashtable map = new Hashtable(); map.put(Constants.VERSION_FILTER, getBndVersion()); for (String filter : require.keySet()) { try { Filter f = new Filter(filter); if (f.match(map)) continue; error("%s fails %s", REQUIRE_BND, require.get(filter)); } catch (Exception t) { error("%s with value %s throws exception", t, REQUIRE_BND, require); } } } /** * md5 macro */ static String _md5Help = "${md5;path}"; public String _md5(String args[]) throws Exception { Macro.verifyCommand(args, _md5Help, new Pattern[] { null, null, Pattern.compile("base64|hex") }, 2, 3); Digester digester = MD5.getDigester(); Resource r = dot.getResource(args[1]); if (r == null) throw new FileNotFoundException("From " + digester + ", not found " + args[1]); IO.copy(r.openInputStream(), digester); boolean hex = args.length > 2 && args[2].equals("hex"); if (hex) return Hex.toHexString(digester.digest().digest()); else return Base64.encodeBase64(digester.digest().digest()); } /** * SHA1 macro */ static String _sha1Help = "${sha1;path}"; public String _sha1(String args[]) throws Exception { Macro.verifyCommand(args, _sha1Help, new Pattern[] { null, null, Pattern.compile("base64|hex") }, 2, 3); Digester digester = SHA1.getDigester(); Resource r = dot.getResource(args[1]); if (r == null) throw new FileNotFoundException("From sha1, not found " + args[1]); IO.copy(r.openInputStream(), digester); return Base64.encodeBase64(digester.digest().digest()); } } bnd-1.50.0/biz.aQute.bndlib/src/aQute/lib/osgi/Instruction.java0000755000175000017500000000713411656076535024116 0ustar drazzibdrazzibpackage aQute.lib.osgi; import java.util.*; import java.util.regex.*; import aQute.libg.generics.*; public class Instruction { Pattern pattern; String instruction; boolean negated; boolean optional; public Instruction(String instruction, boolean negated) { this.instruction = instruction; this.negated = negated; } public boolean matches(String value) { return getMatcher(value).matches(); } public boolean isNegated() { return negated; } public String getPattern() { return instruction; } /** * Convert a string based pattern to a regular expression based pattern. * This is called an instruction, this object makes it easier to handle the * different cases * * @param string * @return */ public static Instruction getPattern(String string) { boolean negated = false; if (string.startsWith("!")) { negated = true; string = string.substring(1); } StringBuffer sb = new StringBuffer(); for (int c = 0; c < string.length(); c++) { switch (string.charAt(c)) { case '.': sb.append("\\."); break; case '*': sb.append(".*"); break; case '?': sb.append(".?"); break; default: sb.append(string.charAt(c)); break; } } string = sb.toString(); if (string.endsWith("\\..*")) { sb.append("|"); sb.append(string.substring(0, string.length() - 4)); } return new Instruction(sb.toString(), negated); } public String toString() { return getPattern(); } public Matcher getMatcher(String value) { if (pattern == null) { pattern = Pattern.compile(instruction); } return pattern.matcher(value); } public int hashCode() { return instruction.hashCode(); } public boolean equals(Object other) { return other != null && (other instanceof Instruction) && instruction.equals(((Instruction) other).instruction); } public void setOptional() { optional = true; } public boolean isOptional() { return optional; } public static Map> replaceWithInstruction( Map> header) { Map> map = Processor.newMap(); for (Iterator>> e = header .entrySet().iterator(); e.hasNext();) { Map.Entry> entry = e.next(); String pattern = entry.getKey(); Instruction instr = getPattern(pattern); String presence = entry.getValue() .get(Constants.PRESENCE_DIRECTIVE); if ("optional".equals(presence)) instr.setOptional(); map.put(instr, entry.getValue()); } return map; } public static Collection select(Collection matchers, Collection targets) { Collection result = Create.list(); outer: for (T t : targets) { String s = t.toString(); for (Instruction i : matchers) { if (i.matches(s)) { if (!i.isNegated()) result.add(t); continue outer; } } } return result; } } bnd-1.50.0/biz.aQute.bndlib/src/aQute/lib/osgi/Processor.java0000755000175000017500000010627211656076535023557 0ustar drazzibdrazzibpackage aQute.lib.osgi; import java.io.*; import java.net.*; import java.util.*; import java.util.concurrent.*; import java.util.jar.*; import java.util.regex.*; import aQute.bnd.service.*; import aQute.lib.io.*; import aQute.libg.generics.*; import aQute.libg.header.*; import aQute.libg.reporter.*; public class Processor implements Reporter, Registry, Constants, Closeable { static ThreadLocal current = new ThreadLocal(); static ExecutorService executor = Executors.newCachedThreadPool(); static Random random = new Random(); // TODO handle include files out of date // TODO make splitter skip eagerly whitespace so trim is not necessary public static String LIST_SPLITTER = "\\s*,\\s*"; final List errors = new ArrayList(); final List warnings = new ArrayList(); final Set basicPlugins = new HashSet(); final Set toBeClosed = new HashSet(); Set plugins; boolean pedantic; boolean trace; boolean exceptions; boolean fileMustExist = true; private File base = new File("").getAbsoluteFile(); Properties properties; private Macro replacer; private long lastModified; private File propertiesFile; private boolean fixup = true; long modified; Processor parent; Set included; CL pluginLoader; Collection filter; HashSet missingCommand; public Processor() { properties = new Properties(); } public Processor(Properties parent) { properties = new Properties(parent); } public Processor(Processor parent) { this(parent.properties); this.parent = parent; } public void setParent(Processor processor) { this.parent = processor; Properties ext = new Properties(processor.properties); ext.putAll(this.properties); this.properties = ext; } public Processor getParent() { return parent; } public Processor getTop() { if (parent == null) return this; else return parent.getTop(); } public void getInfo(Processor processor, String prefix) { if (isFailOk()) addAll(warnings, processor.getErrors(), prefix); else addAll(errors, processor.getErrors(), prefix); addAll(warnings, processor.getWarnings(), prefix); processor.errors.clear(); processor.warnings.clear(); } public void getInfo(Processor processor) { getInfo(processor, ""); } private void addAll(List to, List from, String prefix) { for (T x : from) { to.add(prefix + x); } } /** * A processor can mark itself current for a thread. * * @return */ private Processor current() { Processor p = current.get(); if (p == null) return this; else return p; } public void warning(String string, Object... args) { Processor p = current(); String s = formatArrays(string, args); if (!p.warnings.contains(s)) p.warnings.add(s); p.signal(); } public void error(String string, Object... args) { Processor p = current(); if (p.isFailOk()) p.warning(string, args); else { String s = formatArrays(string, args); if (!p.errors.contains(s)) p.errors.add(s); } p.signal(); } public void error(String string, Throwable t, Object... args) { Processor p = current(); if (p.isFailOk()) p.warning(string + ": " + t, args); else { p.errors.add("Exception: " + t.getMessage()); String s = formatArrays(string, args); if (!p.errors.contains(s)) p.errors.add(s); } if (p.exceptions) t.printStackTrace(); p.signal(); } public void signal() { } public List getWarnings() { return warnings; } public List getErrors() { return errors; } public Map> parseHeader(String value) { return parseHeader(value, this); } /** * Standard OSGi header parser. * * @param value * @return */ static public Map> parseHeader(String value, Processor logger) { return OSGiHeader.parseHeader(value, logger); } Map> getClauses(String header) { return parseHeader(getProperty(header)); } public void addClose(Closeable jar) { toBeClosed.add(jar); } /** * Remove all entries from a map that start with a specific prefix * * @param * @param source * @param prefix * @return */ static Map removeKeys(Map source, String prefix) { Map temp = new TreeMap(source); for (Iterator p = temp.keySet().iterator(); p.hasNext();) { String pack = (String) p.next(); if (pack.startsWith(prefix)) p.remove(); } return temp; } public void progress(String s, Object... args) { trace(s, args); } public boolean isPedantic() { return current().pedantic; } public void setPedantic(boolean pedantic) { this.pedantic = pedantic; } public static File getFile(File base, String file) { return IO.getFile(base, file); } public File getFile(String file) { return getFile(base, file); } /** * Return a list of plugins that implement the given class. * * @param clazz * Each returned plugin implements this class/interface * @return A list of plugins */ public List getPlugins(Class clazz) { List l = new ArrayList(); Set all = getPlugins(); for (Object plugin : all) { if (clazz.isInstance(plugin)) l.add(clazz.cast(plugin)); } return l; } /** * Returns the first plugin it can find of the given type. * * @param * @param clazz * @return */ public T getPlugin(Class clazz) { Set all = getPlugins(); for (Object plugin : all) { if (clazz.isInstance(plugin)) return clazz.cast(plugin); } return null; } /** * Return a list of plugins. Plugins are defined with the -plugin command. * They are class names, optionally associated with attributes. Plugins can * implement the Plugin interface to see these attributes. * * Any object can be a plugin. * * @return */ protected synchronized Set getPlugins() { if (this.plugins != null) return this.plugins; missingCommand = new HashSet(); Set list = new LinkedHashSet(); // The owner of the plugin is always in there. list.add(this); setTypeSpecificPlugins(list); if (parent != null) list.addAll(parent.getPlugins()); // We only use plugins now when they are defined on our level // and not if it is in our parent. We inherit from our parent // through the previous block. if (properties.containsKey(PLUGIN)) { String spe = getProperty(PLUGIN); if (spe.equals(NONE)) return new LinkedHashSet(); loadPlugins(list, spe); } return this.plugins = list; } /** * @param list * @param spe */ protected void loadPlugins(Set list, String spe) { Map> plugins = parseHeader(spe); for (Map.Entry> entry : plugins.entrySet()) { String key = (String) entry.getKey(); try { CL loader = getLoader(); String path = entry.getValue().get(PATH_DIRECTIVE); if (path != null) { String parts[] = path.split("\\s*,\\s*"); for (String p : parts) { File f = getFile(p).getAbsoluteFile(); loader.add(f.toURI().toURL()); } } trace("Using plugin %s", key); // Plugins could use the same class with different // parameters so we could have duplicate names Remove // the ! added by the parser to make each name unique. key = removeDuplicateMarker(key); try { Class c = (Class) loader.loadClass(key); Object plugin = c.newInstance(); customize(plugin, entry.getValue()); list.add(plugin); } catch (Throwable t) { // We can defer the error if the plugin specifies // a command name. In that case, we'll verify that // a bnd file does not contain any references to a // plugin // command. The reason this feature was added was // to compile plugin classes with the same build. String commands = entry.getValue().get(COMMAND_DIRECTIVE); if (commands == null) error("Problem loading the plugin: %s exception: (%s)", key, t); else { Collection cs = split(commands); missingCommand.addAll(cs); } } } catch (Throwable e) { error("Problem loading the plugin: " + key + " exception: " + e); } } } protected void setTypeSpecificPlugins(Set list) { list.add(executor); list.add(random); list.addAll(basicPlugins); } /** * @param plugin * @param entry */ protected T customize(T plugin, Map map) { if (plugin instanceof Plugin) { if (map != null) ((Plugin) plugin).setProperties(map); ((Plugin) plugin).setReporter(this); } if (plugin instanceof RegistryPlugin) { ((RegistryPlugin) plugin).setRegistry(this); } return plugin; } public boolean isFailOk() { String v = getProperty(Analyzer.FAIL_OK, null); return v != null && v.equalsIgnoreCase("true"); } public File getBase() { return base; } public void setBase(File base) { this.base = base; } public void clear() { errors.clear(); warnings.clear(); } public void trace(String msg, Object... parms) { Processor p = current(); if (p.trace) { System.out.printf("# " + msg + "\n", parms); } } public List newList() { return new ArrayList(); } public Set newSet() { return new TreeSet(); } public static Map newMap() { return new LinkedHashMap(); } public static Map newHashMap() { return new HashMap(); } public List newList(Collection t) { return new ArrayList(t); } public Set newSet(Collection t) { return new TreeSet(t); } public Map newMap(Map t) { return new LinkedHashMap(t); } public void close() { for (Closeable c : toBeClosed) { try { c.close(); } catch (IOException e) { // Who cares? } } toBeClosed.clear(); } public String _basedir(String args[]) { if (base == null) throw new IllegalArgumentException("No base dir set"); return base.getAbsolutePath(); } /** * Property handling ... * * @return */ public Properties getProperties() { if (fixup) { fixup = false; begin(); } return properties; } public String getProperty(String key) { return getProperty(key, null); } public void mergeProperties(File file, boolean override) { if (file.isFile()) { try { Properties properties = loadProperties(file); mergeProperties(properties, override); } catch (Exception e) { error("Error loading properties file: " + file); } } else { if (!file.exists()) error("Properties file does not exist: " + file); else error("Properties file must a file, not a directory: " + file); } } public void mergeProperties(Properties properties, boolean override) { for (Enumeration e = properties.propertyNames(); e.hasMoreElements();) { String key = (String) e.nextElement(); String value = properties.getProperty(key); if (override || !getProperties().containsKey(key)) setProperty(key, value); } } public void setProperties(Properties properties) { doIncludes(getBase(), properties); this.properties.putAll(properties); } public void addProperties(File file) throws Exception { addIncluded(file); Properties p = loadProperties(file); setProperties(p); } public synchronized void addIncluded(File file) { if (included == null) included = new HashSet(); included.add(file); } /** * Inspect the properties and if you find -includes parse the line included * manifest files or properties files. The files are relative from the given * base, this is normally the base for the analyzer. * * @param ubase * @param p * @param done * @throws IOException * @throws IOException */ private void doIncludes(File ubase, Properties p) { String includes = p.getProperty(INCLUDE); if (includes != null) { includes = getReplacer().process(includes); p.remove(INCLUDE); Collection clauses = parseHeader(includes).keySet(); for (String value : clauses) { boolean fileMustExist = true; boolean overwrite = true; while (true) { if (value.startsWith("-")) { fileMustExist = false; value = value.substring(1).trim(); } else if (value.startsWith("~")) { // Overwrite properties! overwrite = false; value = value.substring(1).trim(); } else break; } try { File file = getFile(ubase, value).getAbsoluteFile(); if (!file.isFile() && fileMustExist) { error("Included file " + file + (file.exists() ? " does not exist" : " is directory")); } else doIncludeFile(file, overwrite, p); } catch (Exception e) { if (fileMustExist) error("Error in processing included file: " + value, e); } } } } /** * @param file * @param parent * @param done * @param overwrite * @throws FileNotFoundException * @throws IOException */ public void doIncludeFile(File file, boolean overwrite, Properties target) throws Exception { if (included != null && included.contains(file)) { error("Cyclic or multiple include of " + file); } else { addIncluded(file); updateModified(file.lastModified(), file.toString()); InputStream in = new FileInputStream(file); Properties sub; if (file.getName().toLowerCase().endsWith(".mf")) { sub = getManifestAsProperties(in); } else sub = loadProperties(in, file.getAbsolutePath()); in.close(); doIncludes(file.getParentFile(), sub); // make sure we do not override properties for (Map.Entry entry : sub.entrySet()) { if (overwrite || !target.containsKey(entry.getKey())) target.setProperty((String) entry.getKey(), (String) entry.getValue()); } } } public void unsetProperty(String string) { getProperties().remove(string); } public boolean refresh() { plugins = null; // We always refresh our plugins if (propertiesFile == null) return false; boolean changed = updateModified(propertiesFile.lastModified(), "properties file"); if (included != null) { for (File file : included) { if (changed) break; changed |= !file.exists() || updateModified(file.lastModified(), "include file: " + file); } } if (changed) { forceRefresh(); return true; } return false; } /** * */ public void forceRefresh() { included = null; properties.clear(); setProperties(propertiesFile, base); propertiesChanged(); } public void propertiesChanged() { } /** * Set the properties by file. Setting the properties this way will also set * the base for this analyzer. After reading the properties, this will call * setProperties(Properties) which will handle the includes. * * @param propertiesFile * @throws FileNotFoundException * @throws IOException */ public void setProperties(File propertiesFile) throws IOException { propertiesFile = propertiesFile.getAbsoluteFile(); setProperties(propertiesFile, propertiesFile.getParentFile()); } public void setProperties(File propertiesFile, File base) { this.propertiesFile = propertiesFile.getAbsoluteFile(); setBase(base); try { if (propertiesFile.isFile()) { // System.out.println("Loading properties " + propertiesFile); long modified = propertiesFile.lastModified(); if (modified > System.currentTimeMillis() + 100) { System.out.println("Huh? This is in the future " + propertiesFile); this.modified = System.currentTimeMillis(); } else this.modified = modified; included = null; Properties p = loadProperties(propertiesFile); setProperties(p); } else { if (fileMustExist) { error("No such properties file: " + propertiesFile); } } } catch (IOException e) { error("Could not load properties " + propertiesFile); } } protected void begin() { if (isTrue(getProperty(PEDANTIC))) setPedantic(true); } public static boolean isTrue(String value) { if (value == null) return false; return !"false".equalsIgnoreCase(value); } /** * Get a property with a proper default * * @param headerName * @param deflt * @return */ public String getProperty(String key, String deflt) { String value = null; Processor source = this; if (filter != null && filter.contains(key)) { value = (String) getProperties().get(key); } else { while (source != null) { value = (String) source.getProperties().get(key); if (value != null) break; source = source.getParent(); } } if (value != null) return getReplacer().process(value, source); else if (deflt != null) return getReplacer().process(deflt, this); else return null; } /** * Helper to load a properties file from disk. * * @param file * @return * @throws IOException */ public Properties loadProperties(File file) throws IOException { updateModified(file.lastModified(), "Properties file: " + file); InputStream in = new FileInputStream(file); Properties p = loadProperties(in, file.getAbsolutePath()); in.close(); return p; } Properties loadProperties(InputStream in, String name) throws IOException { int n = name.lastIndexOf('/'); if (n > 0) name = name.substring(0, n); if (name.length() == 0) name = "."; try { Properties p = new Properties(); p.load(in); return replaceAll(p, "\\$\\{\\.\\}", name); } catch (Exception e) { error("Error during loading properties file: " + name + ", error:" + e); return new Properties(); } } /** * Replace a string in all the values of the map. This can be used to * preassign variables that change. I.e. the base directory ${.} for a * loaded properties */ public static Properties replaceAll(Properties p, String pattern, String replacement) { Properties result = new Properties(); for (Iterator> i = p.entrySet().iterator(); i.hasNext();) { Map.Entry entry = i.next(); String key = (String) entry.getKey(); String value = (String) entry.getValue(); value = value.replaceAll(pattern, replacement); result.put(key, value); } return result; } /** * Merge the attributes of two maps, where the first map can contain * wildcarded names. The idea is that the first map contains patterns (for * example *) with a set of attributes. These patterns are matched against * the found packages in actual. If they match, the result is set with the * merged set of attributes. It is expected that the instructions are * ordered so that the instructor can define which pattern matches first. * Attributes in the instructions override any attributes from the actual.
* * A pattern is a modified regexp so it looks like globbing. The * becomes a * .* just like the ? becomes a .?. '.' are replaced with \\. Additionally, * if the pattern starts with an exclamation mark, it will remove that * matches for that pattern (- the !) from the working set. So the following * patterns should work: *
    *
  • com.foo.bar
  • *
  • com.foo.*
  • *
  • com.foo.???
  • *
  • com.*.[^b][^a][^r]
  • *
  • !com.foo.* (throws away any match for com.foo.*)
  • *
* Enough rope to hang the average developer I would say. * * * @param instructions * the instructions with patterns. A * @param actual * the actual found packages */ public static Map> merge(String type, Map> instructions, Map> actual, Set superfluous, Map> ignored) { Map> toVisit = new HashMap>(actual); // we // do // not // want // to // ruin // our // original Map> result = newMap(); for (Iterator i = instructions.keySet().iterator(); i.hasNext();) { String instruction = i.next(); String originalInstruction = instruction; Map instructedAttributes = instructions.get(instruction); // Check if we have a fixed (starts with '=') or a // duplicate name. A fixed name is added to the output without // checking against the contents. Duplicates are marked // at the end. In that case we do not pick up any contained // information but just add them to the output including the // marker. if (instruction.startsWith("=")) { result.put(instruction.substring(1), instructedAttributes); superfluous.remove(originalInstruction); continue; } if (isDuplicate(instruction)) { result.put(instruction, instructedAttributes); superfluous.remove(originalInstruction); continue; } Instruction instr = Instruction.getPattern(instruction); for (Iterator p = toVisit.keySet().iterator(); p.hasNext();) { String packageName = p.next(); if (instr.matches(packageName)) { superfluous.remove(originalInstruction); if (!instr.isNegated()) { Map newAttributes = new HashMap(); newAttributes.putAll(actual.get(packageName)); newAttributes.putAll(instructedAttributes); result.put(packageName, newAttributes); } else if (ignored != null) { ignored.put(packageName, new HashMap()); } p.remove(); // Can never match again for another pattern } } } return result; } /** * Print a standard Map based OSGi header. * * @param exports * map { name => Map { attribute|directive => value } } * @return the clauses */ public static String printClauses(Map> exports) { return printClauses(exports, false); } public static String printClauses(Map> exports, boolean checkMultipleVersions) { StringBuffer sb = new StringBuffer(); String del = ""; for (Iterator i = exports.keySet().iterator(); i.hasNext();) { String name = i.next(); Map clause = exports.get(name); // We allow names to be duplicated in the input // by ending them with '~'. This is necessary to use // the package names as keys. However, we remove these // suffixes in the output so that you can set multiple // exports with different attributes. String outname = removeDuplicateMarker(name); sb.append(del); sb.append(outname); printClause(clause, sb); del = ","; } return sb.toString(); } public static void printClause(Map map, StringBuffer sb) { for (Iterator j = map.keySet().iterator(); j.hasNext();) { String key = j.next(); // Skip directives we do not recognize if (key.equals(NO_IMPORT_DIRECTIVE) || key.equals(PROVIDE_DIRECTIVE) || key.equals(SPLIT_PACKAGE_DIRECTIVE) || key.equals(FROM_DIRECTIVE)) continue; String value = ((String) map.get(key)).trim(); sb.append(";"); sb.append(key); sb.append("="); boolean clean = (value.length() >= 2 && value.charAt(0) == '"' && value.charAt(value .length() - 1) == '"') || Verifier.TOKEN.matcher(value).matches(); if (!clean) sb.append("\""); sb.append(value); if (!clean) sb.append("\""); } } public Macro getReplacer() { if (replacer == null) return replacer = new Macro(this, getMacroDomains()); else return replacer; } /** * This should be overridden by subclasses to add extra macro command * domains on the search list. * * @return */ protected Object[] getMacroDomains() { return new Object[] {}; } /** * Return the properties but expand all macros. This always returns a new * Properties object that can be used in any way. * * @return */ public Properties getFlattenedProperties() { return getReplacer().getFlattenedProperties(); } public boolean updateModified(long time, String reason) { if (time > lastModified) { lastModified = time; return true; } return false; } public long lastModified() { return lastModified; } /** * Add or override a new property. * * @param key * @param value */ public void setProperty(String key, String value) { checkheader: for (int i = 0; i < headers.length; i++) { if (headers[i].equalsIgnoreCase(value)) { value = headers[i]; break checkheader; } } getProperties().put(key, value); } /** * Read a manifest but return a properties object. * * @param in * @return * @throws IOException */ public static Properties getManifestAsProperties(InputStream in) throws IOException { Properties p = new Properties(); Manifest manifest = new Manifest(in); for (Iterator it = manifest.getMainAttributes().keySet().iterator(); it.hasNext();) { Attributes.Name key = (Attributes.Name) it.next(); String value = manifest.getMainAttributes().getValue(key); p.put(key.toString(), value); } return p; } public File getPropertiesFile() { return propertiesFile; } public void setFileMustExist(boolean mustexist) { fileMustExist = mustexist; } static public String read(InputStream in) throws Exception { InputStreamReader ir = new InputStreamReader(in, "UTF8"); StringBuilder sb = new StringBuilder(); try { char chars[] = new char[1000]; int size = ir.read(chars); while (size > 0) { sb.append(chars, 0, size); size = ir.read(chars); } } finally { ir.close(); } return sb.toString(); } /** * Join a list. * * @param args * @return */ public static String join(Collection list, String delimeter) { return join(delimeter, list); } public static String join(String delimeter, Collection... list) { StringBuilder sb = new StringBuilder(); String del = ""; for (Collection l : list) { if (list != null) { for (Object item : l) { sb.append(del); sb.append(item); del = delimeter; } } } return sb.toString(); } public static String join(Object[] list, String delimeter) { if (list == null) return ""; StringBuilder sb = new StringBuilder(); String del = ""; for (Object item : list) { sb.append(del); sb.append(item); del = delimeter; } return sb.toString(); } public static String join(Collection... list) { return join(",", list); } public static String join(T list[]) { return join(list, ","); } public static void split(String s, Collection set) { String elements[] = s.trim().split(LIST_SPLITTER); for (String element : elements) { if (element.length() > 0) set.add(element); } } public static Collection split(String s) { return split(s, LIST_SPLITTER); } public static Collection split(String s, String splitter) { if (s != null) s = s.trim(); if (s == null || s.trim().length() == 0) return Collections.emptyList(); return Arrays.asList(s.split(splitter)); } public static String merge(String... strings) { ArrayList result = new ArrayList(); for (String s : strings) { if (s != null) split(s, result); } return join(result); } public boolean isExceptions() { return exceptions; } public void setExceptions(boolean exceptions) { this.exceptions = exceptions; } /** * Make the file short if it is inside our base directory, otherwise long. * * @param f * @return */ public String normalize(String f) { if (f.startsWith(base.getAbsolutePath() + "/")) return f.substring(base.getAbsolutePath().length() + 1); else return f; } public String normalize(File f) { return normalize(f.getAbsolutePath()); } public static String removeDuplicateMarker(String key) { int i = key.length() - 1; while (i >= 0 && key.charAt(i) == DUPLICATE_MARKER) --i; return key.substring(0, i + 1); } public static boolean isDuplicate(String name) { return name.length() > 0 && name.charAt(name.length() - 1) == DUPLICATE_MARKER; } public void setTrace(boolean x) { trace = x; } static class CL extends URLClassLoader { CL() { super(new URL[0], Processor.class.getClassLoader()); } void add(URL url) { URL urls[] = getURLs(); for (URL u : urls) { if (u.equals(url)) return; } super.addURL(url); } public Class loadClass(String name) throws NoClassDefFoundError { try { Class c = super.loadClass(name); return c; } catch (Throwable t) { StringBuilder sb = new StringBuilder(); sb.append(name); sb.append(" not found, parent: "); sb.append(getParent()); sb.append(" urls:"); sb.append(Arrays.toString(getURLs())); sb.append(" exception:"); sb.append(t); throw new NoClassDefFoundError(sb.toString()); } } } private CL getLoader() { if (pluginLoader == null) { pluginLoader = new CL(); } return pluginLoader; } /* * Check if this is a valid project. */ public boolean exists() { return base != null && base.isDirectory() && propertiesFile != null && propertiesFile.isFile(); } public boolean isOk() { return isFailOk() || (getErrors().size() == 0); } public boolean isPerfect() { return getErrors().size() == 0 && getWarnings().size() == 0; } public void setForceLocal(Collection local) { filter = local; } /** * Answer if the name is a missing plugin's command name. If a bnd file * contains the command name of a plugin, and that plugin is not available, * then an error is reported during manifest calculation. This allows the * plugin to fail to load when it is not needed. * * We first get the plugins to ensure it is properly initialized. * * @param name * @return */ public boolean isMissingPlugin(String name) { getPlugins(); return missingCommand != null && missingCommand.contains(name); } /** * Append two strings to for a path in a ZIP or JAR file. It is guaranteed * to return a string that does not start, nor ends with a '/', while it is * properly separated with slashes. Double slashes are properly removed. * *
	 *  "/" + "abc/def/" becomes "abc/def"
	 *  
	 * @param prefix
	 * @param suffix
	 * @return
	 * 
	 */
	public static String appendPath(String... parts) {
		StringBuilder sb = new StringBuilder();
		boolean lastSlash = true;
		for (String part : parts) {
			for (int i = 0; i < part.length(); i++) {
				char c = part.charAt(i);
				if (c == '/') {
					if (!lastSlash)
						sb.append('/');
					lastSlash = true;
				} else {
					sb.append(c);
					lastSlash = false;
				}
			}
			if (!lastSlash & sb.length() > 0) {
				sb.append('/');
				lastSlash = true;
			}
		}
		if (lastSlash && sb.length() > 0)
			sb.deleteCharAt(sb.length() - 1);

		return sb.toString();
	}

	/**
	 * Parse the a=b strings and return a map of them.
	 * 
	 * @param attrs
	 * @param clazz
	 * @return
	 */
	public static Map doAttrbutes(Object[] attrs, Clazz clazz, Macro macro) {
		if (attrs == null || attrs.length == 0)
			return Collections.emptyMap();

		Map map = newMap();
		for (Object a : attrs) {
			String attr = (String) a;
			int n = attr.indexOf("=");
			if (n > 0) {
				map.put(attr.substring(0, n), macro.process(attr.substring(n + 1)));
			} else
				throw new IllegalArgumentException(formatArrays(
						"Invalid attribute on package-info.java in %s , %s. Must be = ",
						clazz, attr));
		}
		return map;
	}

	/**
	 * This method is the same as String.format but it makes sure that any
	 * arrays are transformed to strings.
	 * 
	 * @param string
	 * @param parms
	 * @return
	 */
	public static String formatArrays(String string, Object... parms) {
		Object[] parms2 = parms;
		Object[] output = new Object[parms.length];
		for (int i = 0; i < parms.length; i++) {
			output[i] = makePrintable(parms[i]);
		}
		return String.format(string, parms2);
	}

	/**
	 * Check if the object is an array and turn it into a string if it is,
	 * otherwise unchanged.
	 * 
	 * @param object
	 *            the object to make printable
	 * @return a string if it was an array or the original object
	 */
	public static Object makePrintable(Object object) {
		if (object == null)
			return object;

		if (object.getClass().isArray()) {
			Object[] array = (Object[]) object;
			Object[] output = new Object[array.length];
			for (int i = 0; i < array.length; i++) {
				output[i] = makePrintable(array[i]);
			}
			return Arrays.toString(output);
		}
		return object;
	}

	public static String append(String... strings) {
		List result = Create.list();
		for (String s : strings) {
			result.addAll(split(s));
		}
		return join(result);
	}

	public synchronized Class getClass(String type, File jar) throws Exception {
		CL cl = getLoader();
		cl.add(jar.toURI().toURL());
		return cl.loadClass(type);
	}

	public boolean isTrace() {
		return current().trace;
	}

	public static long getDuration(String tm, long dflt) {
		if (tm == null)
			return dflt;

		tm = tm.toUpperCase();
		TimeUnit unit = TimeUnit.MILLISECONDS;
		Matcher m = Pattern
				.compile(
						"\\s*(\\d+)\\s*(NANOSECONDS|MICROSECONDS|MILLISECONDS|SECONDS|MINUTES|HOURS|DAYS)?")
				.matcher(tm);
		if (m.matches()) {
			long duration = Long.parseLong(tm);
			String u = m.group(2);
			if (u != null)
				unit = TimeUnit.valueOf(u);
			duration = TimeUnit.MILLISECONDS.convert(duration, unit);
			return duration;
		}
		return dflt;
	}

	/**
	 * Generate a random string, which is guaranteed to be a valid Java
	 * identifier (first character is an ASCII letter, subsequent characters are
	 * ASCII letters or numbers). Takes an optional parameter for the length of
	 * string to generate; default is 8 characters.
	 */
	public String _random(String[] args) {
		int numchars = 8;
		if (args.length > 1) {
			try {
				numchars = Integer.parseInt(args[1]);
			} catch (NumberFormatException e) {
				throw new IllegalArgumentException(
						"Invalid character count parameter in ${random} macro.");
			}
		}

		if (random == null)
			random = new Random();

		char[] letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ".toCharArray();
		char[] alphanums = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
				.toCharArray();

		char[] array = new char[numchars];
		for (int i = 0; i < numchars; i++) {
			char c;
			if (i == 0)
				c = letters[random.nextInt(letters.length)];
			else
				c = alphanums[random.nextInt(alphanums.length)];
			array[i] = c;
		}

		return new String(array);
	}

	/**
	 * Set the current command thread. This must be balanced with the
	 * {@link #end(Processor)} method. The method returns the previous command
	 * owner or null.
	 * 
	 * The command owner will receive all warnings and error reports.
	 */

	protected Processor beginHandleErrors(String message) {
		trace("begin %s", message);
		Processor previous = current.get();
		current.set(this);
		return previous;
	}

	/**
	 * End a command. Will restore the previous command owner.
	 * 
	 * @param previous
	 */
	protected void endHandleErrors(Processor previous) {
		trace("end");
		current.set(previous);
	}

	public static Executor getExecutor() {
		return executor;
	}

	/**
	 * These plugins are added to the total list of plugins. The separation is
	 * necessary because the list of plugins is refreshed now and then so we
	 * need to be able to add them at any moment in time.
	 * 
	 * @param plugin
	 */
	public synchronized void addBasicPlugin(Object plugin) {
		basicPlugins.add(plugin);
		if (plugins != null)
			plugins.add(plugin);
	}

	public synchronized void removeBasicPlugin(Object plugin) {
		basicPlugins.remove(plugin);
		if (plugins != null)
			plugins.remove(plugin);
	}
}
bnd-1.50.0/biz.aQute.bndlib/src/aQute/lib/osgi/bnd.info0000644000175000017500000000006211656076535022340 0ustar  drazzibdrazzibmodified=${currenttime}
version=${Bundle-Version}
bnd-1.50.0/biz.aQute.bndlib/src/aQute/lib/osgi/ClassDataCollector.java0000644000175000017500000000432411656076535025276 0ustar  drazzibdrazzibpackage aQute.lib.osgi;

public class ClassDataCollector {
    public void classBegin(int access, String name) {
    }

    public boolean classStart(int access, String name) {
        classBegin(access,name);
        return true;
    }

    public void extendsClass(String name) {
    }

    public void implementsInterfaces(String name[]) {
    }

    public void addReference(String token) {
    }

    public void annotation(Annotation annotation) {
    }

    public void parameter(int p) {
    }

    public void method(Clazz.MethodDef defined) {
        if (defined.isConstructor())
            constructor(defined.access, defined.descriptor);
        else
            method(defined.access, defined.name, defined.descriptor);
    }

    public void field(Clazz.FieldDef defined) {
        field(defined.access, defined.name, defined.descriptor);
    }

    public void reference(Clazz.MethodDef referenced) {
    }

    public void reference(Clazz.FieldDef referenced) {
    }

    public void classEnd() {
    }

    @Deprecated // Will really be removed!
    public void field(int access, String name, String descriptor) {
    }

    @Deprecated // Will really be removed!
    public void constructor(int access, String descriptor) {
    }

    @Deprecated // Will really be removed!
    public void method(int access, String name, String descriptor) {
    }

    /**
     * The EnclosingMethod attribute
     * 
     * @param cName The name of the enclosing class, never null. Name is with slashes.
     * @param mName The name of the enclosing method in the class with cName or null
     * @param mDescriptor The descriptor of this type
     */
	public void enclosingMethod(String cName, String mName, String mDescriptor) {
		
	}

	/**
	 * The InnerClass attribute
	 * 
	 * @param innerClass The name of the inner class (with slashes). Can be null.
	 * @param outerClass The name of the outer class (with slashes) Can be null.
	 * @param innerName The name inside the outer class, can be null.
	 * @param modifiers The access flags 
	 */
	public void innerClass(String innerClass, String outerClass, String innerName,
			int innerClassAccessFlags) {		
	}

	public void signature(String signature) {
	}

	public void constant(Object object) {
	}

}
bnd-1.50.0/biz.aQute.bndlib/src/aQute/lib/osgi/eclipse/0000755000175000017500000000000011656076535022346 5ustar  drazzibdrazzibbnd-1.50.0/biz.aQute.bndlib/src/aQute/lib/osgi/eclipse/EclipseClasspath.java0000755000175000017500000002072511656076535026451 0ustar  drazzibdrazzibpackage aQute.lib.osgi.eclipse;

import java.io.*;
import java.util.*;
import java.util.regex.*;

import javax.xml.parsers.*;

import org.w3c.dom.*;
import org.xml.sax.*;

import aQute.libg.reporter.*;

/**
 * Parse the Eclipse project information for the classpath. Unfortunately, it is
 * impossible to read the variables. They are ignored but that can cause
 * problems.
 * 
 * @version $Revision: 1.2 $
 */
public class EclipseClasspath {
    static DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory
                                                                 .newInstance();
    DocumentBuilder               db;
    File                          project;
    File                          workspace;
    Set                     sources                = new LinkedHashSet();
    Set                     allSources                = new LinkedHashSet();
    
    Set                     classpath              = new LinkedHashSet();
    List                    dependents             = new ArrayList();
    File                          output;
    boolean                       recurse                = true;
    Set                     exports                = new LinkedHashSet();
    Map           properties             = new HashMap();
    Reporter                      reporter;
    int                           options;
    Set                     bootclasspath          = new LinkedHashSet();

    public final static int       DO_VARIABLES           = 1;

    /**
     * Parse an Eclipse project structure to discover the classpath.
     * 
     * @param workspace
     *            Points to workspace
     * @param project
     *            Points to project
     * @throws ParserConfigurationException
     * @throws SAXException
     * @throws IOException
     */

    public EclipseClasspath(Reporter reporter, File workspace, File project,
            int options) throws Exception {
        this.project = project.getCanonicalFile();
        this.workspace = workspace.getCanonicalFile();
        this.reporter = reporter;
        db = documentBuilderFactory.newDocumentBuilder();
        parse(this.project, true);
        db = null;
    }

    public EclipseClasspath(Reporter reporter, File workspace, File project)
            throws Exception {
        this(reporter, workspace, project, 0);
    }

    /**
     * Recursive routine to parse the files. If a sub project is detected, it is
     * parsed before the parsing continues. This should give the right order.
     * 
     * @param project
     *            Project directory
     * @param top
     *            If this is the top project
     * @throws ParserConfigurationException
     * @throws SAXException
     * @throws IOException
     */
    void parse(File project, boolean top) throws ParserConfigurationException,
            SAXException, IOException {
        File file = new File(project, ".classpath");
        if (!file.exists())
            throw new FileNotFoundException(".classpath file not found: "
                    + file.getAbsolutePath());

        Document doc = db.parse(file);
        NodeList nodelist = doc.getDocumentElement().getElementsByTagName(
                "classpathentry");

        if (nodelist == null)
            throw new IllegalArgumentException(
                    "Can not find classpathentry in classpath file");

        for (int i = 0; i < nodelist.getLength(); i++) {
            Node node = nodelist.item(i);
            NamedNodeMap attrs = node.getAttributes();
            String kind = get(attrs, "kind");
            if ("src".equals(kind)) {
                String path = get(attrs, "path");
                // TODO boolean exported = "true".equalsIgnoreCase(get(attrs,
                // "exported"));
                if (path.startsWith("/")) {
                    // We have another project
                    File subProject = getFile(workspace, project, path);
                    if (recurse)
                        parse(subProject, false);
                    dependents.add(subProject.getCanonicalFile());
                } else {
                    File src = getFile(workspace, project, path);
                    allSources.add(src);
                    if (top) {
                        // We only want the sources for our own project
                        // or we'll compile all at once. Not a good idea
                        // because project settings can differ.
                        sources.add(src);
                    }
                }
            } else if ("lib".equals(kind)) {
                String path = get(attrs, "path");
                boolean exported = "true".equalsIgnoreCase(get(attrs,
                        "exported"));
                if (top || exported) {
                    File jar = getFile(workspace, project, path);
                    if (jar.getName().startsWith("ee."))
                        bootclasspath.add(jar);
                    else
                        classpath.add(jar);
                    if (exported)
                        exports.add(jar);
                }
            } else if ("output".equals(kind)) {
                String path = get(attrs, "path");
                path = path.replace('/', File.separatorChar);
                output = getFile(workspace, project, path);
                classpath.add(output);
                exports.add(output);
            } else if ("var".equals(kind)) {
                boolean exported = "true".equalsIgnoreCase(get(attrs,
                        "exported"));
                File lib = replaceVar(get(attrs, "path"));
                File slib = replaceVar(get(attrs, "sourcepath"));
                if (lib != null) {
                    classpath.add(lib);
                    if (exported)
                        exports.add(lib);
                }
                if (slib != null)
                    sources.add(slib);
            } else if ("con".equals(kind)) {
                // Should do something useful ...
            }
        }
    }

    private File getFile(File abs, File relative, String opath) {
        String path = opath.replace('/', File.separatorChar);
        File result = new File(path);
        if (result.isAbsolute() && result.isFile()) {
            return result;
        }
        if (path.startsWith(File.separator)) {
            result = abs;
            path = path.substring(1);
        } else
            result = relative;

        StringTokenizer st = new StringTokenizer(path, File.separator);
        while (st.hasMoreTokens()) {
            String token = st.nextToken();
            result = new File(result, token);
        }

        if (!result.exists())
            System.err.println("File not found: project=" + project
                    + " workspace=" + workspace + " path=" + opath + " file="
                    + result);
        return result;
    }

    static Pattern PATH = Pattern.compile("([A-Z_]+)/(.*)");

    private File replaceVar(String path) {
        if ((options & DO_VARIABLES) == 0)
            return null;

        Matcher m = PATH.matcher(path);
        if (m.matches()) {
            String var = m.group(1);
            String remainder = m.group(2);
            String base = (String) properties.get(var);
            if (base != null) {
                File b = new File(base);
                File f = new File(b, remainder.replace('/', File.separatorChar));
                return f;
            } else
                reporter.error("Can't find replacement variable for: " + path);
        } else
            reporter.error("Cant split variable path: " + path);
        return null;
    }

    private String get(NamedNodeMap map, String name) {
        Node node = map.getNamedItem(name);
        if (node == null)
            return null;

        return node.getNodeValue();
    }

    public Set getClasspath() {
        return classpath;
    }

    public Set getSourcepath() {
        return sources;
    }

    public File getOutput() {
        return output;
    }

    public List getDependents() {
        return dependents;
    }

    public void setRecurse(boolean recurse) {
        this.recurse = recurse;
    }

    public Set getExports() {
        return exports;
    }

    public void setProperties(Map map) {
        this.properties = map;
    }

    public Set getBootclasspath() {
        return bootclasspath;
    }

    public Set getAllSources() {
        return allSources;
    }

}
bnd-1.50.0/biz.aQute.bndlib/src/aQute/lib/osgi/Macro.java0000755000175000017500000006021111656076535022631 0ustar  drazzibdrazzibpackage aQute.lib.osgi;

import java.io.*;
import java.lang.reflect.*;
import java.net.*;
import java.text.*;
import java.util.*;
import java.util.regex.*;

import aQute.lib.io.*;
import aQute.libg.sed.*;
import aQute.libg.version.*;

/**
 * Provide a macro processor. This processor can replace variables in strings
 * based on a properties and a domain. The domain can implement functions that
 * start with a "_" and take args[], the names of these functions are available
 * as functions in the macro processor (without the _). Macros can nest to any
 * depth but may not contain loops.
 * 
 * Add POSIX macros:
 * ${#parameter}
    String length.

${parameter%word}
    Remove smallest suffix pattern.

${parameter%%word}
    Remove largest suffix pattern.

${parameter#word}
    Remove smallest prefix pattern.

${parameter##word}
    Remove largest prefix pattern. 
 */
public class Macro implements Replacer {
	Processor	domain;
	Object		targets[];
	boolean		flattening;

	public Macro(Processor domain, Object... targets) {
		this.domain = domain;
		this.targets = targets;
		if (targets != null) {
			for (Object o : targets) {
				assert o != null;
			}
		}
	}

	public String process(String line, Processor source) {
		return process(line, new Link(source,null,line));
	}

	String process(String line, Link link) {
		StringBuffer sb = new StringBuffer();
		process(line, 0, '\u0000', '\u0000', sb, link);
		return sb.toString();
	}

	int process(CharSequence org, int index, char begin, char end, StringBuffer result, Link link) {
		StringBuilder line = new StringBuilder(org);
		int nesting = 1;

		StringBuffer variable = new StringBuffer();
		outer: while (index < line.length()) {
			char c1 = line.charAt(index++);
			if (c1 == end) {
				if (--nesting == 0) {
					result.append(replace(variable.toString(), link));
					return index;
				}
			} else if (c1 == begin)
				nesting++;
			else if (c1 == '\\' && index < line.length() - 1 && line.charAt(index) == '$') {
				// remove the escape backslash and interpret the dollar as a
				// literal
				index++;
				variable.append('$');
				continue outer;
			} else if (c1 == '$' && index < line.length() - 2) {
				char c2 = line.charAt(index);
				char terminator = getTerminator(c2);
				if (terminator != 0) {
					index = process(line, index + 1, c2, terminator, variable, link);
					continue outer;
				}
			}
			variable.append(c1);
		}
		result.append(variable);
		return index;
	}

	public static char getTerminator(char c) {
		switch (c) {
		case '(':
			return ')';
		case '[':
			return ']';
		case '{':
			return '}';
		case '<':
			return '>';
		case '\u00ab': // Guillemet double << >>
			return '\u00bb';
		case '\u2039': // Guillemet single
			return '\u203a';
		}
		return 0;
	}

	protected String replace(String key, Link link) {
		if (link != null && link.contains(key))
			return "${infinite:" + link.toString() + "}";

		if (key != null) {
			key = key.trim();
			if (key.length() > 0) {
				Processor source = domain;
				String value = null;
				while( source != null) {
					value = source.getProperties().getProperty(key);
					if ( value != null )
						break;
					
					source = source.getParent();
				}
				
				if (value != null)
					return process(value, new Link(source,link, key));

				value = doCommands(key, link);
				if (value != null)
					return process(value, new Link(source, link, key));

				if (key != null && key.trim().length() > 0) {
					value = System.getProperty(key);
					if (value != null)
						return value;
				}
				if (!flattening)
					domain.warning("No translation found for macro: " + key);
			} else {
				domain.warning("Found empty macro key");
			}
		} else {
			domain.warning("Found null macro key");
		}
		return "${" + key + "}";
	}

	/**
	 * Parse the key as a command. A command consist of parameters separated by
	 * ':'.
	 * 
	 * @param key
	 * @return
	 */
	static Pattern	commands	= Pattern.compile("(?= 0)
				args[i] = args[i].replaceAll("\\\\;", ";");

		
		if ( args[0].startsWith("^")) {
			String varname = args[0].substring(1).trim();
			
			Processor parent = source.start.getParent();
			if ( parent != null)
				return parent.getProperty(varname);
			else
				return null;
		}
		
		
		Processor rover = domain;
		while (rover != null) {
			String result = doCommand(rover, args[0], args);
			if (result != null)
				return result;

			rover = rover.getParent();
		}

		for (int i = 0; targets != null && i < targets.length; i++) {
			String result = doCommand(targets[i], args[0], args);
			if (result != null)
				return result;
		}

		return doCommand(this, args[0], args);
	}

	private String doCommand(Object target, String method, String[] args) {
		if (target == null)
			; // System.out.println("Huh? Target should never be null " +
		// domain);
		else {
			String cname = "_" + method.replaceAll("-", "_");
			try {
				Method m = target.getClass().getMethod(cname, new Class[] { String[].class });
				return (String) m.invoke(target, new Object[] { args });
			} catch (NoSuchMethodException e) {
				// Ignore
			} catch (InvocationTargetException e) {
				if ( e.getCause() instanceof IllegalArgumentException ) {
					domain.error("%s, for cmd: %s, arguments; %s", e.getMessage(), method, Arrays.toString(args));
				} else {
					domain.warning("Exception in replace: " + e.getCause());
					e.getCause().printStackTrace();
				}
			} catch (Exception e) {
				domain.warning("Exception in replace: " + e + " method=" + method);
				e.printStackTrace();
			}
		}
		return null;
	}

	/**
	 * Return a unique list where the duplicates are removed.
	 * 
	 * @param args
	 * @return
	 */
	static String	_uniqHelp	= "${uniq; ...}";

	public String _uniq(String args[]) {
		verifyCommand(args, _uniqHelp, null, 1, Integer.MAX_VALUE);
		Set set = new LinkedHashSet();
		for (int i = 1; i < args.length; i++) {
			Processor.split(args[i], set);
		}
		return Processor.join(set, ",");
	}

	public String _pathseparator(String args[]) {
		return File.pathSeparator;
	}

	public String _separator(String args[]) {
		return File.separator;
	}

	public String _filter(String args[]) {
		return filter(args, false);
	}

	public String _filterout(String args[]) {
		return filter(args, true);

	}

	static String	_filterHelp	= "${%s;;}";

	String filter(String[] args, boolean include) {
		verifyCommand(args, String.format(_filterHelp, args[0]), null, 3, 3);

		Collection list = new ArrayList(Processor.split(args[1]));
		Pattern pattern = Pattern.compile(args[2]);

		for (Iterator i = list.iterator(); i.hasNext();) {
			if (pattern.matcher(i.next()).matches() == include)
				i.remove();
		}
		return Processor.join(list);
	}

	static String	_sortHelp	= "${sort;...}";

	public String _sort(String args[]) {
		verifyCommand(args, _sortHelp, null, 2, Integer.MAX_VALUE);

		List result = new ArrayList();
		for (int i = 1; i < args.length; i++) {
			Processor.split(args[i], result);
		}
		Collections.sort(result);
		return Processor.join(result);
	}

	static String	_joinHelp	= "${join;...}";

	public String _join(String args[]) {

		verifyCommand(args, _joinHelp, null, 1, Integer.MAX_VALUE);

		List result = new ArrayList();
		for (int i = 1; i < args.length; i++) {
			Processor.split(args[i], result);
		}
		return Processor.join(result);
	}

	static String	_ifHelp	= "${if;; [;] }";

	public String _if(String args[]) {
		verifyCommand(args, _ifHelp, null, 3, 4);
		String condition = args[1].trim();
		if (condition.length() != 0)
			return args[2];
		if (args.length > 3)
			return args[3];
		else
			return "";
	}

	public String _now(String args[]) {
		return new Date().toString();
	}

	public static String	_fmodifiedHelp	= "${fmodified;...}, return latest modification date";

	public String _fmodified(String args[]) throws Exception {
		verifyCommand(args, _fmodifiedHelp, null, 2, Integer.MAX_VALUE);

		long time = 0;
		Collection names = new ArrayList();
		for (int i = 1; i < args.length; i++) {
			Processor.split(args[i], names);
		}
		for (String name : names) {
			File f = new File(name);
			if (f.exists() && f.lastModified() > time)
				time = f.lastModified();
		}
		return "" + time;
	}

	public String _long2date(String args[]) {
		try {
			return new Date(Long.parseLong(args[1])).toString();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "not a valid long";
	}

	public String _literal(String args[]) {
		if (args.length != 2)
			throw new RuntimeException("Need a value for the ${literal;} macro");
		return "${" + args[1] + "}";
	}

	public String _def(String args[]) {
		if (args.length != 2)
			throw new RuntimeException("Need a value for the ${def;} macro");

		return domain.getProperty(args[1], "");
	}

	/**
	 * 
	 * replace ;  ; regex ; replace
	 * 
	 * @param args
	 * @return
	 */
	public String _replace(String args[]) {
		if (args.length != 4) {
			domain.warning("Invalid nr of arguments to replace " + Arrays.asList(args));
			return null;
		}

		String list[] = args[1].split("\\s*,\\s*");
		StringBuffer sb = new StringBuffer();
		String del = "";
		for (int i = 0; i < list.length; i++) {
			String element = list[i].trim();
			if (!element.equals("")) {
				sb.append(del);
				sb.append(element.replaceAll(args[2], args[3]));
				del = ", ";
			}
		}

		return sb.toString();
	}

	public String _warning(String args[]) {
		for (int i = 1; i < args.length; i++) {
			domain.warning(process(args[i]));
		}
		return "";
	}

	public String _error(String args[]) {
		for (int i = 1; i < args.length; i++) {
			domain.error(process(args[i]));
		}
		return "";
	}

	/**
	 * toclassname ; .class ( , .class ) *
	 * 
	 * @param args
	 * @return
	 */
	static String	_toclassnameHelp	= "${classname;}, convert class paths to FQN class names ";

	public String _toclassname(String args[]) {
		verifyCommand(args, _toclassnameHelp, null, 2, 2);
		Collection paths = Processor.split(args[1]);

		List names = new ArrayList(paths.size());
		for (String path : paths) {
			if (path.endsWith(".class")) {
				String name = path.substring(0, path.length() - 6).replace('/', '.');
				names.add(name);
			} else if (path.endsWith(".java")) {
				String name = path.substring(0, path.length() - 5).replace('/', '.');
				names.add(name);
			} else {
				domain.warning("in toclassname, " + args[1]
						+ " is not a class path because it does not end in .class");
			}
		}
		return Processor.join(names, ",");
	}

	/**
	 * toclassname ; .class ( , .class ) *
	 * 
	 * @param args
	 * @return
	 */

	static String	_toclasspathHelp	= "${toclasspath;[;boolean]}, convert a list of class names to paths";

	public String _toclasspath(String args[]) {
		verifyCommand(args, _toclasspathHelp, null, 2, 3);
		boolean cl = true;
		if (args.length > 2)
			cl = new Boolean(args[2]);

		Collection names = Processor.split(args[1]);
		Collection paths = new ArrayList(names.size());
		for (String name : names) {
			String path = name.replace('.', '/') + (cl ? ".class" : "");
			paths.add(path);
		}
		return Processor.join(paths, ",");
	}

	public String _dir(String args[]) {
		if (args.length < 2) {
			domain.warning("Need at least one file name for ${dir;...}");
			return null;
		} else {
			String del = "";
			StringBuffer sb = new StringBuffer();
			for (int i = 1; i < args.length; i++) {
				File f = domain.getFile(args[i]);
				if (f.exists() && f.getParentFile().exists()) {
					sb.append(del);
					sb.append(f.getParentFile().getAbsolutePath());
					del = ",";
				}
			}
			return sb.toString();
		}

	}

	public String _basename(String args[]) {
		if (args.length < 2) {
			domain.warning("Need at least one file name for ${basename;...}");
			return null;
		} else {
			String del = "";
			StringBuffer sb = new StringBuffer();
			for (int i = 1; i < args.length; i++) {
				File f = domain.getFile(args[i]);
				if (f.exists() && f.getParentFile().exists()) {
					sb.append(del);
					sb.append(f.getName());
					del = ",";
				}
			}
			return sb.toString();
		}

	}

	public String _isfile(String args[]) {
		if (args.length < 2) {
			domain.warning("Need at least one file name for ${isfile;...}");
			return null;
		} else {
			boolean isfile = true;
			for (int i = 1; i < args.length; i++) {
				File f = new File(args[i]).getAbsoluteFile();
				isfile &= f.isFile();
			}
			return isfile ? "true" : "false";
		}

	}

	public String _isdir(String args[]) {
		if (args.length < 2) {
			domain.warning("Need at least one file name for ${isdir;...}");
			return null;
		} else {
			boolean isdir = true;
			for (int i = 1; i < args.length; i++) {
				File f = new File(args[i]).getAbsoluteFile();
				isdir &= f.isDirectory();
			}
			return isdir ? "true" : "false";
		}

	}

	public String _tstamp(String args[]) {
		String format = "yyyyMMddHHmm";
		long now = System.currentTimeMillis();

		if (args.length > 1) {
			format = args[1];
			if (args.length > 2) {
				now = Long.parseLong(args[2]);
				if (args.length > 3) {
					domain.warning("Too many arguments for tstamp: " + Arrays.toString(args));
				}
			}
		}
		SimpleDateFormat sdf = new SimpleDateFormat(format);
		return sdf.format(new Date(now));
	}

	/**
	 * Wildcard a directory. The lists can contain Instruction that are matched
	 * against the given directory
	 * 
	 * ${lsr;;(;)*} ${lsa;;(;)*}
	 * 
	 * @author aqute
	 * 
	 */

	public String _lsr(String args[]) {
		return ls(args, true);
	}

	public String _lsa(String args[]) {
		return ls(args, false);
	}

	String ls(String args[], boolean relative) {
		if (args.length < 2)
			throw new IllegalArgumentException(
					"the ${ls} macro must at least have a directory as parameter");

		File dir = domain.getFile(args[1]);
		if (!dir.isAbsolute())
			throw new IllegalArgumentException(
					"the ${ls} macro directory parameter is not absolute: " + dir);

		if (!dir.exists())
			throw new IllegalArgumentException(
					"the ${ls} macro directory parameter does not exist: " + dir);

		if (!dir.isDirectory())
			throw new IllegalArgumentException(
					"the ${ls} macro directory parameter points to a file instead of a directory: "
							+ dir);

		String[] files = dir.list();
		List result;

		if (args.length < 3) {
			result = Arrays.asList(files);
		} else
			result = new ArrayList();

		for (int i = 2; i < args.length; i++) {
			String parts[] = args[i].split("\\s*,\\s*");
			for (String pattern : parts) {
				// So make it in to an instruction
				Instruction instr = Instruction.getPattern(pattern);

				// For each project, match it against the instruction
				for (int f = 0; f < files.length; f++) {
					if (files[f] != null) {
						if (instr.matches(files[f])) {
							if (!instr.isNegated()) {
								if (relative)
									result.add(files[f]);
								else
									result.add(new File(dir, files[f]).getAbsolutePath());
							}
							files[f] = null;
						}
					}
				}
			}
		}
		return Processor.join(result, ",");
	}

	public String _currenttime(String args[]) {
		return Long.toString(System.currentTimeMillis());
	}

	/**
	 * Modify a version to set a version policy. Thed policy is a mask that is
	 * mapped to a version.
	 * 
	 * 
	 * +           increment
	 * -           decrement
	 * =           maintain
	 * ˜           discard
	 * 
	 * ==+      = maintain major, minor, increment micro, discard qualifier
	 * ˜˜˜=     = just get the qualifier
	 * version="[${version;==;${@}},${version;=+;${@}})"
	 * 
* * * * * @param args * @return */ final static String MASK_STRING = "[\\-+=~0123456789]{0,3}[=~]?"; final static Pattern MASK = Pattern.compile(MASK_STRING); final static String _versionHelp = "${version;;}, modify a version\n" + " ::= [ M [ M [ M [ MQ ]]]\n" + "M ::= '+' | '-' | MQ\n" + "MQ ::= '~' | '='"; final static Pattern _versionPattern[] = new Pattern[] { null, null, MASK, Verifier.VERSION }; public String _version(String args[]) { verifyCommand(args, _versionHelp, null, 2, 3); String mask = args[1]; Version version = null; if (args.length >= 3) version = new Version(args[2]); return version(version, mask); } String version(Version version, String mask) { if (version == null) { String v = domain.getProperty("@"); if (v == null) { domain .error( "No version specified for ${version} or ${range} and no implicit version ${@} either, mask=%s", mask); v = "0"; } version = new Version(v); } StringBuilder sb = new StringBuilder(); String del = ""; for (int i = 0; i < mask.length(); i++) { char c = mask.charAt(i); String result = null; if (c != '~') { if (i == 3) { result = version.getQualifier(); } else if (Character.isDigit(c)) { // Handle masks like +00, =+0 result = String.valueOf(c); } else { int x = version.get(i); switch (c) { case '+': x++; break; case '-': x--; break; case '=': break; } result = Integer.toString(x); } if (result != null) { sb.append(del); del = "."; sb.append(result); } } } return sb.toString(); } /** * Schortcut for version policy * *
	 * -provide-policy : ${policy;[==,=+)}
	 * -consume-policy : ${policy;[==,+)}
	 * 
* * @param args * @return */ static Pattern RANGE_MASK = Pattern.compile("(\\[|\\()(" + MASK_STRING + "),(" + MASK_STRING +")(\\]|\\))"); static String _rangeHelp = "${range;[;]}, range for version, if version not specified lookyp ${@}\n" + " ::= [ M [ M [ M [ MQ ]]]\n" + "M ::= '+' | '-' | MQ\n" + "MQ ::= '~' | '='"; static Pattern _rangePattern[] = new Pattern[] { null, RANGE_MASK }; public String _range(String args[]) { verifyCommand(args, _rangeHelp, _rangePattern, 2, 3); Version version = null; if (args.length >= 3) version = new Version(args[2]); String spec = args[1]; Matcher m = RANGE_MASK.matcher(spec); m.matches(); String floor = m.group(1); String floorMask = m.group(2); String ceilingMask = m.group(3); String ceiling = m.group(4); StringBuilder sb = new StringBuilder(); sb.append(floor); sb.append(version(version, floorMask)); sb.append(","); sb.append(version(version, ceilingMask)); sb.append(ceiling); String s = sb.toString(); VersionRange vr = new VersionRange(s); if (!(vr.includes(vr.getHigh()) || vr.includes(vr.getLow()))) { domain.error("${range} macro created an invalid range %s from %s and mask %s", s, version, spec); } return sb.toString(); } /** * System command. Execute a command and insert the result. * * @param args * @param help * @param patterns * @param low * @param high */ public String system_internal(boolean allowFail, String args[]) throws Exception { verifyCommand(args, "${" + (allowFail ? "system-allow-fail" : "system") + ";[;]}, execute a system command", null, 2, 3); String command = args[1]; String input = null; if (args.length > 2) { input = args[2]; } Process process = Runtime.getRuntime().exec(command, null, domain.getBase()); if (input != null) { process.getOutputStream().write(input.getBytes("UTF-8")); } process.getOutputStream().close(); String s = IO.collect(process.getInputStream(), "UTF-8"); int exitValue = process.waitFor(); if (!allowFail && (exitValue != 0)) { domain.error("System command " + command + " failed with " + exitValue); } return s.trim(); } public String _system(String args[]) throws Exception { return system_internal(false, args); } public String _system_allow_fail(String args[]) throws Exception { String result = ""; try { result = system_internal(true, args); } catch (Throwable t) { /* ignore */ } return result; } public String _env(String args[]) { verifyCommand(args, "${env;}, get the environmet variable", null, 2, 2); try { return System.getenv(args[1]); } catch (Throwable t) { return null; } } /** * Get the contents of a file. * * @param in * @return * @throws IOException */ public String _cat(String args[]) throws IOException { verifyCommand(args, "${cat;}, get the content of a file", null, 2, 2); File f = domain.getFile(args[1]); if (f.isFile()) { return IO.collect(f); } else if (f.isDirectory()) { return Arrays.toString(f.list()); } else { try { URL url = new URL(args[1]); return IO.collect(url, "UTF-8"); } catch (MalformedURLException mfue) { // Ignore here } return null; } } public static void verifyCommand(String args[], String help, Pattern[] patterns, int low, int high) { String message = ""; if (args.length > high) { message = "too many arguments"; } else if (args.length < low) { message = "too few arguments"; } else { for (int i = 0; patterns != null && i < patterns.length && i < args.length; i++) { if (patterns[i] != null) { Matcher m = patterns[i].matcher(args[i]); if (!m.matches()) message += String.format("Argument %s (%s) does not match %s\n", i, args[i], patterns[i].pattern()); } } } if (message.length() != 0) { StringBuilder sb = new StringBuilder(); String del = "${"; for (String arg : args) { sb.append(del); sb.append(arg); del = ";"; } sb.append("}, is not understood. "); sb.append(message); throw new IllegalArgumentException(sb.toString()); } } // Helper class to track expansion of variables // on the stack. static class Link { Link previous; String key; Processor start; public Link(Processor start, Link previous, String key) { this.previous = previous; this.key = key; this.start = start; } public boolean contains(String key) { if (this.key.equals(key)) return true; if (previous == null) return false; return previous.contains(key); } public String toString() { StringBuffer sb = new StringBuffer(); String del = "["; for (Link r = this; r != null; r = r.previous) { sb.append(del); sb.append(r.key); del = ","; } sb.append("]"); return sb.toString(); } } /** * Take all the properties and translate them to actual values. This method * takes the set properties and traverse them over all entries, including * the default properties for that properties. The values no longer contain * macros. * * @return A new Properties with the flattened values */ public Properties getFlattenedProperties() { // Some macros only work in a lower processor, so we // do not report unknown macros while flattening flattening = true; try { Properties flattened = new Properties(); Properties source = domain.getProperties(); for (Enumeration e = source.propertyNames(); e.hasMoreElements();) { String key = (String) e.nextElement(); if (!key.startsWith("_")) if (key.startsWith("-")) flattened.put(key, source.getProperty(key)); else flattened.put(key, process(source.getProperty(key))); } return flattened; } finally { flattening = false; } }; public static String _fileHelp = "${file;;...}, create correct OS dependent path"; public String _osfile(String args[]) { verifyCommand(args, _fileHelp, null, 3, 3); File base = new File(args[1]); File f = Processor.getFile(base, args[2]); return f.getAbsolutePath(); } public String _path(String args[]) { List list = new ArrayList(); for (int i = 1; i < args.length; i++) { list.addAll(Processor.split(args[i])); } return Processor.join(list, File.pathSeparator); } public static Properties getParent(Properties p) { try { Field f = Properties.class.getDeclaredField("defaults"); f.setAccessible(true); return (Properties) f.get(p); } catch (Exception e) { Field[] fields = Properties.class.getFields(); System.out.println(Arrays.toString(fields)); return null; } } public String process(String line) { return process(line,domain); } } bnd-1.50.0/biz.aQute.bndlib/src/aQute/lib/osgi/URLResource.java0000755000175000017500000000113011656076535023735 0ustar drazzibdrazzibpackage aQute.lib.osgi; import java.io.*; import java.net.*; public class URLResource implements Resource { URL url; String extra; public URLResource(URL url) { this.url = url; } public InputStream openInputStream() throws IOException { return url.openStream(); } public String toString() { return ":" + url.getPath() + ":"; } public void write(OutputStream out) throws Exception { FileResource.copy(this, out); } public long lastModified() { return -1; } public String getExtra() { return extra; } public void setExtra(String extra) { this.extra = extra; } } bnd-1.50.0/biz.aQute.bndlib/src/aQute/lib/osgi/Annotation.java0000644000175000017500000000327411656076535023705 0ustar drazzibdrazzibpackage aQute.lib.osgi; import java.lang.annotation.*; import java.util.*; import aQute.bnd.annotation.metatype.*; public class Annotation { String name; Map elements; ElementType member; RetentionPolicy policy; public Annotation(String name, Map elements, ElementType member, RetentionPolicy policy) { this.name = name; if ( elements == null) this.elements = Collections.emptyMap(); else this.elements = elements; this.member = member; this.policy = policy; } public String getName() { return name; } public ElementType getElementType() { return member; } public RetentionPolicy getRetentionPolicy() { return policy; } public String toString() { return name + ":" + member + ":" + policy + ":" + elements; } @SuppressWarnings("unchecked") public T get(String string) { if (elements == null) return null; return (T) elements.get(string); } public void put(String string, Object v) { if (elements == null) return; elements.put(string, v); } public Set keySet() { if (elements == null) return Collections.emptySet(); return elements.keySet(); } @SuppressWarnings("unchecked") public T getAnnotation() throws Exception { String cname = Clazz.objectDescriptorToFQN(name); Class c = (Class) getClass().getClassLoader().loadClass(cname); return getAnnotation(c); } public T getAnnotation(Class c) throws Exception { String cname = Clazz.objectDescriptorToFQN(name); if ( ! c.getName().equals(cname)) return null; return Configurable.createConfigurable(c, elements ); } } bnd-1.50.0/biz.aQute.bndlib/src/aQute/lib/osgi/AbstractResource.java0000644000175000017500000000221411656076535025037 0ustar drazzibdrazzibpackage aQute.lib.osgi; import java.io.*; public abstract class AbstractResource implements Resource { String extra; byte[] calculated; long lastModified; protected AbstractResource(long modified) { lastModified = modified; } public String getExtra() { return extra; } public long lastModified() { return lastModified; } public InputStream openInputStream() throws IOException { return new ByteArrayInputStream(getLocalBytes()); } private byte[] getLocalBytes() throws IOException { try { if (calculated != null) return calculated; return calculated = getBytes(); } catch (IOException e) { throw e; } catch (Exception e) { IOException ee = new IOException("Opening resource"); ee.initCause(e); throw ee; } } public void setExtra(String extra) { this.extra = extra; } public void write(OutputStream out) throws IOException { out.write(getLocalBytes()); } abstract protected byte[] getBytes() throws Exception; } bnd-1.50.0/biz.aQute.bndlib/src/aQute/lib/osgi/Verifier.java0000755000175000017500000011640511656076535023352 0ustar drazzibdrazzibpackage aQute.lib.osgi; import java.util.*; import java.util.jar.*; import java.util.regex.*; import aQute.libg.qtokens.*; public class Verifier extends Analyzer { Jar dot; Manifest manifest; Map> referred = newHashMap(); Map> contained = newHashMap(); Map> uses = newHashMap(); Map> mimports; Map> mdynimports; Map> mexports; List bundleClasspath; Map> ignore = newHashMap(); // Packages // to // ignore Map classSpace; boolean r3; boolean usesRequire; boolean fragment; Attributes main; final static Pattern EENAME = Pattern .compile("CDC-1\\.0/Foundation-1\\.0" + "|CDC-1\\.1/Foundation-1\\.1" + "|OSGi/Minimum-1\\.[1-9]" + "|JRE-1\\.1" + "|J2SE-1\\.2" + "|J2SE-1\\.3" + "|J2SE-1\\.4" + "|J2SE-1\\.5" + "|JavaSE-1\\.6" + "|JavaSE-1\\.7" + "|PersonalJava-1\\.1" + "|PersonalJava-1\\.2" + "|CDC-1\\.0/PersonalBasis-1\\.0" + "|CDC-1\\.0/PersonalJava-1\\.0"); final static int V1_1 = 45; final static int V1_2 = 46; final static int V1_3 = 47; final static int V1_4 = 48; final static int V1_5 = 49; final static int V1_6 = 50; final static int V1_7 = 51; static class EE { String name; int target; EE(String name, int source, int target) { this.name = name; this.target = target; } } final static EE[] ees = { new EE("CDC-1.0/Foundation-1.0", V1_3, V1_1), new EE("CDC-1.1/Foundation-1.1", V1_3, V1_2), new EE("OSGi/Minimum-1.0", V1_3, V1_1), new EE("OSGi/Minimum-1.1", V1_3, V1_2), new EE("JRE-1.1", V1_1, V1_1), // new EE("J2SE-1.2", V1_2, V1_1), // new EE("J2SE-1.3", V1_3, V1_1), // new EE("J2SE-1.4", V1_3, V1_2), // new EE("J2SE-1.5", V1_5, V1_5), // new EE("JavaSE-1.6", V1_6, V1_6), new EE("PersonalJava-1.1", V1_1, V1_1), new EE("PersonalJava-1.2", V1_1, V1_1), new EE("CDC-1.0/PersonalBasis-1.0", V1_3, V1_1), new EE("CDC-1.0/PersonalJava-1.0", V1_3, V1_1), new EE("CDC-1.1/PersonalBasis-1.1", V1_3, V1_2), new EE("CDC-1.1/PersonalJava-1.1", V1_3, V1_2) }; final static Pattern BUNDLEMANIFESTVERSION = Pattern .compile("2"); public final static String SYMBOLICNAME_STRING = "[a-zA-Z0-9_-]+(\\.[a-zA-Z0-9_-]+)*"; public final static Pattern SYMBOLICNAME = Pattern .compile(SYMBOLICNAME_STRING); public final static String VERSION_STRING = "[0-9]+(\\.[0-9]+(\\.[0-9]+(\\.[0-9A-Za-z_-]+)?)?)?"; public final static Pattern VERSION = Pattern .compile(VERSION_STRING); final static Pattern FILTEROP = Pattern .compile("=|<=|>=|~="); public final static Pattern VERSIONRANGE = Pattern .compile("((\\(|\\[)" + VERSION_STRING + "," + VERSION_STRING + "(\\]|\\)))|" + VERSION_STRING); final static Pattern FILE = Pattern .compile("/?[^/\"\n\r\u0000]+(/[^/\"\n\r\u0000]+)*"); final static Pattern WILDCARDPACKAGE = Pattern .compile("((\\p{Alnum}|_)+(\\.(\\p{Alnum}|_)+)*(\\.\\*)?)|\\*"); public final static Pattern ISO639 = Pattern .compile("[A-Z][A-Z]"); public final static Pattern HEADER_PATTERN = Pattern .compile("[A-Za-z0-9][-a-zA-Z0-9_]+"); public final static Pattern TOKEN = Pattern .compile("[-a-zA-Z0-9_]+"); public final static Pattern NUMBERPATTERN = Pattern .compile("\\d+"); public final static Pattern PATHPATTERN = Pattern .compile(".*"); public final static Pattern FQNPATTERN = Pattern .compile(".*"); public final static Pattern URLPATTERN = Pattern .compile(".*"); public final static Pattern ANYPATTERN = Pattern .compile(".*"); public final static Pattern FILTERPATTERN = Pattern .compile(".*"); public final static Pattern TRUEORFALSEPATTERN = Pattern .compile("true|false|TRUE|FALSE"); public static final Pattern WILDCARDNAMEPATTERN = Pattern .compile(".*"); public static final Pattern BUNDLE_ACTIVATIONPOLICYPATTERN = Pattern .compile("lazy"); public final static String EES[] = { "CDC-1.0/Foundation-1.0", "CDC-1.1/Foundation-1.1", "OSGi/Minimum-1.0", "OSGi/Minimum-1.1", "OSGi/Minimum-1.2", "JRE-1.1", "J2SE-1.2", "J2SE-1.3", "J2SE-1.4", "J2SE-1.5", "JavaSE-1.6", "JavaSE-1.7", "PersonalJava-1.1", "PersonalJava-1.2", "CDC-1.0/PersonalBasis-1.0", "CDC-1.0/PersonalJava-1.0" }; public final static String OSNAMES[] = { "AIX", // IBM "DigitalUnix", // Compaq "Embos", // Segger Embedded Software Solutions "Epoc32", // SymbianOS Symbian OS "FreeBSD", // Free BSD "HPUX", // hp-ux Hewlett Packard "IRIX", // Silicon Graphics "Linux", // Open source "MacOS", // Apple "NetBSD", // Open source "Netware", // Novell "OpenBSD", // Open source "OS2", // OS/2 IBM "QNX", // procnto QNX "Solaris", // Sun (almost an alias of SunOS) "SunOS", // Sun Microsystems "VxWorks", // WindRiver Systems "Windows95", "Win32", "Windows98", "WindowsNT", "WindowsCE", "Windows2000", // Win2000 "Windows2003", // Win2003 "WindowsXP", "WindowsVista", }; public final static String PROCESSORNAMES[] = { "68k", // Motorola // 68000 "ARM_LE", // Intel Strong ARM. Deprecated because it does not // specify the endianness. See the following two rows. "arm_le", // Intel Strong ARM Little Endian mode "arm_be", // Intel String ARM Big Endian mode "Alpha", // "ia64n",// Hewlett Packard 32 bit "ia64w",// Hewlett Packard 64 bit mode "Ignite", // psc1k PTSC "Mips", // SGI "PArisc", // Hewlett Packard "PowerPC", // power ppc Motorola/IBM Power PC "Sh4", // Hitachi "Sparc", // SUN "Sparcv9", // SUN "S390", // IBM Mainframe 31 bit "S390x", // IBM Mainframe 64-bit "V850E", // NEC V850E "x86", // pentium i386 "i486", // i586 i686 Intel& AMD 32 bit "x86-64", }; Properties properties; public Verifier(Jar jar) throws Exception { this(jar, null); } public Verifier(Jar jar, Properties properties) throws Exception { this.dot = jar; this.properties = properties; this.manifest = jar.getManifest(); if (manifest == null) { manifest = new Manifest(); error("This file contains no manifest and is therefore not a bundle"); } main = this.manifest.getMainAttributes(); verifyHeaders(main); r3 = getHeader(Analyzer.BUNDLE_MANIFESTVERSION) == null; usesRequire = getHeader(Analyzer.REQUIRE_BUNDLE) != null; fragment = getHeader(Analyzer.FRAGMENT_HOST) != null; bundleClasspath = getBundleClassPath(); mimports = parseHeader(manifest.getMainAttributes().getValue( Analyzer.IMPORT_PACKAGE)); mdynimports = parseHeader(manifest.getMainAttributes().getValue( Analyzer.DYNAMICIMPORT_PACKAGE)); mexports = parseHeader(manifest.getMainAttributes().getValue( Analyzer.EXPORT_PACKAGE)); ignore = parseHeader(manifest.getMainAttributes().getValue( Analyzer.IGNORE_PACKAGE)); } public Verifier() { // TODO Auto-generated constructor stub } private void verifyHeaders(Attributes main) { for (Object element : main.keySet()) { Attributes.Name header = (Attributes.Name) element; String h = header.toString(); if (!HEADER_PATTERN.matcher(h).matches()) error("Invalid Manifest header: " + h + ", pattern=" + HEADER_PATTERN); } } private List getBundleClassPath() { List list = newList(); String bcp = getHeader(Analyzer.BUNDLE_CLASSPATH); if (bcp == null) { list.add(dot); } else { Map> entries = parseHeader(bcp); for (Map.Entry> ex : entries.entrySet()) { String jarOrDir = ex.getKey(); if (jarOrDir.equals(".")) { list.add(dot); } else { if (jarOrDir.equals("/")) jarOrDir = ""; if (jarOrDir.endsWith("/")) { error("Bundle-Classpath directory must not end with a slash: " + jarOrDir); jarOrDir = jarOrDir.substring(0, jarOrDir.length() - 1); } Resource resource = dot.getResource(jarOrDir); if (resource != null) { try { Jar sub = new Jar(jarOrDir); addClose(sub); EmbeddedResource.build(sub, resource); if (!jarOrDir.endsWith(".jar")) warning("Valid JAR file on Bundle-Classpath does not have .jar extension: " + jarOrDir); list.add(sub); } catch (Exception e) { error("Invalid embedded JAR file on Bundle-Classpath: " + jarOrDir + ", " + e); } } else if (dot.getDirectories().containsKey(jarOrDir)) { if (r3) error("R3 bundles do not support directories on the Bundle-ClassPath: " + jarOrDir); try { Jar sub = new Jar(jarOrDir); addClose(sub); for (Map.Entry entry : dot .getResources().entrySet()) { if (entry.getKey().startsWith(jarOrDir)) sub.putResource(entry.getKey().substring( jarOrDir.length() + 1), entry .getValue()); } list.add(sub); } catch (Exception e) { error("Invalid embedded directory file on Bundle-Classpath: " + jarOrDir + ", " + e); } } else { // Map info = ex.getValue(); // if (! "optional".equals( // info.get(RESOLUTION_DIRECTIVE))) // warning("Cannot find a file or directory for // Bundle-Classpath entry: %s", // jarOrDir); } } } } return list; } /* * Bundle-NativeCode ::= nativecode ( ',' nativecode )* ( ’,’ optional) ? * nativecode ::= path ( ';' path )* // See 1.4.2 ( ';' parameter )+ * optional ::= ’*’ */ public void verifyNative() { String nc = getHeader("Bundle-NativeCode"); doNative(nc); } public void doNative(String nc) { if (nc != null) { QuotedTokenizer qt = new QuotedTokenizer(nc, ",;=", false); char del; do { do { String name = qt.nextToken(); if (name == null) { error("Can not parse name from bundle native code header: " + nc); return; } del = qt.getSeparator(); if (del == ';') { if (dot != null && !dot.exists(name)) { error("Native library not found in JAR: " + name); } } else { String value = null; if (del == '=') value = qt.nextToken(); String key = name.toLowerCase(); if (key.equals("osname")) { // ... } else if (key.equals("osversion")) { // verify version range verify(value, VERSIONRANGE); } else if (key.equals("language")) { verify(value, ISO639); } else if (key.equals("processor")) { // verify(value, PROCESSORS); } else if (key.equals("selection-filter")) { // verify syntax filter verifyFilter(value); } else if (name.equals("*") && value == null) { // Wildcard must be at end. if (qt.nextToken() != null) error("Bundle-Native code header may only END in wildcard: nc"); } else { warning("Unknown attribute in native code: " + name + "=" + value); } del = qt.getSeparator(); } } while (del == ';'); } while (del == ','); } } public boolean verifyFilter(String value) { try { verifyFilter(value, 0); return true; } catch (Exception e) { error("Not a valid filter: " + value + e.getMessage()); return false; } } private void verifyActivator() { String bactivator = getHeader("Bundle-Activator"); if (bactivator != null) { Clazz cl = loadClass(bactivator); if (cl == null) { int n = bactivator.lastIndexOf('.'); if (n > 0) { String pack = bactivator.substring(0, n); if (mimports.containsKey(pack)) return; error("Bundle-Activator not found on the bundle class path nor in imports: " + bactivator); } else error("Activator uses default package and is not local (default package can not be imported): " + bactivator); } } } private Clazz loadClass(String className) { String path = className.replace('.', '/') + ".class"; return (Clazz) classSpace.get(path); } private void verifyComponent() { String serviceComponent = getHeader("Service-Component"); if (serviceComponent != null) { Map> map = parseHeader(serviceComponent); for (String component : map.keySet()) { if (component.indexOf("*") < 0 && !dot.exists(component)) { error("Service-Component entry can not be located in JAR: " + component); } else { // validate component ... } } } } public void info() { System.out.println("Refers : " + referred); System.out.println("Contains : " + contained); System.out.println("Manifest Imports : " + mimports); System.out.println("Manifest Exports : " + mexports); } /** * Invalid exports are exports mentioned in the manifest but not found on * the classpath. This can be calculated with: exports - contains. * * Unfortunately, we also must take duplicate names into account. These * duplicates are of course no erroneous. */ private void verifyInvalidExports() { Set invalidExport = newSet(mexports.keySet()); invalidExport.removeAll(contained.keySet()); // We might have duplicate names that are marked for it. These // should not be counted. Should we test them against the contained // set? Hmm. If someone wants to hang himself by using duplicates than // I guess he can go ahead ... This is not a recommended practice for (Iterator i = invalidExport.iterator(); i.hasNext();) { String pack = i.next(); if (isDuplicate(pack)) i.remove(); } if (!invalidExport.isEmpty()) error("Exporting packages that are not on the Bundle-Classpath" + bundleClasspath + ": " + invalidExport); } /** * Invalid imports are imports that we never refer to. They can be * calculated by removing the refered packages from the imported packages. * This leaves packages that the manifest imported but that we never use. */ private void verifyInvalidImports() { Set invalidImport = newSet(mimports.keySet()); invalidImport.removeAll(referred.keySet()); // TODO Added this line but not sure why it worked before ... invalidImport.removeAll(contained.keySet()); String bactivator = getHeader(Analyzer.BUNDLE_ACTIVATOR); if (bactivator != null) { int n = bactivator.lastIndexOf('.'); if (n > 0) { invalidImport.remove(bactivator.substring(0, n)); } } if (isPedantic() && !invalidImport.isEmpty()) warning("Importing packages that are never refered to by any class on the Bundle-Classpath" + bundleClasspath + ": " + invalidImport); } /** * Check for unresolved imports. These are referals that are not imported by * the manifest and that are not part of our bundle classpath. The are * calculated by removing all the imported packages and contained from the * refered packages. */ private void verifyUnresolvedReferences() { Set unresolvedReferences = new TreeSet(referred .keySet()); unresolvedReferences.removeAll(mimports.keySet()); unresolvedReferences.removeAll(contained.keySet()); // Remove any java.** packages. for (Iterator p = unresolvedReferences.iterator(); p.hasNext();) { String pack = p.next(); if (pack.startsWith("java.") || ignore.containsKey(pack)) p.remove(); else { // Remove any dynamic imports if (isDynamicImport(pack)) p.remove(); } } if (!unresolvedReferences.isEmpty()) { // Now we want to know the // classes that are the culprits Set culprits = new HashSet(); for (Clazz clazz : classSpace.values()) { if (hasOverlap(unresolvedReferences, clazz.getReferred())) culprits.add(clazz.getPath()); } error("Unresolved references to " + unresolvedReferences + " by class(es) on the Bundle-Classpath" + bundleClasspath + ": " + culprits); } } /** * @param p * @param pack */ private boolean isDynamicImport(String pack) { for (String pattern : mdynimports.keySet()) { // Wildcard? if (pattern.equals("*")) return true; // All packages can be dynamically imported if (pattern.endsWith(".*")) { pattern = pattern.substring(0, pattern.length() - 2); if (pack.startsWith(pattern) && (pack.length() == pattern.length() || pack .charAt(pattern.length()) == '.')) return true; } else { if (pack.equals(pattern)) return true; } } return false; } private boolean hasOverlap(Set a, Set b) { for (Iterator i = a.iterator(); i.hasNext();) { if (b.contains(i.next())) return true; } return false; } public void verify() throws Exception { if (classSpace == null) classSpace = analyzeBundleClasspath(dot, parseHeader(getHeader(Analyzer.BUNDLE_CLASSPATH)), contained, referred, uses); verifyDirectives("Export-Package", "uses:|mandatory:|include:|exclude:|" + IMPORT_DIRECTIVE); verifyDirectives("Import-Package", "resolution:"); verifyDirectives("Require-Bundle", "visibility:|resolution:"); verifyDirectives("Fragment-Host", "resolution:"); verifyDirectives("Provide-Capability", "effective:|uses:"); verifyDirectives("Require-Capability", "effective:|resolve:|filter:"); verifyDirectives("Bundle-SymbolicName", "singleton:|fragment-attachment:|mandatory:"); verifyManifestFirst(); verifyActivator(); verifyActivationPolicy(); verifyComponent(); verifyNative(); verifyInvalidExports(); verifyInvalidImports(); verifyUnresolvedReferences(); verifySymbolicName(); verifyListHeader("Bundle-RequiredExecutionEnvironment", EENAME, false); verifyHeader("Bundle-ManifestVersion", BUNDLEMANIFESTVERSION, false); verifyHeader("Bundle-Version", VERSION, true); verifyListHeader("Bundle-Classpath", FILE, false); verifyDynamicImportPackage(); verifyBundleClasspath(); verifyUses(); if (usesRequire) { if (!getErrors().isEmpty()) { getWarnings() .add( 0, "Bundle uses Require Bundle, this can generate false errors because then not enough information is available without the required bundles"); } } } /** * Verify if the header does not contain any other directives * * @param header * @param directives */ private void verifyDirectives(String header, String directives) { Pattern pattern = Pattern.compile(directives); Map> map = parseHeader(manifest.getMainAttributes().getValue(header)); for ( Map.Entry> entry : map.entrySet()) { for ( String key : entry.getValue().keySet()) { if ( key.endsWith(":")) { if ( ! key.startsWith("x-")) { Matcher m = pattern.matcher(key); if ( m.matches()) continue; warning("Unknown directive %s in %s, allowed directives are %s, and 'x-*'.", key, header, directives.replace('|', ',')); } } } } } /** * Verify the use clauses */ private void verifyUses() { } public boolean verifyActivationPolicy() { String policy = getHeader(Constants.BUNDLE_ACTIVATIONPOLICY); if (policy == null) return true; return verifyActivationPolicy(policy); } public boolean verifyActivationPolicy(String policy) { Map> map = parseHeader(policy); if (map.size() == 0) warning("Bundle-ActivationPolicy is set but has no argument %s", policy); else if (map.size() > 1) warning("Bundle-ActivationPolicy has too many arguments %s", policy); else { Map s = map.get("lazy"); if (s == null) warning( "Bundle-ActivationPolicy set but is not set to lazy: %s", policy); else return true; } return false; } public void verifyBundleClasspath() { Map> bcp = parseHeader(getHeader(Analyzer.BUNDLE_CLASSPATH)); if (bcp.isEmpty() || bcp.containsKey(".")) return; for ( String path : bcp.keySet() ) { if ( path.endsWith("/")) error("A Bundle-ClassPath entry must not end with '/': %s", path); if ( dot.getDirectories().containsKey(path)) // We assume that any classes are in a directory // and therefore do not care when the bundle is included return; } for (String path : dot.getResources().keySet()) { if (path.endsWith(".class")) { warning("The Bundle-Classpath does not contain the actual bundle JAR (as specified with '.' in the Bundle-Classpath) but the JAR does contain classes. Is this intentional?"); return; } } } /** *
     *          DynamicImport-Package ::= dynamic-description
     *              ( ',' dynamic-description )*
     *              
     *          dynamic-description::= wildcard-names ( ';' parameter )*
     *          wildcard-names ::= wildcard-name ( ';' wildcard-name )*
     *          wildcard-name ::= package-name 
     *                         | ( package-name '.*' ) // See 1.4.2
     *                         | '*'
     * 
*/ private void verifyDynamicImportPackage() { verifyListHeader("DynamicImport-Package", WILDCARDPACKAGE, true); String dynamicImportPackage = getHeader("DynamicImport-Package"); if (dynamicImportPackage == null) return; Map> map = parseHeader(dynamicImportPackage); for (String name : map.keySet()) { name = name.trim(); if (!verify(name, WILDCARDPACKAGE)) error("DynamicImport-Package header contains an invalid package name: " + name); Map sub = map.get(name); if (r3 && sub.size() != 0) { error("DynamicPackage-Import has attributes on import: " + name + ". This is however, an <=R3 bundle and attributes on this header were introduced in R4. "); } } } private void verifyManifestFirst() { if (!dot.manifestFirst) { error("Invalid JAR stream: Manifest should come first to be compatible with JarInputStream, it was not"); } } private void verifySymbolicName() { Map> bsn = parseHeader(getHeader(Analyzer.BUNDLE_SYMBOLICNAME)); if (!bsn.isEmpty()) { if (bsn.size() > 1) error("More than one BSN specified " + bsn); String name = (String) bsn.keySet().iterator().next(); if (!SYMBOLICNAME.matcher(name).matches()) { error("Symbolic Name has invalid format: " + name); } } } /** *
     *         filter ::= ’(’ filter-comp ’)’
     *         filter-comp ::= and | or | not | operation
     *         and ::= ’&’ filter-list
     *         or ::= ’|’ filter-list
     *         not ::= ’!’ filter
     *         filter-list ::= filter | filter filter-list
     *         operation ::= simple | present | substring
     *         simple ::= attr filter-type value
     *         filter-type ::= equal | approx | greater | less
     *         equal ::= ’=’
     *         approx ::= ’˜=’
     *         greater ::= ’>=’
     *         less ::= ’<=’
     *         present ::= attr ’=*’
     *         substring ::= attr ’=’ initial any final
     *         inital ::= () | value
     *         any ::= ’*’ star-value
     *         star-value ::= () | value ’*’ star-value
     *         final ::= () | value
     *         value ::= <see text>
     * 
* * @param expr * @param index * @return */ public static int verifyFilter(String expr, int index) { try { while (Character.isWhitespace(expr.charAt(index))) index++; if (expr.charAt(index) != '(') throw new IllegalArgumentException( "Filter mismatch: expected ( at position " + index + " : " + expr); index++; // skip ( while (Character.isWhitespace(expr.charAt(index))) index++; switch (expr.charAt(index)) { case '!': index++; // skip ! while (Character.isWhitespace(expr.charAt(index))) index++; if (expr.charAt(index) != '(') throw new IllegalArgumentException( "Filter mismatch: ! (not) must have one sub expression " + index + " : " + expr); while (Character.isWhitespace(expr.charAt(index))) index++; index = verifyFilter(expr, index); while (Character.isWhitespace(expr.charAt(index))) index++; if (expr.charAt(index) != ')') throw new IllegalArgumentException( "Filter mismatch: expected ) at position " + index + " : " + expr); return index + 1; case '&': case '|': index++; // skip operator while (Character.isWhitespace(expr.charAt(index))) index++; while (expr.charAt(index) == '(') { index = verifyFilter(expr, index); while (Character.isWhitespace(expr.charAt(index))) index++; } if (expr.charAt(index) != ')') throw new IllegalArgumentException( "Filter mismatch: expected ) at position " + index + " : " + expr); return index + 1; // skip ) default: index = verifyFilterOperation(expr, index); if (expr.charAt(index) != ')') throw new IllegalArgumentException( "Filter mismatch: expected ) at position " + index + " : " + expr); return index + 1; } } catch (IndexOutOfBoundsException e) { throw new IllegalArgumentException( "Filter mismatch: early EOF from " + index); } } static private int verifyFilterOperation(String expr, int index) { StringBuffer sb = new StringBuffer(); while ("=><~()".indexOf(expr.charAt(index)) < 0) { sb.append(expr.charAt(index++)); } String attr = sb.toString().trim(); if (attr.length() == 0) throw new IllegalArgumentException( "Filter mismatch: attr at index " + index + " is 0"); sb = new StringBuffer(); while ("=><~".indexOf(expr.charAt(index)) >= 0) { sb.append(expr.charAt(index++)); } String operator = sb.toString(); if (!verify(operator, FILTEROP)) throw new IllegalArgumentException( "Filter error, illegal operator " + operator + " at index " + index); sb = new StringBuffer(); while (")".indexOf(expr.charAt(index)) < 0) { switch (expr.charAt(index)) { case '\\': if ("\\)(*".indexOf(expr.charAt(index + 1)) >= 0 ) index++; else throw new IllegalArgumentException( "Filter error, illegal use of backslash at index " + index + ". Backslash may only be used before * or () or \\"); } sb.append(expr.charAt(index++)); } return index; } private String getHeader(String string) { return main.getValue(string); } private boolean verifyHeader(String name, Pattern regex, boolean error) { String value = manifest.getMainAttributes().getValue(name); if (value == null) return false; QuotedTokenizer st = new QuotedTokenizer(value.trim(), ","); for (Iterator i = st.getTokenSet().iterator(); i.hasNext();) { if (!verify((String) i.next(), regex)) { String msg = "Invalid value for " + name + ", " + value + " does not match " + regex.pattern(); if (error) error(msg); else warning(msg); } } return true; } static private boolean verify(String value, Pattern regex) { return regex.matcher(value).matches(); } private boolean verifyListHeader(String name, Pattern regex, boolean error) { String value = manifest.getMainAttributes().getValue(name); if (value == null) return false; Map> map = parseHeader(value); for (String header : map.keySet()) { if (!regex.matcher(header).matches()) { String msg = "Invalid value for " + name + ", " + value + " does not match " + regex.pattern(); if (error) error(msg); else warning(msg); } } return true; } public String getProperty(String key, String deflt) { if (properties == null) return deflt; return properties.getProperty(key, deflt); } public void setClassSpace(Map classspace, Map> contained, Map> referred, Map> uses) { this.classSpace = classspace; this.contained = contained; this.referred = referred; this.uses = uses; } public static boolean isVersion(String version) { return VERSION.matcher(version).matches(); } public static boolean isIdentifier(String value) { if (value.length() < 1) return false; if (!Character.isJavaIdentifierStart(value.charAt(0))) return false; for (int i = 1; i < value.length(); i++) { if (!Character.isJavaIdentifierPart(value.charAt(i))) return false; } return true; } public static boolean isMember(String value, String[] matches) { for (String match : matches) { if (match.equals(value)) return true; } return false; } public static boolean isFQN(String name) { if ( name.length() == 0) return false; if ( !Character.isJavaIdentifierStart(name.charAt(0))) return false; for ( int i=1; i 0) { out.write(buffer, 0, size); size = in.read(buffer); } } finally { in.close(); } } static void traverse(Jar jar, int rootlength, File directory, Pattern doNotCopy) { if (doNotCopy != null && doNotCopy.matcher(directory.getName()).matches()) return; jar.updateModified(directory.lastModified(), "Dir change"); File files[] = directory.listFiles(); for (int i = 0; i < files.length; i++) { if (files[i].isDirectory()) traverse(jar, rootlength, files[i], doNotCopy); else { String path = files[i].getAbsolutePath().substring( rootlength + 1); if (File.separatorChar != '/') path = path.replace(File.separatorChar, '/'); jar.putResource(path, new FileResource(files[i]), true); } } } public long lastModified() { return file.lastModified(); } public String getExtra() { return extra; } public void setExtra(String extra) { this.extra = extra; } public long size() { return (int) file.length(); } } bnd-1.50.0/biz.aQute.bndlib/src/aQute/lib/osgi/Constants.java0000644000175000017500000003352311656076535023547 0ustar drazzibdrazzibpackage aQute.lib.osgi; import java.nio.charset.*; import java.util.*; import java.util.regex.*; public interface Constants { /* * Defined in OSGi */ /** * @syntax Bundle-ActivationPolicy ::= policy ( ’;’ directive )* policy ::= * ’lazy’ */ String BND_ADDXMLTOTEST = "Bnd-AddXMLToTest"; String BUNDLE_ACTIVATIONPOLICY = "Bundle-ActivationPolicy"; String BUNDLE_ACTIVATOR = "Bundle-Activator"; String BUNDLE_BLUEPRINT = "Bundle-Copyright"; String BUNDLE_CATEGORY = "Bundle-Category"; String BUNDLE_CLASSPATH = "Bundle-ClassPath"; String BUNDLE_CONTACTADDRESS = "Bundle-ContactAddress"; String BUNDLE_COPYRIGHT = "Bundle-Copyright"; String BUNDLE_DESCRIPTION = "Bundle-Description"; String BUNDLE_DOCURL = "Bundle-DocURL"; String BUNDLE_ICON = "Bundle-Icon"; String BUNDLE_LICENSE = "Bundle-License"; String BUNDLE_LOCALIZATION = "Bundle-Localization"; String BUNDLE_MANIFESTVERSION = "Bundle-ManifestVersion"; String BUNDLE_NAME = "Bundle-Name"; String BUNDLE_NATIVECODE = "Bundle-NativeCode"; String BUNDLE_REQUIREDEXECUTIONENVIRONMENT = "Bundle-RequiredExecutionEnvironment"; String BUNDLE_SYMBOLICNAME = "Bundle-SymbolicName"; String BUNDLE_UPDATELOCATION = "Bundle-UpdateLocation"; String BUNDLE_VENDOR = "Bundle-Vendor"; String BUNDLE_VERSION = "Bundle-Version"; String DYNAMICIMPORT_PACKAGE = "DynamicImport-Package"; String EXPORT_PACKAGE = "Export-Package"; String EXPORT_SERVICE = "Export-Service"; String FRAGMENT_HOST = "Fragment-Host"; String IMPORT_PACKAGE = "Import-Package"; String IMPORT_SERVICE = "Import-Service"; String REQUIRE_BUNDLE = "Require-Bundle"; String SERVICE_COMPONENT = "Service-Component"; String PRIVATE_PACKAGE = "Private-Package"; String IGNORE_PACKAGE = "Ignore-Package"; String INCLUDE_RESOURCE = "Include-Resource"; String CONDITIONAL_PACKAGE = "Conditional-Package"; String BND_LASTMODIFIED = "Bnd-LastModified"; String CREATED_BY = "Created-By"; String TOOL = "Tool"; String TESTCASES = "Test-Cases"; String SIGNATURE_TEST = "-signaturetest"; String headers[] = { BUNDLE_ACTIVATOR, BUNDLE_CONTACTADDRESS, BUNDLE_COPYRIGHT, BUNDLE_DESCRIPTION, BUNDLE_DOCURL, BUNDLE_LOCALIZATION, BUNDLE_NATIVECODE, BUNDLE_VENDOR, BUNDLE_VERSION, BUNDLE_LICENSE, BUNDLE_CLASSPATH, SERVICE_COMPONENT, EXPORT_PACKAGE, IMPORT_PACKAGE, BUNDLE_LOCALIZATION, BUNDLE_MANIFESTVERSION, BUNDLE_NAME, BUNDLE_NATIVECODE, BUNDLE_REQUIREDEXECUTIONENVIRONMENT, BUNDLE_SYMBOLICNAME, BUNDLE_VERSION, FRAGMENT_HOST, PRIVATE_PACKAGE, IGNORE_PACKAGE, INCLUDE_RESOURCE, REQUIRE_BUNDLE, IMPORT_SERVICE, EXPORT_SERVICE, CONDITIONAL_PACKAGE, BND_LASTMODIFIED, TESTCASES, SIGNATURE_TEST }; String BUILDPATH = "-buildpath"; String BUILDPACKAGES = "-buildpackages"; String BUMPPOLICY = "-bumppolicy"; String CONDUIT = "-conduit"; String COMPILER_SOURCE = "-source"; String COMPILER_TARGET = "-target"; String DEPENDSON = "-dependson"; String DEPLOY = "-deploy"; String DEPLOYREPO = "-deployrepo"; String DONOTCOPY = "-donotcopy"; String DEBUG = "-debug"; String EXPORT_CONTENTS = "-exportcontents"; String FAIL_OK = "-failok"; String INCLUDE = "-include"; String INCLUDERESOURCE = "-includeresource"; String MAKE = "-make"; String METATYPE = "-metatype"; String MANIFEST = "-manifest"; String SAVEMANIFEST = "-savemanifest"; String NAMESECTION = "-namesection"; String NODEFAULTVERSION = "-nodefaultversion"; String NOEXTRAHEADERS = "-noextraheaders"; String NOMANIFEST = "-nomanifest"; String NOUSES = "-nouses"; @Deprecated String NOPE = "-nope"; String NOBUNDLES = "-nobundles"; String PEDANTIC = "-pedantic"; String PLUGIN = "-plugin"; String POM = "-pom"; String RELEASEREPO = "-releaserepo"; String REMOVEHEADERS = "-removeheaders"; String RESOURCEONLY = "-resourceonly"; String SOURCES = "-sources"; String SOURCEPATH = "-sourcepath"; String SUB = "-sub"; String RUNPROPERTIES = "-runproperties"; String RUNSYSTEMPACKAGES = "-runsystempackages"; String RUNBUNDLES = "-runbundles"; String RUNPATH = "-runpath"; String RUNSTORAGE = "-runstorage"; String RUNBUILDS = "-runbuilds"; String RUNPATH_MAIN_DIRECTIVE = "main:"; String RUNPATH_LAUNCHER_DIRECTIVE = "launcher:"; String RUNVM = "-runvm"; String RUNTRACE = "-runtrace"; String RUNFRAMEWORK = "-runframework"; String RUNTIMEOUT = "-runtimeout"; String SNAPSHOT = "-snapshot"; String RUNFRAMEWORK_SERVICES = "services"; String RUNFRAMEWORK_NONE = "none"; String REPORTNEWER = "-reportnewer"; String SIGN = "-sign"; String TESTPACKAGES = "-testpackages"; String TESTREPORT = "-testreport"; String TESTPATH = "-testpath"; String TESTCONTINUOUS = "-testcontinuous"; String UNDERTEST = "-undertest"; String VERBOSE = "-verbose"; @Deprecated String VERSIONPOLICY_IMPL = "-versionpolicy-impl"; @Deprecated String VERSIONPOLICY_USES = "-versionpolicy-uses"; String PROVIDER_POLICY = "-provider-policy"; String CONSUMER_POLICY = "-consumer-policy"; @Deprecated String VERSIONPOLICY = "-versionpolicy"; String WAB = "-wab"; String WABLIB = "-wablib"; String REQUIRE_BND = "-require-bnd"; // Deprecated String CLASSPATH = "-classpath"; String options[] = { BUILDPATH, BUMPPOLICY, CONDUIT, CLASSPATH, CONSUMER_POLICY, DEPENDSON, DONOTCOPY, EXPORT_CONTENTS, FAIL_OK, INCLUDE, INCLUDERESOURCE, MAKE, MANIFEST, NOEXTRAHEADERS, NOUSES, NOBUNDLES, PEDANTIC, PLUGIN, POM, PROVIDER_POLICY, REMOVEHEADERS, RESOURCEONLY, SOURCES, SOURCEPATH, SOURCES, SOURCEPATH, SUB, RUNBUNDLES, RUNPATH, RUNSYSTEMPACKAGES, RUNPROPERTIES, REPORTNEWER, UNDERTEST, TESTPATH, TESTPACKAGES, TESTREPORT, VERBOSE, NOMANIFEST, DEPLOYREPO, RELEASEREPO, SAVEMANIFEST, RUNVM, WAB, WABLIB, RUNFRAMEWORK, RUNTRACE, TESTCONTINUOUS, SNAPSHOT }; // Ignore bundle specific headers. These bundles do not make // a lot of sense to inherit String[] BUNDLE_SPECIFIC_HEADERS = new String[] { INCLUDE_RESOURCE, BUNDLE_ACTIVATOR, BUNDLE_CLASSPATH, BUNDLE_NAME, BUNDLE_NATIVECODE, BUNDLE_SYMBOLICNAME, IMPORT_PACKAGE, EXPORT_PACKAGE, DYNAMICIMPORT_PACKAGE, FRAGMENT_HOST, REQUIRE_BUNDLE, PRIVATE_PACKAGE, EXPORT_CONTENTS, TESTCASES, NOMANIFEST, SIGNATURE_TEST, WAB, WABLIB }; char DUPLICATE_MARKER = '~'; String SPECIFICATION_VERSION = "specification-version"; String SPLIT_PACKAGE_DIRECTIVE = "-split-package:"; String IMPORT_DIRECTIVE = "-import:"; String NO_IMPORT_DIRECTIVE = "-noimport:"; String REMOVE_ATTRIBUTE_DIRECTIVE = "-remove-attribute:"; String LIB_DIRECTIVE = "lib:"; String NOANNOTATIONS = "-noannotations"; String COMMAND_DIRECTIVE = "command:"; String USES_DIRECTIVE = "uses:"; String MANDATORY_DIRECTIVE = "mandatory:"; String INCLUDE_DIRECTIVE = "include:"; String PROVIDE_DIRECTIVE = "provide:"; String EXCLUDE_DIRECTIVE = "exclude:"; String PRESENCE_DIRECTIVE = "presence:"; String PRIVATE_DIRECTIVE = "private:"; String SINGLETON_DIRECTIVE = "singleton:"; String EXTENSION_DIRECTIVE = "extension:"; String VISIBILITY_DIRECTIVE = "visibility:"; String FRAGMENT_ATTACHMENT_DIRECTIVE = "fragment-attachment:"; String RESOLUTION_DIRECTIVE = "resolution:"; String PATH_DIRECTIVE = "path:"; String SIZE_ATTRIBUTE = "size"; String LINK_ATTRIBUTE = "link"; String NAME_ATTRIBUTE = "name"; String DESCRIPTION_ATTRIBUTE = "description"; String OSNAME_ATTRIBUTE = "osname"; String OSVERSION_ATTRIBUTE = "osversion"; String PROCESSOR_ATTRIBUTE = "processor"; String LANGUAGE_ATTRIBUTE = "language"; String SELECTION_FILTER_ATTRIBUTE = "selection-filter"; String BLUEPRINT_WAIT_FOR_DEPENDENCIES_ATTRIBUTE = "blueprint.wait-for-dependencies"; String BLUEPRINT_TIMEOUT_ATTRIBUTE = "blueprint.timeout"; String VERSION_ATTRIBUTE = "version"; String BUNDLE_SYMBOLIC_NAME_ATTRIBUTE = "bundle-symbolic-name"; String BUNDLE_VERSION_ATTRIBUTE = "bundle-version"; String FROM_DIRECTIVE = "from:"; String KEYSTORE_LOCATION_DIRECTIVE = "keystore:"; String KEYSTORE_PROVIDER_DIRECTIVE = "provider:"; String KEYSTORE_PASSWORD_DIRECTIVE = "password:"; String SIGN_PASSWORD_DIRECTIVE = "sign-password:"; String NONE = "none"; String directives[] = { SPLIT_PACKAGE_DIRECTIVE, NO_IMPORT_DIRECTIVE, IMPORT_DIRECTIVE, RESOLUTION_DIRECTIVE, INCLUDE_DIRECTIVE, USES_DIRECTIVE, EXCLUDE_DIRECTIVE, KEYSTORE_LOCATION_DIRECTIVE, KEYSTORE_PROVIDER_DIRECTIVE, KEYSTORE_PASSWORD_DIRECTIVE, SIGN_PASSWORD_DIRECTIVE, COMMAND_DIRECTIVE, NOANNOTATIONS, LIB_DIRECTIVE, RUNPATH_LAUNCHER_DIRECTIVE, FROM_DIRECTIVE, PRIVATE_DIRECTIVE // TODO }; String USES_USES = "<>"; String CURRENT_USES = "@uses"; String IMPORT_REFERENCE = "reference"; String IMPORT_PRIVATE = "private"; String[] importDirectives = { IMPORT_REFERENCE, IMPORT_PRIVATE }; static final Pattern VALID_PROPERTY_TYPES = Pattern .compile("(String|Long|Double|Float|Integer|Byte|Character|Boolean|Short)"); String DEFAULT_BND_EXTENSION = ".bnd"; String DEFAULT_JAR_EXTENSION = ".jar"; String DEFAULT_BAR_EXTENSION = ".bar"; String DEFAULT_BNDRUN_EXTENSION = ".bndrun"; String[] METAPACKAGES = { "META-INF", "OSGI-INF", "OSGI-OPT" }; String CURRENT_VERSION = "@"; String CURRENT_PACKAGE = "@package"; String BUILDFILES = "buildfiles"; String EMPTY_HEADER = "<>"; String EMBEDDED_REPO = "/embedded-repo.jar"; String LAUNCHER_PLUGIN = "Launcher-Plugin"; String TESTER_PLUGIN = "Tester-Plugin"; String DEFAULT_LAUNCHER_BSN = "biz.aQute.launcher"; String DEFAULT_TESTER_BSN = "biz.aQute.junit"; String DEFAULT_DO_NOT_COPY = "CVS|\\.svn|\\.git|\\.DS_Store"; Charset DEFAULT_CHARSET = Charset.forName("UTF8"); String VERSION_FILTER = "version"; /** * Component constants */ public final static String NAMESPACE_STEM = "http://www.osgi.org/xmlns/scr"; public final static String JIDENTIFIER = "<>"; public final static String COMPONENT_NAME = "name:"; public final static String COMPONENT_FACTORY = "factory:"; public final static String COMPONENT_SERVICEFACTORY = "servicefactory:"; public final static String COMPONENT_IMMEDIATE = "immediate:"; public final static String COMPONENT_ENABLED = "enabled:"; public final static String COMPONENT_DYNAMIC = "dynamic:"; public final static String COMPONENT_MULTIPLE = "multiple:"; public final static String COMPONENT_PROVIDE = "provide:"; public final static String COMPONENT_OPTIONAL = "optional:"; public final static String COMPONENT_PROPERTIES = "properties:"; public final static String COMPONENT_IMPLEMENTATION = "implementation:"; public final static String COMPONENT_DESIGNATE = "designate:"; public final static String COMPONENT_DESIGNATEFACTORY = "designateFactory:"; public final static String COMPONENT_DESCRIPTORS = ".descriptors:"; // v1.1.0 public final static String COMPONENT_VERSION = "version:"; public final static String COMPONENT_CONFIGURATION_POLICY = "configuration-policy:"; public final static String COMPONENT_MODIFIED = "modified:"; public final static String COMPONENT_ACTIVATE = "activate:"; public final static String COMPONENT_DEACTIVATE = "deactivate:"; final static Map EMPTY = Collections.emptyMap(); public final static String[] componentDirectives = new String[] { COMPONENT_FACTORY, COMPONENT_IMMEDIATE, COMPONENT_ENABLED, COMPONENT_DYNAMIC, COMPONENT_MULTIPLE, COMPONENT_PROVIDE, COMPONENT_OPTIONAL, COMPONENT_PROPERTIES, COMPONENT_IMPLEMENTATION, COMPONENT_SERVICEFACTORY, COMPONENT_VERSION, COMPONENT_CONFIGURATION_POLICY, COMPONENT_MODIFIED, COMPONENT_ACTIVATE, COMPONENT_DEACTIVATE, COMPONENT_NAME, COMPONENT_DESCRIPTORS, COMPONENT_DESIGNATE, COMPONENT_DESIGNATEFACTORY }; public final static Set SET_COMPONENT_DIRECTIVES = new HashSet( Arrays.asList(componentDirectives)); public final static Set SET_COMPONENT_DIRECTIVES_1_1 = // new HashSet( Arrays.asList( COMPONENT_VERSION, COMPONENT_CONFIGURATION_POLICY, COMPONENT_MODIFIED, COMPONENT_ACTIVATE, COMPONENT_DEACTIVATE)); } bnd-1.50.0/biz.aQute.bndlib/src/aQute/lib/osgi/packageinfo0000644000175000017500000000001711656076535023112 0ustar drazzibdrazzibversion 1.43.1 bnd-1.50.0/biz.aQute.bndlib/src/aQute/lib/osgi/Resource.java0000755000175000017500000000036411656076535023362 0ustar drazzibdrazzibpackage aQute.lib.osgi; import java.io.*; public interface Resource { InputStream openInputStream() throws Exception ; void write(OutputStream out) throws Exception; long lastModified(); void setExtra(String extra); String getExtra(); } bnd-1.50.0/biz.aQute.bndlib/src/aQute/lib/osgi/ZipResource.java0000755000175000017500000000470011656076535024043 0ustar drazzibdrazzibpackage aQute.lib.osgi; import java.io.*; import java.util.*; import java.util.regex.*; import java.util.zip.*; public class ZipResource implements Resource { ZipFile zip; ZipEntry entry; long lastModified; String extra; ZipResource(ZipFile zip, ZipEntry entry, long lastModified) { this.zip = zip; this.entry = entry; this.lastModified = lastModified; byte[] data = entry.getExtra(); if (data != null) this.extra = new String(data); } public InputStream openInputStream() throws IOException { return zip.getInputStream(entry); } public String toString() { return ":" + zip.getName() + "(" + entry.getName() + "):"; } public static ZipFile build(Jar jar, File file) throws ZipException, IOException { return build(jar, file, null); } public static ZipFile build(Jar jar, File file, Pattern pattern) throws ZipException, IOException { try { ZipFile zip = new ZipFile(file); nextEntry: for (Enumeration e = zip.entries(); e .hasMoreElements();) { ZipEntry entry = e.nextElement(); if (pattern != null) { Matcher m = pattern.matcher(entry.getName()); if (!m.matches()) continue nextEntry; } if (!entry.isDirectory()) { long time = entry.getTime(); if (time <= 0) time = file.lastModified(); jar.putResource(entry.getName(), new ZipResource(zip, entry, time), true); } } return zip; } catch (ZipException ze) { throw new ZipException("The JAR/ZIP file (" + file.getAbsolutePath() + ") seems corrupted, error: " + ze.getMessage()); } catch (FileNotFoundException e) { throw new IllegalArgumentException("Problem opening JAR: " + file.getAbsolutePath()); } } public void write(OutputStream out) throws Exception { FileResource.copy(this, out); } public long lastModified() { return lastModified; } public String getExtra() { return extra; } public void setExtra(String extra) { this.extra = extra; } } bnd-1.50.0/biz.aQute.bndlib/src/aQute/lib/osgi/Builder.java0000755000175000017500000010364211656076535023164 0ustar drazzibdrazzibpackage aQute.lib.osgi; import java.io.*; import java.util.*; import java.util.jar.*; import java.util.regex.*; import java.util.zip.*; import aQute.bnd.component.*; import aQute.bnd.make.*; import aQute.bnd.make.component.*; import aQute.bnd.make.metatype.*; import aQute.bnd.maven.*; import aQute.bnd.service.*; /** * Include-Resource: ( [name '=' ] file )+ * * Private-Package: package-decl ( ',' package-decl )* * * Export-Package: package-decl ( ',' package-decl )* * * Import-Package: package-decl ( ',' package-decl )* * * @version $Revision: 1.27 $ */ public class Builder extends Analyzer { Pattern xdoNotCopy = null; private static final int SPLIT_MERGE_LAST = 1; private static final int SPLIT_MERGE_FIRST = 2; private static final int SPLIT_ERROR = 3; private static final int SPLIT_FIRST = 4; private static final int SPLIT_DEFAULT = 0; List sourcePath = new ArrayList(); Make make = new Make(this); public Builder(Processor parent) { super(parent); } public Builder() { } public Jar build() throws Exception { init(); if (isTrue(getProperty(NOBUNDLES))) return null; if (getProperty(CONDUIT) != null) error("Specified " + CONDUIT + " but calls build() instead of builds() (might be a programmer error"); dot = new Jar("dot"); addClose(dot); try { long modified = Long.parseLong(getProperty("base.modified")); dot.updateModified(modified, "Base modified"); } catch (Exception e) { } doExpand(dot); doIncludeResources(dot); doConditional(dot); dot = doWab(dot); // NEW! // Check if we override the calculation of the // manifest. We still need to calculated it because // we need to have analyzed the classpath. Manifest manifest = calcManifest(); String mf = getProperty(MANIFEST); if (mf != null) { File mff = getFile(mf); if (mff.isFile()) { try { InputStream in = new FileInputStream(mff); manifest = new Manifest(in); in.close(); } catch (Exception e) { error(MANIFEST + " while reading manifest file", e); } } else { error(MANIFEST + ", no such file " + mf); } } if (getProperty(NOMANIFEST) == null) dot.setManifest(manifest); else dot.setDoNotTouchManifest(); // This must happen after we analyzed so // we know what it is on the classpath addSources(dot); if (getProperty(POM) != null) dot.putResource("pom.xml", new PomResource(dot.getManifest())); if (!isNoBundle()) doVerify(dot); if (dot.getResources().isEmpty()) error("The JAR is empty: " + dot.getName()); dot.updateModified(lastModified(), "Last Modified Processor"); dot.setName(getBsn()); sign(dot); doSaveManifest(dot); return dot; } /** * Allow any local initialization by subclasses before we build. */ public void init() throws Exception { begin(); doRequireBnd(); } /** * Turn this normal bundle in a web and add any resources. * * @throws Exception */ private Jar doWab(Jar dot) throws Exception { String wab = getProperty(WAB); String wablib = getProperty(WABLIB); if (wab == null && wablib == null) return dot; setProperty(BUNDLE_CLASSPATH, append("WEB-INF/classes", getProperty(BUNDLE_CLASSPATH))); Jar next = new Jar(dot.getName()); addClose(next); for (Map.Entry entry : dot.getResources().entrySet()) { String path = entry.getKey(); if (path.indexOf('/') > 0 && !Character.isUpperCase(path.charAt(0))) { trace("wab: moving: %s", path); next.putResource("WEB-INF/classes/" + path, entry.getValue()); } else { trace("wab: not moving: %s", path); next.putResource(path, entry.getValue()); } } Map> clauses = parseHeader(getProperty(WABLIB)); for (String key : clauses.keySet()) { File f = getFile(key); addWabLib(next, f); } doIncludeResource(next, wab); return next; } /** * Add a wab lib to the jar. * * @param f */ private void addWabLib(Jar dot, File f) throws Exception { if (f.exists()) { Jar jar = new Jar(f); jar.setDoNotTouchManifest(); addClose(jar); String path = "WEB-INF/lib/" + f.getName(); dot.putResource(path, new JarResource(jar)); setProperty(BUNDLE_CLASSPATH, append(getProperty(BUNDLE_CLASSPATH), path)); Manifest m = jar.getManifest(); String cp = m.getMainAttributes().getValue("Class-Path"); if (cp != null) { Collection parts = split(cp, ","); for (String part : parts) { File sub = getFile(f.getParentFile(), part); if (!sub.exists() || !sub.getParentFile().equals(f.getParentFile())) { warning("Invalid Class-Path entry %s in %s, must exist and must reside in same directory", sub, f); } else { addWabLib(dot, sub); } } } } else { error("WAB lib does not exist %s", f); } } /** * Get the manifest and write it out separately if -savemanifest is set * * @param dot */ private void doSaveManifest(Jar dot) throws Exception { String output = getProperty(SAVEMANIFEST); if (output == null) return; File f = getFile(output); if (f.isDirectory()) { f = new File(f, "MANIFEST.MF"); } f.delete(); f.getParentFile().mkdirs(); OutputStream out = new FileOutputStream(f); try { Jar.writeManifest(dot.getManifest(), out); } finally { out.close(); } changedFile(f); } protected void changedFile(File f) { } /** * Sign the jar file. * * -sign : [ ';' 'password:=' ] [ ';' 'keystore:=' * ] [ ';' 'sign-password:=' ] ( ',' ... )* * * @return */ void sign(Jar jar) throws Exception { String signing = getProperty("-sign"); if (signing == null) return; trace("Signing %s, with %s", getBsn(), signing); List signers = getPlugins(SignerPlugin.class); Map> infos = parseHeader(signing); for (Map.Entry> entry : infos.entrySet()) { for (SignerPlugin signer : signers) { signer.sign(this, entry.getKey()); } } } public boolean hasSources() { return isTrue(getProperty(SOURCES)); } protected String getImportPackages() { String ip = super.getImportPackages(); if (ip != null) return ip; return "*"; } private void doConditional(Jar dot) throws Exception { Map> conditionals = getHeader(CONDITIONAL_PACKAGE); if (conditionals.isEmpty()) return; while (true) { analyze(); Map> imports = getImports(); // Match the packages specified in conditionals // against the imports. Any match must become a // Private-Package Map> filtered = merge(CONDITIONAL_PACKAGE, conditionals, imports, new HashSet(), null); // Imports can also specify a private import. These // packages must also be copied to the bundle for (Map.Entry> entry : getImports().entrySet()) { String type = entry.getValue().get(IMPORT_DIRECTIVE); if (type != null && type.equals(PRIVATE_DIRECTIVE)) filtered.put(entry.getKey(), entry.getValue()); } // remove existing packages to prevent merge errors filtered.keySet().removeAll(dot.getPackages()); if (filtered.size() == 0) break; int size = dot.getResources().size(); doExpand(dot, CONDITIONAL_PACKAGE + " Private imports", Instruction.replaceWithInstruction(filtered), false); // Were there any expansions? if (size == dot.getResources().size()) break; analyzed = false; } } /** * Intercept the call to analyze and cleanup versions after we have analyzed * the setup. We do not want to cleanup if we are going to verify. */ public void analyze() throws Exception { super.analyze(); cleanupVersion(imports, null); cleanupVersion(exports, getVersion()); String version = getProperty(BUNDLE_VERSION); if (version != null) { version = cleanupVersion(version); if (version.endsWith(".SNAPSHOT")) { version = version.replaceAll("SNAPSHOT$", getProperty(SNAPSHOT, "SNAPSHOT")); } setProperty(BUNDLE_VERSION, version); } } public void cleanupVersion(Map> mapOfMap, String defaultVersion) { for (Iterator>> e = mapOfMap.entrySet().iterator(); e .hasNext();) { Map.Entry> entry = e.next(); Map attributes = entry.getValue(); String v = attributes.get(Constants.VERSION_ATTRIBUTE); if (v == null && defaultVersion != null) { if (!isTrue(getProperty(Constants.NODEFAULTVERSION))) { v = defaultVersion; if (isPedantic()) warning("Used bundle version %s for exported package %s", v, entry.getKey()); } else { if (isPedantic()) warning("No export version for exported package %s", entry.getKey()); } } if (v != null) attributes.put(Constants.VERSION_ATTRIBUTE, cleanupVersion(v)); } } /** * */ private void addSources(Jar dot) { if (!hasSources()) return; Set packages = new HashSet(); try { ByteArrayOutputStream out = new ByteArrayOutputStream(); getProperties().store(out, "Generated by BND, at " + new Date()); dot.putResource("OSGI-OPT/bnd.bnd", new EmbeddedResource(out.toByteArray(), 0)); out.close(); } catch (Exception e) { error("Can not embed bnd file in JAR: " + e); } for (Iterator cpe = classspace.keySet().iterator(); cpe.hasNext();) { String path = cpe.next(); path = path.substring(0, path.length() - ".class".length()) + ".java"; String pack = getPackage(path).replace('.', '/'); if (pack.length() > 1) pack = pack + "/"; boolean found = false; String[] fixed = { "packageinfo", "package.html", "module-info.java", "package-info.java" }; for (Iterator i = getSourcePath().iterator(); i.hasNext();) { File root = i.next(); File f = getFile(root, path); if (f.exists()) { found = true; if (!packages.contains(pack)) { packages.add(pack); File bdir = getFile(root, pack); for (int j = 0; j < fixed.length; j++) { File ff = getFile(bdir, fixed[j]); if (ff.isFile()) { String name = "OSGI-OPT/src/" + pack + fixed[j]; dot.putResource(name, new FileResource(ff)); } } } if ( path.trim().length() == 0) System.out.println("Duh?"); dot.putResource("OSGI-OPT/src/" + path, new FileResource(f)); } } if (!found) { for (Jar jar : classpath) { Resource resource = jar.getResource(path); if (resource != null) { dot.putResource("OSGI-OPT/src/"+path, resource); } else { resource = jar.getResource("OSGI-OPT/src/" + path); if (resource != null) { dot.putResource("OSGI-OPT/src/"+path, resource); } } } } if (getSourcePath().isEmpty()) warning("Including sources but " + SOURCEPATH + " does not contain any source directories "); // TODO copy from the jars where they came from } } boolean firstUse = true; public Collection getSourcePath() { if (firstUse) { firstUse = false; String sp = getProperty(SOURCEPATH); if (sp != null) { Map> map = parseHeader(sp); for (Iterator i = map.keySet().iterator(); i.hasNext();) { String file = i.next(); if (!isDuplicate(file)) { File f = getFile(file); if (!f.isDirectory()) { error("Adding a sourcepath that is not a directory: " + f); } else { sourcePath.add(f); } } } } } return sourcePath; } private void doVerify(Jar dot) throws Exception { Verifier verifier = new Verifier(dot, getProperties()); verifier.setPedantic(isPedantic()); // Give the verifier the benefit of our analysis // prevents parsing the files twice verifier.setClassSpace(classspace, contained, referred, uses); verifier.verify(); getInfo(verifier); } private void doExpand(Jar jar) throws IOException { if (getClasspath().size() == 0 && (getProperty(EXPORT_PACKAGE) != null || getProperty(EXPORT_PACKAGE) != null || getProperty(PRIVATE_PACKAGE) != null)) warning("Classpath is empty. Private-Package and Export-Package can only expand from the classpath when there is one"); Map> privateMap = Instruction .replaceWithInstruction(getHeader(PRIVATE_PACKAGE)); Map> exportMap = Instruction .replaceWithInstruction(getHeader(EXPORT_PACKAGE)); if (isTrue(getProperty(Constants.UNDERTEST))) { privateMap.putAll(Instruction.replaceWithInstruction(parseHeader(getProperty( Constants.TESTPACKAGES, "test;presence:=optional")))); } if (!privateMap.isEmpty()) doExpand(jar, "Private-Package, or -testpackages", privateMap, true); if (!exportMap.isEmpty()) { Jar exports = new Jar("exports"); doExpand(exports, EXPORT_PACKAGE, exportMap, true); jar.addAll(exports); exports.close(); } if (!isNoBundle()) { if (privateMap.isEmpty() && exportMap.isEmpty() && !isResourceOnly() && getProperty(EXPORT_CONTENTS) == null) { warning("None of Export-Package, Provide-Package, Private-Package, -testpackages, or -exportcontents is set, therefore no packages will be included"); } } } /** * * @param jar * @param name * @param instructions */ private void doExpand(Jar jar, String name, Map> instructions, boolean mandatory) { Set superfluous = removeMarkedDuplicates(instructions.keySet()); for (Iterator c = getClasspath().iterator(); c.hasNext();) { Jar now = c.next(); doExpand(jar, instructions, now, superfluous); } if (mandatory && superfluous.size() > 0) { StringBuilder sb = new StringBuilder(); String del = "Instructions in " + name + " that are never used: "; for (Iterator i = superfluous.iterator(); i.hasNext();) { Instruction p = i.next(); sb.append(del); sb.append(p.toString()); del = "\n "; } sb.append("\nClasspath: "); sb.append(Processor.join(getClasspath())); sb.append("\n"); warning("%s",sb.toString()); if (isPedantic()) diagnostics = true; } } /** * Iterate over each directory in the class path entry and check if that * directory is a desired package. * * @param included * @param classpathEntry */ private void doExpand(Jar jar, Map> included, Jar classpathEntry, Set superfluous) { loop: for (Map.Entry> directory : classpathEntry .getDirectories().entrySet()) { String path = directory.getKey(); if (doNotCopy(getName(path))) continue; if (directory.getValue() == null) continue; String pack = path.replace('/', '.'); Instruction instr = matches(included, pack, superfluous, classpathEntry.getName()); if (instr != null) { // System.out.println("Pattern match: " + pack + " " + // instr.getPattern() + " " + instr.isNegated()); if (!instr.isNegated()) { Map contents = directory.getValue(); // What to do with split packages? Well if this // directory already exists, we will check the strategy // and react accordingly. boolean overwriteResource = true; if (jar.hasDirectory(path)) { Map directives = included.get(instr); switch (getSplitStrategy((String) directives.get(SPLIT_PACKAGE_DIRECTIVE))) { case SPLIT_MERGE_LAST: overwriteResource = true; break; case SPLIT_MERGE_FIRST: overwriteResource = false; break; case SPLIT_ERROR: error(diagnostic(pack, getClasspath(), classpathEntry.source)); continue loop; case SPLIT_FIRST: continue loop; default: warning("%s", diagnostic(pack, getClasspath(), classpathEntry.source)); overwriteResource = false; break; } } jar.addDirectory(contents, overwriteResource); String key = path + "/bnd.info"; Resource r = jar.getResource(key); if (r != null) jar.putResource(key, new PreprocessResource(this, r)); if (hasSources()) { String srcPath = "OSGI-OPT/src/" + path; Map srcContents = classpathEntry.getDirectories().get( srcPath); if (srcContents != null) { jar.addDirectory(srcContents, overwriteResource); } } } } } } /** * Analyze the classpath for a split package * * @param pack * @param classpath * @param source * @return */ private String diagnostic(String pack, List classpath, File source) { // Default is like merge-first, but with a warning // Find the culprits pack = pack.replace('.', '/'); List culprits = new ArrayList(); for (Iterator i = classpath.iterator(); i.hasNext();) { Jar culprit = (Jar) i.next(); if (culprit.getDirectories().containsKey(pack)) { culprits.add(culprit); } } return "Split package " + pack + "\nUse directive -split-package:=(merge-first|merge-last|error|first) on Export/Private Package instruction to get rid of this warning\n" + "Package found in " + culprits + "\n" + "Reference from " + source + "\n" + "Classpath " + classpath; } private int getSplitStrategy(String type) { if (type == null) return SPLIT_DEFAULT; if (type.equals("merge-last")) return SPLIT_MERGE_LAST; if (type.equals("merge-first")) return SPLIT_MERGE_FIRST; if (type.equals("error")) return SPLIT_ERROR; if (type.equals("first")) return SPLIT_FIRST; error("Invalid strategy for split-package: " + type); return SPLIT_DEFAULT; } /** * Matches the instructions against a package. * * @param instructions * The list of instructions * @param pack * The name of the package * @param superfluousPatterns * The total list of patterns, matched patterns are removed * @param source * The name of the source container, can be filtered upon with * the from: directive. * @return */ private Instruction matches(Map> instructions, String pack, Set superfluousPatterns, String source) { for (Map.Entry> entry : instructions.entrySet()) { Instruction pattern = entry.getKey(); // It is possible to filter on the source of the // package with the from: directive. This is an // instruction that must match the name of the // source class path entry. String from = entry.getValue().get(FROM_DIRECTIVE); if (from != null) { Instruction f = Instruction.getPattern(from); if (!f.matches(source) || f.isNegated()) return null; } // Now do the normal // matching if (pattern.matches(pack)) { if (superfluousPatterns != null) superfluousPatterns.remove(pattern); return pattern; } } return null; } private Map> getHeader(String string) { if (string == null) return Collections.emptyMap(); return parseHeader(getProperty(string)); } /** * Parse the Bundle-Includes header. Files in the bundles Include header are * included in the jar. The source can be a directory or a file. * * @throws IOException * @throws FileNotFoundException */ private void doIncludeResources(Jar jar) throws Exception { String includes = getProperty("Bundle-Includes"); if (includes == null) { includes = getProperty(INCLUDERESOURCE); if (includes == null || includes.length() == 0) includes = getProperty("Include-Resource"); } else warning("Please use -includeresource instead of Bundle-Includes"); doIncludeResource(jar, includes); } private void doIncludeResource(Jar jar, String includes) throws Exception { Map> clauses = parseHeader(includes); doIncludeResource(jar, clauses); } private void doIncludeResource(Jar jar, Map> clauses) throws ZipException, IOException, Exception { for (Map.Entry> entry : clauses.entrySet()) { doIncludeResource(jar, entry.getKey(), entry.getValue()); } } private void doIncludeResource(Jar jar, String name, Map extra) throws ZipException, IOException, Exception { boolean preprocess = false; if (name.startsWith("{") && name.endsWith("}")) { preprocess = true; name = name.substring(1, name.length() - 1).trim(); } String parts[] = name.split("\\s*=\\s*"); String source = parts[0]; String destination = parts[0]; if (parts.length == 2) source = parts[1]; if (source.startsWith("@")) { extractFromJar(jar, source.substring(1), parts.length == 1 ? "" : destination); } else if (extra.containsKey("literal")) { String literal = (String) extra.get("literal"); Resource r = new EmbeddedResource(literal.getBytes("UTF-8"), 0); String x = (String) extra.get("extra"); if (x != null) r.setExtra(x); jar.putResource(name, r); } else { File sourceFile; String destinationPath; sourceFile = getFile(source); if (parts.length == 1) { // Directories should be copied to the root // but files to their file name ... if (sourceFile.isDirectory()) destinationPath = ""; else destinationPath = sourceFile.getName(); } else { destinationPath = parts[0]; } // Handle directories if (sourceFile.isDirectory()) { destinationPath = doResourceDirectory(jar, extra, preprocess, sourceFile, destinationPath); return; } // destinationPath = checkDestinationPath(destinationPath); if (!sourceFile.exists()) { noSuchFile(jar, name, extra, source, destinationPath); } else copy(jar, destinationPath, sourceFile, preprocess, extra); } } private String doResourceDirectory(Jar jar, Map extra, boolean preprocess, File sourceFile, String destinationPath) throws Exception { String filter = extra.get("filter:"); boolean flatten = isTrue(extra.get("flatten:")); boolean recursive = true; String directive = extra.get("recursive:"); if (directive != null) { recursive = isTrue(directive); } InstructionFilter iFilter = null; if (filter != null) { iFilter = new InstructionFilter(Instruction.getPattern(filter), recursive, getDoNotCopy()); } else { iFilter = new InstructionFilter(null, recursive, getDoNotCopy()); } Map files = newMap(); resolveFiles(sourceFile, iFilter, recursive, destinationPath, files, flatten); for (Map.Entry entry : files.entrySet()) { copy(jar, entry.getKey(), entry.getValue(), preprocess, extra); } return destinationPath; } private void resolveFiles(File dir, FileFilter filter, boolean recursive, String path, Map files, boolean flatten) { if (doNotCopy(dir.getName())) { return; } File[] fs = dir.listFiles(filter); for (File file : fs) { if (file.isDirectory()) { if (recursive) { String nextPath; if (flatten) nextPath = path; else nextPath = appendPath(path, file.getName()); resolveFiles(file, filter, recursive, nextPath, files, flatten); } // Directories are ignored otherwise } else { String p = appendPath(path, file.getName()); if (files.containsKey(p)) warning("Include-Resource overwrites entry %s from file %s", p, file); files.put(p, file); } } } private void noSuchFile(Jar jar, String clause, Map extra, String source, String destinationPath) throws Exception { Jar src = getJarFromName(source, "Include-Resource " + source); if (src != null) { JarResource jarResource = new JarResource(src); jar.putResource(destinationPath, jarResource); } else { Resource lastChance = make.process(source); if (lastChance != null) { String x = extra.get("extra"); if (x != null) lastChance.setExtra(x); jar.putResource(destinationPath, lastChance); } else error("Input file does not exist: " + source); } } /** * Extra resources from a Jar and add them to the given jar. The clause is * the * * @param jar * @param clauses * @param i * @throws ZipException * @throws IOException */ private void extractFromJar(Jar jar, String source, String destination) throws ZipException, IOException { // Inline all resources and classes from another jar // optionally appended with a modified regular expression // like @zip.jar!/META-INF/MANIFEST.MF int n = source.lastIndexOf("!/"); Instruction instr = null; if (n > 0) { instr = Instruction.getPattern(source.substring(n + 2)); source = source.substring(0, n); } // Pattern filter = null; // if (n > 0) { // String fstring = source.substring(n + 2); // source = source.substring(0, n); // filter = wildcard(fstring); // } Jar sub = getJarFromName(source, "extract from jar"); if (sub == null) error("Can not find JAR file " + source); else { jar.addAll(sub, instr, destination); } } private void copy(Jar jar, String path, File from, boolean preprocess, Map extra) throws Exception { if (doNotCopy(from.getName())) return; if (from.isDirectory()) { File files[] = from.listFiles(); for (int i = 0; i < files.length; i++) { copy(jar, appendPath(path, files[i].getName()), files[i], preprocess, extra); } } else { if (from.exists()) { Resource resource = new FileResource(from); if (preprocess) { resource = new PreprocessResource(this, resource); } String x = extra.get("extra"); if (x != null) resource.setExtra(x); if (path.endsWith("/")) path = path + from.getName(); jar.putResource(path, resource); if (isTrue(extra.get(LIB_DIRECTIVE))) { setProperty(BUNDLE_CLASSPATH, append(getProperty(BUNDLE_CLASSPATH), path)); } } else { error("Input file does not exist: " + from); } } } private String getName(String where) { int n = where.lastIndexOf('/'); if (n < 0) return where; return where.substring(n + 1); } public void setSourcepath(File[] files) { for (int i = 0; i < files.length; i++) addSourcepath(files[i]); } public void addSourcepath(File cp) { if (!cp.exists()) warning("File on sourcepath that does not exist: " + cp); sourcePath.add(cp); } public void close() { super.close(); } /** * Build Multiple jars. If the -sub command is set, we filter the file with * the given patterns. * * @return * @throws Exception */ public Jar[] builds() throws Exception { begin(); // Are we acting as a conduit for another JAR? String conduit = getProperty(CONDUIT); if (conduit != null) { Map> map = parseHeader(conduit); Jar[] result = new Jar[map.size()]; int n = 0; for (String file : map.keySet()) { Jar c = new Jar(getFile(file)); addClose(c); String name = map.get(file).get("name"); if (name != null) c.setName(name); result[n++] = c; } return result; } List result = new ArrayList(); List builders; builders = getSubBuilders(); for (Builder builder : builders) { try { Jar jar = builder.build(); jar.setName(builder.getBsn()); result.add(jar); } catch (Exception e) { e.printStackTrace(); error("Sub Building " + builder.getBsn(), e); } if (builder != this) getInfo(builder, builder.getBsn() + ": "); } return result.toArray(new Jar[result.size()]); } /** * Answer a list of builders that represent this file or a list of files * specified in -sub. This list can be empty. These builders represents to * be created artifacts and are each scoped to such an artifacts. The * builders can be used to build the bundles or they can be used to find out * information about the to be generated bundles. * * @return List of 0..n builders representing artifacts. * @throws Exception */ public List getSubBuilders() throws Exception { String sub = (String) getProperty(SUB); if (sub == null || sub.trim().length() == 0 || EMPTY_HEADER.equals(sub)) return Arrays.asList(this); List builders = new ArrayList(); if (isTrue(getProperty(NOBUNDLES))) return builders; Map> subsMap = parseHeader(sub); for (Iterator i = subsMap.keySet().iterator(); i.hasNext();) { File file = getFile(i.next()); if (file.isFile()) { builders.add(getSubBuilder(file)); i.remove(); } } Set subs = Instruction.replaceWithInstruction(subsMap).keySet(); List members = new ArrayList(Arrays.asList(getBase().listFiles())); nextFile: while (members.size() > 0) { File file = members.remove(0); // Check if the file is one of our parents Processor p = this; while (p != null) { if (file.equals(p.getPropertiesFile())) continue nextFile; p = p.getParent(); } for (Iterator i = subs.iterator(); i.hasNext();) { Instruction instruction = i.next(); if (instruction.matches(file.getName())) { if (!instruction.isNegated()) { builders.add(getSubBuilder(file)); } // Because we matched (even though we could be negated) // we skip any remaining searches continue nextFile; } } } return builders; } public Builder getSubBuilder(File file) throws Exception { Builder builder = getSubBuilder(); if (builder != null) { builder.setProperties(file); addClose(builder); } return builder; } public Builder getSubBuilder() throws Exception { Builder builder = new Builder(this); builder.setBase(getBase()); for (Jar file : getClasspath()) { builder.addClasspath(file); } return builder; } /** * A macro to convert a maven version to an OSGi version */ public String _maven_version(String args[]) { if (args.length > 2) error("${maven_version} macro receives too many arguments " + Arrays.toString(args)); else if (args.length < 2) error("${maven_version} macro has no arguments, use ${maven_version;1.2.3-SNAPSHOT}"); else { return cleanupVersion(args[1]); } return null; } public String _permissions(String args[]) throws IOException { StringBuilder sb = new StringBuilder(); for (String arg : args) { if ("packages".equals(arg) || "all".equals(arg)) { for (String imp : getImports().keySet()) { if (!imp.startsWith("java.")) { sb.append("(org.osgi.framework.PackagePermission \""); sb.append(imp); sb.append("\" \"import\")\r\n"); } } for (String exp : getExports().keySet()) { sb.append("(org.osgi.framework.PackagePermission \""); sb.append(exp); sb.append("\" \"export\")\r\n"); } } else if ("admin".equals(arg) || "all".equals(arg)) { sb.append("(org.osgi.framework.AdminPermission)"); } else if ("permissions".equals(arg)) ; else error("Invalid option in ${permissions}: %s", arg); } return sb.toString(); } /** * */ public void removeBundleSpecificHeaders() { Set set = new HashSet(Arrays.asList(BUNDLE_SPECIFIC_HEADERS)); setForceLocal(set); } /** * Check if the given resource is in scope of this bundle. That is, it * checks if the Include-Resource includes this resource or if it is a class * file it is on the class path and the Export-Pacakge or Private-Package * include this resource. * * For now, include resources are skipped. * * @param f * @return */ public boolean isInScope(Collection resources) throws Exception { Map> clauses = parseHeader(getProperty(Constants.EXPORT_PACKAGE)); clauses.putAll(parseHeader(getProperty(Constants.PRIVATE_PACKAGE))); if (isTrue(getProperty(Constants.UNDERTEST))) { clauses.putAll(parseHeader(getProperty(Constants.TESTPACKAGES, "test;presence:=optional"))); } Map> instructions = Instruction .replaceWithInstruction(clauses); for (File r : resources) { String cpEntry = getClasspathEntrySuffix(r); if (cpEntry != null) { String pack = Clazz.getPackage(cpEntry); Instruction i = matches(instructions, pack, null, r.getName()); if (i != null) return !i.isNegated(); } } return false; } /** * Answer the string of the resource that it has in the container. * * @param resource * The resource to look for * @return * @throws Exception */ public String getClasspathEntrySuffix(File resource) throws Exception { for (Jar jar : getClasspath()) { File source = jar.getSource(); if (source != null) { source = source.getCanonicalFile(); String sourcePath = source.getAbsolutePath(); String resourcePath = resource.getAbsolutePath(); if (resourcePath.startsWith(sourcePath)) { // Make sure that the path name is translated correctly // i.e. on Windows the \ must be translated to / String filePath = resourcePath.substring(sourcePath.length() + 1); return filePath.replace(File.separatorChar, '/'); } } } return null; } /** * doNotCopy * * The doNotCopy variable maintains a patter for files that should not be * copied. There is a default {@link #DEFAULT_DO_NOT_COPY} but this ca be * overridden with the {@link Constants#DONOTCOPY} property. */ public boolean doNotCopy(String v) { return getDoNotCopy().matcher(v).matches(); } public Pattern getDoNotCopy() { if (xdoNotCopy == null) { String string = null; try { string = getProperty(DONOTCOPY, DEFAULT_DO_NOT_COPY); xdoNotCopy = Pattern.compile(string); } catch (Exception e) { error("Invalid value for %s, value is %s", DONOTCOPY, string); xdoNotCopy = Pattern.compile(DEFAULT_DO_NOT_COPY); } } return xdoNotCopy; } /** */ static MakeBnd makeBnd = new MakeBnd(); static MakeCopy makeCopy = new MakeCopy(); static ServiceComponent serviceComponent = new ServiceComponent(); static DSAnnotations dsAnnotations = new DSAnnotations(); static MetatypePlugin metatypePlugin = new MetatypePlugin(); @Override protected void setTypeSpecificPlugins(Set list) { list.add(makeBnd); list.add(makeCopy); list.add(serviceComponent); list.add(dsAnnotations); list.add(metatypePlugin); super.setTypeSpecificPlugins(list); } } bnd-1.50.0/biz.aQute.bndlib/src/aQute/lib/osgi/OpCodes.java0000755000175000017500000012104511656076535023127 0ustar drazzibdrazzibpackage aQute.lib.osgi; public class OpCodes { final static short nop = 0x00; // [No change] performs // no // operation final static short aconst_null = 0x01; // ? null pushes a null // reference onto the stack final static short iconst_m1 = 0x02; // ? -1 loads the int // value -1 // onto the stack final static short iconst_0 = 0x03; // ? 0 loads the int // value 0 // onto the stack final static short iconst_1 = 0x04; // ? 1 loads the int // value 1 // onto the stack final static short iconst_2 = 0x05; // ? 2 loads the int // value 2 // onto the stack final static short iconst_3 = 0x06; // ? 3 loads the int // value 3 // onto the stack final static short iconst_4 = 0x07; // ? 4 loads the int // value 4 // onto the stack final static short iconst_5 = 0x08; // ? 5 loads the int // value 5 // onto the stack final static short lconst_0 = 0x09; // ? 0L pushes the long // 0 onto // the stack final static short bipush = 0x10; // byte ? value pushes a // byte // onto the stack as an integer // value final static short sipush = 0x11; // byte1, byte2 ? value // pushes a // signed integer (byte1 << 8 + // byte2) onto the stack final static short ldc = 0x12; // index ? value pushes // a // constant #index from a // constant pool (String, int, // float or class type) onto the // stack final static short ldc_w = 0x13; // indexbyte1, // indexbyte2 ? // value pushes a constant // #index from a constant pool // (String, int, float or class // type) onto the stack (wide // index is constructed as // indexbyte1 << 8 + indexbyte2) final static short ldc2_w = 0x14; // indexbyte1, // indexbyte2 ? // value pushes a constant // #index from a constant pool // (double or long) onto the // stack (wide index is // constructed as indexbyte1 << // 8 + indexbyte2) final static short iload = 0x15; // index ? value loads // an int // value from a variable #index final static short lload = 0x16; // index ? value load a // long // value from a local variable // #index final static short fload = 0x17; // index ? value loads a // float // value from a local variable // #index final static short dload = 0x18; // index ? value loads a // double // value from a local variable // #index final static short aload = 0x19; // index ? objectref // loads a // reference onto the stack from // a local variable #index final static short lload_2 = 0x20; // ? value load a long // value // from a local variable 2 final static short lload_3 = 0x21; // ? value load a long // value // from a local variable 3 final static short fload_0 = 0x22; // ? value loads a float // value // from local variable 0 final static short fload_1 = 0x23; // ? value loads a float // value // from local variable 1 final static short fload_2 = 0x24; // ? value loads a float // value // from local variable 2 final static short fload_3 = 0x25; // ? value loads a float // value // from local variable 3 final static short dload_0 = 0x26; // ? value loads a // double from // local variable 0 final static short dload_1 = 0x27; // ? value loads a // double from // local variable 1 final static short dload_2 = 0x28; // ? value loads a // double from // local variable 2 final static short dload_3 = 0x29; // ? value loads a // double from // local variable 3 final static short faload = 0x30; // arrayref, index ? // value loads // a float from an array final static short daload = 0x31; // arrayref, index ? // value loads // a double from an array final static short aaload = 0x32; // arrayref, index ? // value loads // onto the stack a reference // from an array final static short baload = 0x33; // arrayref, index ? // value loads // a byte or Boolean value from // an array final static short caload = 0x34; // arrayref, index ? // value loads // a char from an array final static short saload = 0x35; // arrayref, index ? // value load // short from array final static short istore = 0x36; // index value ? store // int value // into variable #index final static short lstore = 0x37; // index value ? store a // long // value in a local variable // #index final static short fstore = 0x38; // index value ? stores // a float // value into a local variable // #index final static short dstore = 0x39; // index value ? stores // a double // value into a local variable // #index final static short lstore_1 = 0x40; // value ? store a long // value in // a local variable 1 final static short lstore_2 = 0x41; // value ? store a long // value in // a local variable 2 final static short lstore_3 = 0x42; // value ? store a long // value in // a local variable 3 final static short fstore_0 = 0x43; // value ? stores a // float value // into local variable 0 final static short fstore_1 = 0x44; // value ? stores a // float value // into local variable 1 final static short fstore_2 = 0x45; // value ? stores a // float value // into local variable 2 final static short fstore_3 = 0x46; // value ? stores a // float value // into local variable 3 final static short dstore_0 = 0x47; // value ? stores a // double into // local variable 0 final static short dstore_1 = 0x48; // value ? stores a // double into // local variable 1 final static short dstore_2 = 0x49; // value ? stores a // double into // local variable 2 final static short lastore = 0x50; // arrayref, index, // value ? // store a long to an array final static short fastore = 0x51; // arreyref, index, // value ? // stores a float in an array final static short dastore = 0x52; // arrayref, index, // value ? // stores a double into an array final static short aastore = 0x53; // arrayref, index, // value ? // stores into a reference to an // array final static short bastore = 0x54; // arrayref, index, // value ? // stores a byte or Boolean // value into an array final static short castore = 0x55; // arrayref, index, // value ? // stores a char into an array final static short sastore = 0x56; // arrayref, index, // value ? // store short to array final static short pop = 0x57; // value ? discards the // top // value on the stack final static short pop2 = 0x58; // {value2, value1} ? // discards // the top two values on the // stack (or one value, if it is // a double or long) final static short dup = 0x59; // value ? value, value // duplicates the value on top // of the stack final static short iadd = 0x60; // value1, value2 ? // result adds // two ints together final static short ladd = 0x61; // value1, value2 ? // result add // two longs final static short fadd = 0x62; // value1, value2 ? // result adds // two floats final static short dadd = 0x63; // value1, value2 ? // result adds // two doubles final static short isub = 0x64; // value1, value2 ? // result int // subtract final static short lsub = 0x65; // value1, value2 ? // result // subtract two longs final static short fsub = 0x66; // value1, value2 ? // result // subtracts two floats final static short dsub = 0x67; // value1, value2 ? // result // subtracts a double from // another final static short imul = 0x68; // value1, value2 ? // result // multiply two integers final static short lmul = 0x69; // value1, value2 ? // result // multiplies two longs final static short irem = 0x70; // value1, value2 ? // result // logical int remainder final static short lrem = 0x71; // value1, value2 ? // result // remainder of division of two // longs final static short frem = 0x72; // value1, value2 ? // result gets // the remainder from a division // between two floats final static short drem = 0x73; // value1, value2 ? // result gets // the remainder from a division // between two doubles final static short ineg = 0x74; // value ? result negate // int final static short lneg = 0x75; // value ? result // negates a long final static short fneg = 0x76; // value ? result // negates a // float final static short dneg = 0x77; // value ? result // negates a // double final static short ishl = 0x78; // value1, value2 ? // result int // shift left final static short lshl = 0x79; // value1, value2 ? // result // bitwise shift left of a long // value1 by value2 positions final static short ior = 0x80; // value1, value2 ? // result // logical int or final static short lor = 0x81; // value1, value2 ? // result // bitwise or of two longs final static short ixor = 0x82; // value1, value2 ? // result int // xor final static short lxor = 0x83; // value1, value2 ? // result // bitwise exclusive or of two // longs final static short iinc = 0x84; // index, const [No // change] // increment local variable // #index by signed byte const final static short i2l = 0x85; // value ? result // converts an // int into a long final static short i2f = 0x86; // value ? result // converts an // int into a float final static short i2d = 0x87; // value ? result // converts an // int into a double final static short l2i = 0x88; // value ? result // converts a // long to an int final static short l2f = 0x89; // value ? result // converts a // long to a float final static short d2f = 0x90; // value ? result // converts a // double to a float final static short i2b = 0x91; // value ? result // converts an // int into a byte final static short i2c = 0x92; // value ? result // converts an // int into a character final static short i2s = 0x93; // value ? result // converts an // int into a short final static short lcmp = 0x94; // value1, value2 ? // result // compares two longs values final static short fcmpl = 0x95; // value1, value2 ? // result // compares two floats final static short fcmpg = 0x96; // value1, value2 ? // result // compares two floats final static short dcmpl = 0x97; // value1, value2 ? // result // compares two doubles final static short dcmpg = 0x98; // value1, value2 ? // result // compares two doubles final static short ifeq = 0x99; // branchbyte1, // branchbyte2 // value ? if value is 0, branch // to instruction at // branchoffset (signed short // constructed from unsigned // bytes branchbyte1 << 8 + // branchbyte2) final static short lconst_1 = 0x0a; // ? 1L pushes the long // 1 onto // the stack final static short fconst_0 = 0x0b; // ? 0.0f pushes 0.0f on // the // stack final static short fconst_1 = 0x0c; // ? 1.0f pushes 1.0f on // the // stack final static short fconst_2 = 0x0d; // ? 2.0f pushes 2.0f on // the // stack final static short dconst_0 = 0x0e; // ? 0.0 pushes the // constant 0.0 // onto the stack final static short dconst_1 = 0x0f; // ? 1.0 pushes the // constant 1.0 // onto the stack final static short iload_0 = 0x1a; // ? value loads an int // value // from variable 0 final static short iload_1 = 0x1b; // ? value loads an int // value // from variable 1 final static short iload_2 = 0x1c; // ? value loads an int // value // from variable 2 final static short iload_3 = 0x1d; // ? value loads an int // value // from variable 3 final static short lload_0 = 0x1e; // ? value load a long // value // from a local variable 0 final static short lload_1 = 0x1f; // ? value load a long // value // from a local variable 1 final static short aload_0 = 0x2a; // ? objectref loads a // reference // onto the stack from local // variable 0 final static short aload_1 = 0x2b; // ? objectref loads a // reference // onto the stack from local // variable 1 final static short aload_2 = 0x2c; // ? objectref loads a // reference // onto the stack from local // variable 2 final static short aload_3 = 0x2d; // ? objectref loads a // reference // onto the stack from local // variable 3 final static short iaload = 0x2e; // arrayref, index ? // value loads // an int from an array final static short laload = 0x2f; // arrayref, index ? // value load // a long from an array final static short astore = 0x3a; // index objectref ? // stores a // reference into a local // variable #index final static short istore_0 = 0x3b; // value ? store int // value into // variable 0 final static short istore_1 = 0x3c; // value ? store int // value into // variable 1 final static short istore_2 = 0x3d; // value ? store int // value into // variable 2 final static short istore_3 = 0x3e; // value ? store int // value into // variable 3 final static short lstore_0 = 0x3f; // value ? store a long // value in // a local variable 0 final static short dstore_3 = 0x4a; // value ? stores a // double into // local variable 3 final static short astore_0 = 0x4b; // objectref ? stores a // reference into local variable // 0 final static short astore_1 = 0x4c; // objectref ? stores a // reference into local variable // 1 final static short astore_2 = 0x4d; // objectref ? stores a // reference into local variable // 2 final static short astore_3 = 0x4e; // objectref ? stores a // reference into local variable // 3 final static short iastore = 0x4f; // arrayref, index, // value ? // stores an int into an array final static short dup_x1 = 0x5a; // value2, value1 ? // value1, // value2, value1 inserts a copy // of the top value into the // stack two values from the top final static short dup_x2 = 0x5b; // value3, value2, // value1 ? // value1, value3, value2, // value1 inserts a copy of the // top value into the stack two // (if value2 is double or long // it takes up the entry of // value3, too) or three values // (if value2 is neither double // nor long) from the top final static short dup2 = 0x5c; // {value2, value1} ? // {value2, // value1}, {value2, value1} // duplicate top two stack words // (two values, if value1 is not // double nor long; a single // value, if value1 is double or // long) final static short dup2_x1 = 0x5d; // value3, {value2, // value1} ? // {value2, value1}, value3, // {value2, value1} duplicate // two words and insert beneath // third word (see explanation // above) final static short dup2_x2 = 0x5e; // {value4, value3}, // {value2, // value1} ? {value2, value1}, // {value4, value3}, {value2, // value1} duplicate two words // and insert beneath fourth // word final static short swap = 0x5f; // value2, value1 ? // value1, // value2 swaps two top words on // the stack (note that value1 // and value2 must not be double // or long) final static short fmul = 0x6a; // value1, value2 ? // result // multiplies two floats final static short dmul = 0x6b; // value1, value2 ? // result // multiplies two doubles final static short idiv = 0x6c; // value1, value2 ? // result // divides two integers final static short ldiv = 0x6d; // value1, value2 ? // result // divide two longs final static short fdiv = 0x6e; // value1, value2 ? // result // divides two floats final static short ddiv = 0x6f; // value1, value2 ? // result // divides two doubles final static short ishr = 0x7a; // value1, value2 ? // result int // shift right final static short lshr = 0x7b; // value1, value2 ? // result // bitwise shift right of a long // value1 by value2 positions final static short iushr = 0x7c; // value1, value2 ? // result int // shift right final static short lushr = 0x7d; // value1, value2 ? // result // bitwise shift right of a long // value1 by value2 positions, // unsigned final static short iand = 0x7e; // value1, value2 ? // result // performs a logical and on two // integers final static short land = 0x7f; // value1, value2 ? // result // bitwise and of two longs final static short l2d = 0x8a; // value ? result // converts a // long to a double final static short f2i = 0x8b; // value ? result // converts a // float to an int final static short f2l = 0x8c; // value ? result // converts a // float to a long final static short f2d = 0x8d; // value ? result // converts a // float to a double final static short d2i = 0x8e; // value ? result // converts a // double to an int final static short d2l = 0x8f; // value ? result // converts a // double to a long final static short ifne = 0x9a; // branchbyte1, // branchbyte2 // value ? if value is not 0, // branch to instruction at // branchoffset (signed short // constructed from unsigned // bytes branchbyte1 << 8 + // branchbyte2) final static short iflt = 0x9b; // branchbyte1, // branchbyte2 // value ? if value is less than // 0, branch to instruction at // branchoffset (signed short // constructed from unsigned // bytes branchbyte1 << 8 + // branchbyte2) final static short ifge = 0x9c; // branchbyte1, // branchbyte2 // value ? if value is greater // than or equal to 0, branch to // instruction at branchoffset // (signed short constructed // from unsigned bytes // branchbyte1 << 8 + // branchbyte2) final static short ifgt = 0x9d; // branchbyte1, // branchbyte2 // value ? if value is greater // than 0, branch to instruction // at branchoffset (signed short // constructed from unsigned // bytes branchbyte1 << 8 + // branchbyte2) final static short ifle = 0x9e; // branchbyte1, // branchbyte2 // value ? if value is less than // or equal to 0, branch to // instruction at branchoffset // (signed short constructed // from unsigned bytes // branchbyte1 << 8 + // branchbyte2) final static short if_icmpeq = 0x9f; // branchbyte1, // branchbyte2 // value1, value2 ? if ints are // equal, branch to instruction // at branchoffset (signed short // constructed from unsigned // bytes branchbyte1 << 8 + // branchbyte2) final static short if_icmpne = 0xa0; // branchbyte1, // branchbyte2 // value1, value2 ? if ints are // not equal, branch to // instruction at branchoffset // (signed short constructed // from unsigned bytes // branchbyte1 << 8 + // branchbyte2) final static short if_icmplt = 0xa1; // branchbyte1, // branchbyte2 // value1, value2 ? if value1 is // less than value2, branch to // instruction at branchoffset // (signed short constructed // from unsigned bytes // branchbyte1 << 8 + // branchbyte2) final static short if_icmpge = 0xa2; // branchbyte1, // branchbyte2 // value1, value2 ? if value1 is // greater than or equal to // value2, branch to instruction // at branchoffset (signed short // constructed from unsigned // bytes branchbyte1 << 8 + // branchbyte2) final static short if_icmpgt = 0xa3; // branchbyte1, // branchbyte2 // value1, value2 ? if value1 is // greater than value2, branch // to instruction at // branchoffset (signed short // constructed from unsigned // bytes branchbyte1 << 8 + // branchbyte2) final static short if_icmple = 0xa4; // branchbyte1, // branchbyte2 // value1, value2 ? if value1 is // less than or equal to value2, // branch to instruction at // branchoffset (signed short // constructed from unsigned // bytes branchbyte1 << 8 + // branchbyte2) final static short if_acmpeq = 0xa5; // branchbyte1, // branchbyte2 // value1, value2 ? if // references are equal, branch // to instruction at // branchoffset (signed short // constructed from unsigned // bytes branchbyte1 << 8 + // branchbyte2) final static short if_acmpne = 0xa6; // branchbyte1, // branchbyte2 // value1, value2 ? if // references are not equal, // branch to instruction at // branchoffset (signed short // constructed from unsigned // bytes branchbyte1 << 8 + // branchbyte2) final static short goto_ = 0xa7; // branchbyte1, // branchbyte2 [no // change] goes to another // instruction at branchoffset // (signed short constructed // from unsigned bytes // branchbyte1 << 8 + // branchbyte2) final static short jsr = 0xa8; // branchbyte1, // branchbyte2 ? // address jump to subroutine at // branchoffset (signed short // constructed from unsigned // bytes branchbyte1 << 8 + // branchbyte2) and place the // return address on the stack final static short ret = 0xa9; // index [No change] // continue // execution from address taken // from a local variable #index // (the asymmetry with jsr is // intentional) final static short tableswitch = 0xaa; // [0-3 bytes padding], // defaultbyte1, defaultbyte2, // defaultbyte3, defaultbyte4, // lowbyte1, lowbyte2, lowbyte3, // lowbyte4, highbyte1, // highbyte2, highbyte3, // highbyte4, jump offsets... // index ? continue execution // from an address in the table // at offset index final static short lookupswitch = 0xab; // <0-3 bytes padding>, // defaultbyte1, defaultbyte2, // defaultbyte3, defaultbyte4, // npairs1, npairs2, npairs3, // npairs4, match-offset // pairs... key ? a target // address is looked up from a // table using a key and // execution continues from the // instruction at that address final static short ireturn = 0xac; // value ? [empty] // returns an // integer from a method final static short lreturn = 0xad; // value ? [empty] // returns a // long value final static short freturn = 0xae; // value ? [empty] // returns a // float final static short dreturn = 0xaf; // value ? [empty] // returns a // double from a method final static short areturn = 0xb0; // objectref ? [empty] // returns a // reference from a method final static short return_ = 0xb1; // ? [empty] return void // from // method final static short getstatic = 0xb2; // index1, index2 ? // value gets a // static field value of a // class, where the field is // identified by field reference // in the constant pool index // (index1 << 8 + index2) final static short putstatic = 0xb3; // indexbyte1, // indexbyte2 value // ? set static field to value // in a class, where the field // is identified by a field // reference index in constant // pool (indexbyte1 << 8 + // indexbyte2) final static short getfield = 0xb4; // index1, index2 // objectref ? // value gets a field value of // an object objectref, where // the field is identified by // field reference in the // constant pool index (index1 // << 8 + index2) final static short putfield = 0xb5; // indexbyte1, // indexbyte2 // objectref, value ? set field // to value in an object // objectref, where the field is // identified by a field // reference index in constant // pool (indexbyte1 << 8 + // indexbyte2) final static short invokevirtual = 0xb6; // indexbyte1, // indexbyte2 // objectref, [arg1, arg2, ...] // ? invoke virtual method on // object objectref, where the // method is identified by // method reference index in // constant pool (indexbyte1 << // 8 + indexbyte2) final static short invokespecial = 0xb7; // indexbyte1, // indexbyte2 // objectref, [arg1, arg2, ...] // ? invoke instance method on // object objectref, where the // method is identified by // method reference index in // constant pool (indexbyte1 << // 8 + indexbyte2) final static short invokestatic = 0xb8; // indexbyte1, // indexbyte2 [arg1, // arg2, ...] ? invoke a static // method, where the method is // identified by method // reference index in constant // pool (indexbyte1 << 8 + // indexbyte2) final static short invokeinterface = 0xb9; // indexbyte1, // indexbyte2, // count, 0 objectref, [arg1, // arg2, ...] ? invokes an // interface method on object // objectref, where the // interface method is // identified by method // reference index in constant // pool (indexbyte1 << 8 + // indexbyte2) final static short xxxunusedxxx = 0xba; // this opcode is // reserved "for // historical reasons" final static short new_ = 0xbb; // indexbyte1, // indexbyte2 ? // objectref creates new object // of type identified by class // reference in constant pool // index (indexbyte1 << 8 + // indexbyte2) final static short newarray = 0xbc; // atype count ? // arrayref // creates new array with count // elements of primitive type // identified by atype final static short anewarray = 0xbd; // indexbyte1, // indexbyte2 count // ? arrayref creates a new // array of references of length // count and component type // identified by the class // reference index (indexbyte1 // << 8 + indexbyte2) in the // constant pool final static short arraylength = 0xbe; // arrayref ? length // gets the // length of an array final static short athrow = 0xbf; // objectref ? [empty], // objectref throws an error or // exception (notice that the // rest of the stack is cleared, // leaving only a reference to // the Throwable) final static short checkcast = 0xc0; // indexbyte1, // indexbyte2 // objectref ? objectref checks // whether an objectref is of a // certain type, the class // reference of which is in the // constant pool at index // (indexbyte1 << 8 + // indexbyte2) final static short instanceof_ = 0xc1; // indexbyte1, // indexbyte2 // objectref ? result determines // if an object objectref is of // a given type, identified by // class reference index in // constant pool (indexbyte1 << // 8 + indexbyte2) final static short monitorenter = 0xc2; // objectref ? enter // monitor for // object ("grab the lock" - // start of synchronized() // section) final static short monitorexit = 0xc3; // objectref ? exit // monitor for // object ("release the lock" - // end of synchronized() // section) final static short wide = 0xc4; // opcode, indexbyte1, // indexbyte2 final static short multianewarray = 0xc5; // indexbyte1, // indexbyte2, // dimensions count1, // [count2,...] ? arrayref // create a new array of // dimensions dimensions with // elements of type identified // by class reference in // constant pool index // (indexbyte1 << 8 + // indexbyte2); the sizes of // each dimension is identified // by count1, [count2, etc] final static short ifnull = 0xc6; // branchbyte1, // branchbyte2 // value ? if value is null, // branch to instruction at // branchoffset (signed short // constructed from unsigned // bytes branchbyte1 << 8 + // branchbyte2) final static short ifnonnull = 0xc7; // branchbyte1, // branchbyte2 // value ? if value is not null, // branch to instruction at // branchoffset (signed short // constructed from unsigned // bytes branchbyte1 << 8 + // branchbyte2) final static short goto_w = 0xc8; // branchbyte1, // branchbyte2, // branchbyte3, branchbyte4 [no // change] goes to another // instruction at branchoffset // (signed int constructed from // unsigned bytes branchbyte1 << // 24 + branchbyte2 << 16 + // branchbyte3 << 8 + // branchbyte4) final static short jsr_w = 0xc9; // branchbyte1, // branchbyte2, // branchbyte3, branchbyte4 ? // address jump to subroutine at // branchoffset (signed int // constructed from unsigned // bytes branchbyte1 << 24 + // branchbyte2 << 16 + // branchbyte3 << 8 + // branchbyte4) and place the // return address on the stack final static short breakpoint = 0xca; // reserved for // breakpoints in // Java debuggers; should not // appear in any class file final static short impdep1 = 0xfe; // reserved for // implementation-dependent // operations within debuggers; // should not appear in any // class file final static short impdep2 = 0xff; // reserved for // implementation-dependent // operations within debuggers; // should not appear in any // class file final static byte OFFSETS[] = new byte[256]; static { OFFSETS[bipush] = 1; // byte ? value pushes a byte onto the // stack as an integer value OFFSETS[sipush] = 2; // byte1, byte2 ? value pushes a signed // integer (byte1 << 8 + byte2) onto the // stack OFFSETS[ldc] = 1; // index ? value pushes a constant // #index from a constant pool (String, // int, float or class type) onto the // stack OFFSETS[ldc_w] = 2; // indexbyte1, indexbyte2 ? value pushes // a constant #index from a constant // pool (String, int, float or class // type) onto the stack (wide index is // constructed as indexbyte1 << 8 + // indexbyte2) OFFSETS[ldc2_w] = 2; // indexbyte1, indexbyte2 ? value pushes // a constant #index from a constant // pool (double or long) onto the stack // (wide index is constructed as // indexbyte1 << 8 + indexbyte2) OFFSETS[iload] = 1; // index ? value loads an int value from // a variable #index OFFSETS[lload] = 1; // index ? value load a long value from // a local variable #index OFFSETS[fload] = 1; // index ? value loads a float value // from a local variable #index OFFSETS[dload] = 1; // index ? value loads a double value // from a local variable #index OFFSETS[aload] = 1; // index ? objectref loads a reference // onto the stack from a local variable // #index OFFSETS[istore] = 1; // index value ? store int value into // variable #index OFFSETS[lstore] = 1; // index value ? store a long value in a // local variable #index OFFSETS[fstore] = 1; // index value ? stores a float value // into a local variable #index OFFSETS[dstore] = 1; // index value ? stores a double value // into a local variable #index OFFSETS[iinc] = 2; // index, const [No change] increment // local variable #index by signed byte // const OFFSETS[ifeq] = 2; // branchbyte1, branchbyte2 value ? if // value is 0, branch to instruction at // branchoffset (signed short // constructed from unsigned bytes // branchbyte1 << 8 + branchbyte2) OFFSETS[astore] = 1; // index objectref ? stores a reference // into a local variable #index OFFSETS[ifne] = 2; // branchbyte1, branchbyte2 value ? if // value is not 0, branch to instruction // at branchoffset (signed short // constructed from unsigned bytes // branchbyte1 << 8 + branchbyte2) OFFSETS[iflt] = 2; // branchbyte1, branchbyte2 value ? if // value is less than 0, branch to // instruction at branchoffset (signed // short constructed from unsigned bytes // branchbyte1 << 8 + branchbyte2) OFFSETS[ifge] = 2; // branchbyte1, branchbyte2 value ? if // value is greater than or equal to 0, // branch to instruction at branchoffset // (signed short constructed from // unsigned bytes branchbyte1 << 8 + // branchbyte2) OFFSETS[ifgt] = 2; // branchbyte1, branchbyte2 value ? if // value is greater than 0, branch to // instruction at branchoffset (signed // short constructed from unsigned bytes // branchbyte1 << 8 + branchbyte2) OFFSETS[ifle] = 2; // branchbyte1, branchbyte2 value ? if // value is less than or equal to 0, // branch to instruction at branchoffset // (signed short constructed from // unsigned bytes branchbyte1 << 8 + // branchbyte2) OFFSETS[if_icmpeq] = 2; // branchbyte1, branchbyte2 value1, // value2 ? if ints are equal, // branch to instruction at // branchoffset (signed short // constructed from unsigned bytes // branchbyte1 << 8 + branchbyte2) OFFSETS[if_icmpne] = 2; // branchbyte1, branchbyte2 value1, // value2 ? if ints are not equal, // branch to instruction at // branchoffset (signed short // constructed from unsigned bytes // branchbyte1 << 8 + branchbyte2) OFFSETS[if_icmplt] = 2; // branchbyte1, branchbyte2 value1, // value2 ? if value1 is less than // value2, branch to instruction at // branchoffset (signed short // constructed from unsigned bytes // branchbyte1 << 8 + branchbyte2) OFFSETS[if_icmpge] = 2; // branchbyte1, branchbyte2 value1, // value2 ? if value1 is greater // than or equal to value2, branch // to instruction at branchoffset // (signed short constructed from // unsigned bytes branchbyte1 << 8 + // branchbyte2) OFFSETS[if_icmpgt] = 2; // branchbyte1, branchbyte2 value1, // value2 ? if value1 is greater // than value2, branch to // instruction at branchoffset // (signed short constructed from // unsigned bytes branchbyte1 << 8 + // branchbyte2) OFFSETS[if_icmple] = 2; // branchbyte1, branchbyte2 value1, // value2 ? if value1 is less than // or equal to value2, branch to // instruction at branchoffset // (signed short constructed from // unsigned bytes branchbyte1 << 8 + // branchbyte2) OFFSETS[if_acmpeq] = 2; // branchbyte1, branchbyte2 value1, // value2 ? if references are equal, // branch to instruction at // branchoffset (signed short // constructed from unsigned bytes // branchbyte1 << 8 + branchbyte2) OFFSETS[if_acmpne] = 2; // branchbyte1, branchbyte2 value1, // value2 ? if references are not // equal, branch to instruction at // branchoffset (signed short // constructed from unsigned bytes // branchbyte1 << 8 + branchbyte2) OFFSETS[goto_] = 2; // branchbyte1, branchbyte2 [no change] // goes to another instruction at // branchoffset (signed short // constructed from unsigned bytes // branchbyte1 << 8 + branchbyte2) OFFSETS[jsr] = 2; // branchbyte1, branchbyte2 ? address // jump to subroutine at branchoffset // (signed short constructed from // unsigned bytes branchbyte1 << 8 + // branchbyte2) and place the return // address on the stack OFFSETS[ret] = 1; // index [No change] continue execution // from address taken from a local // variable #index (the asymmetry with // jsr is intentional) OFFSETS[tableswitch] = -1; // [0-3 bytes padding], // defaultbyte1, defaultbyte2, // defaultbyte3, defaultbyte4, // lowbyte1, lowbyte2, lowbyte3, // lowbyte4, highbyte1, // highbyte2, highbyte3, // highbyte4, jump offsets... // index ? continue execution // from an address in the table // at offset index OFFSETS[lookupswitch] = -1; // <0-3 bytes padding>, // defaultbyte1, defaultbyte2, // defaultbyte3, defaultbyte4, // npairs1, npairs2, npairs3, // npairs4, match-offset // pairs... key ? a target // address is looked up from a // table using a key and // execution continues from the // instruction at that address OFFSETS[getstatic] = 2; // index1, index2 ? value gets a // static field value of a class, // where the field is identified by // field reference in the constant // pool index (index1 << 8 + index2) OFFSETS[putstatic] = 2; // indexbyte1, indexbyte2 value ? // set static field to value in a // class, where the field is // identified by a field reference // index in constant pool // (indexbyte1 << 8 + indexbyte2) OFFSETS[getfield] = 2; // index1, index2 objectref ? value // gets a field value of an object // objectref, where the field is // identified by field reference in // the constant pool index (index1 // << 8 + index2) OFFSETS[putfield] = 2; // indexbyte1, indexbyte2 objectref, // value ? set field to value in an // object objectref, where the field // is identified by a field // reference index in constant pool // (indexbyte1 << 8 + indexbyte2) OFFSETS[invokevirtual] = 2; // indexbyte1, indexbyte2 // objectref, [arg1, arg2, ...] // ? invoke virtual method on // object objectref, where the // method is identified by // method reference index in // constant pool (indexbyte1 << // 8 + indexbyte2) OFFSETS[invokespecial] = 2; // indexbyte1, indexbyte2 // objectref, [arg1, arg2, ...] // ? invoke instance method on // object objectref, where the // method is identified by // method reference index in // constant pool (indexbyte1 << // 8 + indexbyte2) OFFSETS[invokestatic] = 2; // indexbyte1, indexbyte2 [arg1, // arg2, ...] ? invoke a static // method, where the method is // identified by method // reference index in constant // pool (indexbyte1 << 8 + // indexbyte2) OFFSETS[invokeinterface] = 2; // indexbyte1, indexbyte2, // count, 0 objectref, // [arg1, arg2, ...] ? // invokes an interface // method on object // objectref, where the // interface method is // identified by method // reference index in // constant pool (indexbyte1 // << 8 + indexbyte2) OFFSETS[new_] = 2; // indexbyte1, indexbyte2 ? objectref // creates new object of type identified // by class reference in constant pool // index (indexbyte1 << 8 + indexbyte2) OFFSETS[newarray] = 1; // atype count ? arrayref creates // new array with count elements of // primitive type identified by // atype OFFSETS[anewarray] = 2; // indexbyte1, indexbyte2 count ? // arrayref creates a new array of // references of length count and // component type identified by the // class reference index (indexbyte1 // << 8 + indexbyte2) in the // constant pool OFFSETS[checkcast] = 2; // indexbyte1, indexbyte2 objectref // ? objectref checks whether an // objectref is of a certain type, // the class reference of which is // in the constant pool at index // (indexbyte1 << 8 + indexbyte2) OFFSETS[instanceof_] = 2; // indexbyte1, indexbyte2 objectref // ? result determines if an object // objectref is of a given type, // identified by class reference // index in constant pool // (indexbyte1 << 8 + indexbyte2) OFFSETS[wide] = 3; // opcode, indexbyte1, indexbyte2 OFFSETS[multianewarray] = 3; // indexbyte1, indexbyte2, // dimensions count1, // [count2,...] ? arrayref // create a new array of // dimensions dimensions with // elements of type identified // by class reference in // constant pool index // (indexbyte1 << 8 + // indexbyte2); the sizes of // each dimension is identified // by count1, [count2, etc] OFFSETS[ifnull] = 2; // branchbyte1, branchbyte2 value ? if // value is null, branch to instruction // at branchoffset (signed short // constructed from unsigned bytes // branchbyte1 << 8 + branchbyte2) OFFSETS[ifnonnull] = 2; // branchbyte1, branchbyte2 value ? // if value is not null, branch to // instruction at branchoffset // (signed short constructed from // unsigned bytes branchbyte1 << 8 + // branchbyte2) OFFSETS[goto_w] = 4; // branchbyte1, branchbyte2, // branchbyte3, branchbyte4 [no change] // goes to another instruction at // branchoffset (signed int constructed // from unsigned bytes branchbyte1 << 24 // + branchbyte2 << 16 + branchbyte3 << // 8 + branchbyte4) OFFSETS[jsr_w] = 4; // branchbyte1, branchbyte2, // branchbyte3, branchbyte4 ? address // jump to subroutine at branchoffset // (signed int constructed from unsigned // bytes branchbyte1 << 24 + branchbyte2 // << 16 + branchbyte3 << 8 + // branchbyte4) and place the return // address on the stack } } bnd-1.50.0/biz.aQute.bndlib/src/aQute/lib/deployer/0000755000175000017500000000000011656076535021604 5ustar drazzibdrazzibbnd-1.50.0/biz.aQute.bndlib/src/aQute/lib/deployer/FileRepo.java0000644000175000017500000002033511656076535024157 0ustar drazzibdrazzibpackage aQute.lib.deployer; import java.io.*; import java.util.*; import java.util.jar.*; import java.util.regex.*; import aQute.bnd.service.*; import aQute.lib.io.*; import aQute.lib.osgi.*; import aQute.libg.reporter.*; import aQute.libg.version.*; public class FileRepo implements Plugin, RepositoryPlugin, Refreshable, RegistryPlugin { public static String LOCATION = "location"; public static String READONLY = "readonly"; public static String NAME = "name"; File[] EMPTY_FILES = new File[0]; protected File root; Registry registry; boolean canWrite = true; Pattern REPO_FILE = Pattern .compile("([-a-zA-z0-9_\\.]+)-([0-9\\.]+|latest)\\.(jar|lib)"); Reporter reporter; boolean dirty; String name; public FileRepo() { } public FileRepo(String name, File location, boolean canWrite) { this.name = name; this.root = location; this.canWrite = canWrite; } protected void init() throws Exception { // for extensions } public void setProperties(Map map) { String location = (String) map.get(LOCATION); if (location == null) throw new IllegalArgumentException("Location must be set on a FileRepo plugin"); root = new File(location); if (!root.isDirectory()) throw new IllegalArgumentException("Repository is not a valid directory " + root); String readonly = (String) map.get(READONLY); if (readonly != null && Boolean.valueOf(readonly).booleanValue()) canWrite = false; name = (String) map.get(NAME); } /** * Get a list of URLs to bundles that are constrained by the bsn and * versionRange. */ public File[] get(String bsn, String versionRange) throws Exception { init(); // If the version is set to project, we assume it is not // for us. A project repo will then get it. if (versionRange != null && versionRange.equals("project")) return null; // // Check if the entry exists // File f = new File(root, bsn); if (!f.isDirectory()) return null; // // The version range we are looking for can // be null (for all) or a version range. // VersionRange range; if (versionRange == null || versionRange.equals("latest")) { range = new VersionRange("0"); } else range = new VersionRange(versionRange); // // Iterator over all the versions for this BSN. // Create a sorted map over the version as key // and the file as URL as value. Only versions // that match the desired range are included in // this list. // File instances[] = f.listFiles(); SortedMap versions = new TreeMap(); for (int i = 0; i < instances.length; i++) { Matcher m = REPO_FILE.matcher(instances[i].getName()); if (m.matches() && m.group(1).equals(bsn)) { String versionString = m.group(2); Version version; if (versionString.equals("latest")) version = new Version(Integer.MAX_VALUE); else version = new Version(versionString); if (range.includes(version) || versionString.equals(versionRange)) versions.put(version, instances[i]); } } File[] files = (File[]) versions.values().toArray(EMPTY_FILES); if ("latest".equals(versionRange) && files.length > 0) { return new File[] { files[files.length - 1] }; } return files; } public boolean canWrite() { return canWrite; } public File put(Jar jar) throws Exception { init(); dirty = true; Manifest manifest = jar.getManifest(); if (manifest == null) throw new IllegalArgumentException("No manifest in JAR: " + jar); String bsn = manifest.getMainAttributes().getValue(Analyzer.BUNDLE_SYMBOLICNAME); if (bsn == null) throw new IllegalArgumentException("No Bundle SymbolicName set"); Map> b = Processor.parseHeader(bsn, null); if (b.size() != 1) throw new IllegalArgumentException("Multiple bsn's specified " + b); for (String key : b.keySet()) { bsn = key; if (!Verifier.SYMBOLICNAME.matcher(bsn).matches()) throw new IllegalArgumentException("Bundle SymbolicName has wrong format: " + bsn); } String versionString = manifest.getMainAttributes().getValue(Analyzer.BUNDLE_VERSION); Version version; if (versionString == null) version = new Version(); else version = new Version(versionString); File dir = new File(root, bsn); dir.mkdirs(); String fName = bsn + "-" + version.getMajor() + "." + version.getMinor() + "." + version.getMicro() + ".jar"; File file = new File(dir, fName); reporter.trace("Updating " + file.getAbsolutePath()); if (!file.exists() || file.lastModified() < jar.lastModified()) { jar.write(file); reporter.progress("Updated " + file.getAbsolutePath()); fireBundleAdded(jar, file); } else { reporter.progress("Did not update " + jar + " because repo has a newer version"); reporter.trace("NOT Updating " + fName + " (repo is newer)"); } File latest = new File(dir, bsn + "-latest.jar"); if (latest.exists() && latest.lastModified() < jar.lastModified()) { jar.write(latest); file = latest; } return file; } protected void fireBundleAdded(Jar jar, File file) { if (registry == null) return; List listeners = registry .getPlugins(RepositoryListenerPlugin.class); for (RepositoryListenerPlugin listener : listeners) { try { listener.bundleAdded(this, jar, file); } catch (Exception e) { if (reporter != null) reporter.warning("Repository listener threw an unexpected exception: %s", e); } } } public void setLocation(String string) { root = new File(string); if (!root.isDirectory()) throw new IllegalArgumentException("Invalid repository directory"); } public void setReporter(Reporter reporter) { this.reporter = reporter; } public List list(String regex) throws Exception { init(); Instruction pattern = null; if (regex != null) pattern = Instruction.getPattern(regex); List result = new ArrayList(); if (root == null) { if (reporter != null) reporter.error("FileRepo root directory is not set."); } else { File[] list = root.listFiles(); if (list != null) { for (File f : list) { if (!f.isDirectory()) continue; // ignore non-directories String fileName = f.getName(); if (fileName.charAt(0) == '.') continue; // ignore hidden files if (pattern == null || pattern.matches(fileName)) result.add(fileName); } } else if (reporter != null) reporter.error("FileRepo root directory (%s) does not exist", root); } return result; } public List versions(String bsn) throws Exception { init(); File dir = new File(root, bsn); if (dir.isDirectory()) { String versions[] = dir.list(); List list = new ArrayList(); for (String v : versions) { Matcher m = REPO_FILE.matcher(v); if (m.matches()) { String version = m.group(2); if (version.equals("latest")) version = Integer.MAX_VALUE+""; list.add(new Version(version)); } } return list; } return null; } public String toString() { return String.format("%-40s r/w=%s", root.getAbsolutePath(), canWrite()); } public File getRoot() { return root; } public boolean refresh() { if (dirty) { dirty = false; return true; } else return false; } public String getName() { if (name == null) { return toString(); } return name; } public File get(String bsn, String version, Strategy strategy, Map properties) throws Exception { if (version == null) version = "0.0.0"; if (strategy == Strategy.EXACT) { VersionRange vr = new VersionRange(version); if (vr.isRange()) return null; if ( vr.getHigh().getMajor() == Integer.MAX_VALUE) version = "latest"; File file = IO.getFile(root, bsn + "/" + bsn + "-" + version + ".jar"); if (file.isFile()) return file; else { file = IO.getFile(root, bsn + "/" + bsn + "-" + version + ".lib"); if (file.isFile()) return file; } return null; } File[] files = get(bsn, version); if (files == null || files.length == 0) return null; if (files.length >= 0) { switch (strategy) { case LOWEST: return files[0]; case HIGHEST: return files[files.length - 1]; } } return null; } public void setRegistry(Registry registry) { this.registry = registry; } } bnd-1.50.0/biz.aQute.bndlib/src/aQute/lib/deployer/FileInstallRepo.java0000644000175000017500000001141511656076535025505 0ustar drazzibdrazzibpackage aQute.lib.deployer; import java.io.*; import java.net.*; import java.util.*; import java.util.jar.*; import java.util.regex.*; import aQute.lib.osgi.*; import aQute.libg.reporter.*; import aQute.libg.version.*; public class FileInstallRepo extends FileRepo { String group; boolean dirty; Reporter reporter; Pattern REPO_FILE = Pattern .compile("([-a-zA-z0-9_\\.]+)-([0-9\\.]+)\\.(jar|lib)"); public void setProperties(Map map) { super.setProperties(map); group = map.get("group"); } public void setReporter(Reporter reporter) { super.setReporter(reporter); this.reporter = reporter; } public File put(Jar jar) throws Exception { dirty = true; Manifest manifest = jar.getManifest(); if (manifest == null) throw new IllegalArgumentException("No manifest in JAR: " + jar); String bsn = manifest.getMainAttributes().getValue( Analyzer.BUNDLE_SYMBOLICNAME); if (bsn == null) throw new IllegalArgumentException("No Bundle SymbolicName set"); Map> b = Processor.parseHeader(bsn, null); if (b.size() != 1) throw new IllegalArgumentException("Multiple bsn's specified " + b); for (String key : b.keySet()) { bsn = key; if (!Verifier.SYMBOLICNAME.matcher(bsn).matches()) throw new IllegalArgumentException( "Bundle SymbolicName has wrong format: " + bsn); } String versionString = manifest.getMainAttributes().getValue( Analyzer.BUNDLE_VERSION); Version version; if (versionString == null) version = new Version(); else version = new Version(versionString); File dir; if (group == null) { dir = getRoot(); } else { dir= new File(getRoot(), group); dir.mkdirs(); } String fName = bsn + "-" + version.getMajor() + "." + version.getMinor() + "." + version.getMicro() + ".jar"; File file = new File(dir, fName); jar.write(file); fireBundleAdded(jar, file); file = new File(dir, bsn + "-latest.jar"); if (file.isFile() && file.lastModified() < jar.lastModified()) { jar.write(file); } return file; } public boolean refresh() { if ( dirty ) { dirty = false; return true; } else return false; } @Override public List list(String regex) { Instruction pattern = null; if (regex != null) pattern = Instruction.getPattern(regex); String list[] = getRoot().list(); List result = new ArrayList(); for (String f : list) { Matcher m = REPO_FILE.matcher(f); if (!m.matches()) { continue; } String s = m.group(1); if (pattern == null || pattern.matches(s)) result.add(s); } return result; } @Override public File[] get(String bsn, String versionRange) throws MalformedURLException { // If the version is set to project, we assume it is not // for us. A project repo will then get it. if (versionRange != null && versionRange.equals("project")) return null; // // The version range we are looking for can // be null (for all) or a version range. // VersionRange range; if (versionRange == null || versionRange.equals("latest")) { range = new VersionRange("0"); } else range = new VersionRange(versionRange); // // Iterator over all the versions for this BSN. // Create a sorted map over the version as key // and the file as URL as value. Only versions // that match the desired range are included in // this list. // File instances[] = getRoot().listFiles(); SortedMap versions = new TreeMap(); for (int i = 0; i < instances.length; i++) { Matcher m = REPO_FILE.matcher(instances[i].getName()); if (m.matches() && m.group(1).equals(bsn)) { String versionString = m.group(2); Version version; if (versionString.equals("latest")) version = new Version(Integer.MAX_VALUE); else version = new Version(versionString); if (range.includes(version)) versions.put(version, instances[i]); } } return (File[]) versions.values().toArray(new File[versions.size()]); } } bnd-1.50.0/biz.aQute.bndlib/src/aQute/lib/deployer/obr/0000755000175000017500000000000011656076535022366 5ustar drazzibdrazzibbnd-1.50.0/biz.aQute.bndlib/src/aQute/lib/deployer/obr/Property.java0000644000175000017500000000330111656076535025052 0ustar drazzibdrazzibpackage aQute.lib.deployer.obr; /** * @immutable * @author Neil Bartlett */ public class Property { static final String PACKAGE = "package"; static final String USES = "uses"; static final String VERSION = "version"; private final String name; private final String type; private final String value; public Property(String name, String type, String value) { this.name = name; this.type = type; this.value = value; } public String getName() { return name; } public String getType() { return type; } public String getValue() { return value; } @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append("Property [name=").append(name).append(", type=").append(type).append(", value=").append(value).append("]"); return builder.toString(); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((name == null) ? 0 : name.hashCode()); result = prime * result + ((type == null) ? 0 : type.hashCode()); result = prime * result + ((value == null) ? 0 : value.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Property other = (Property) obj; if (name == null) { if (other.name != null) return false; } else if (!name.equals(other.name)) return false; if (type == null) { if (other.type != null) return false; } else if (!type.equals(other.type)) return false; if (value == null) { if (other.value != null) return false; } else if (!value.equals(other.value)) return false; return true; } } bnd-1.50.0/biz.aQute.bndlib/src/aQute/lib/deployer/obr/OBR.java0000644000175000017500000000574211656076535023663 0ustar drazzibdrazzibpackage aQute.lib.deployer.obr; import java.io.File; import java.net.MalformedURLException; import java.net.URL; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Map; import aQute.lib.deployer.FileRepo; /** * A simple read-only OBR-based repository that uses a list of index locations * and a basic local cache. * *

*

Properties

*
    *
  • locations: comma-separated list of index URLs. NB: surround with single quotes!
  • *
  • name: repository name; defaults to the index URLs. *
  • cache: local cache directory. May be omitted, in which case the repository will only be * able to serve resources with {@code file:} URLs.
  • *
  • location: (deprecated) alias for "locations". *
* *

*

Example

* *
 * -plugin: aQute.lib.deployer.obr.OBR;locations='http://www.example.com/repository.xml';cache=${workspace}/.cache
 * 
* * @author Neil Bartlett * */ public class OBR extends AbstractBaseOBR { public static final String PROP_LOCATIONS = "locations"; @Deprecated public static final String PROP_LOCATION = "location"; public static final String PROP_CACHE = "cache"; protected List locations; protected File cacheDir; public void setProperties(Map map) { super.setProperties(map); String locationsStr = map.get(PROP_LOCATIONS); // backwards compatibility if (locationsStr == null) locationsStr = map.get(PROP_LOCATION); try { if (locationsStr != null) locations = parseLocations(locationsStr); else locations = Collections.emptyList(); } catch (MalformedURLException e) { throw new IllegalArgumentException(String.format("Invalid location, unable to parse as URL list: %s", locationsStr), e); } String cacheDirStr = map.get(PROP_CACHE); if (cacheDirStr != null) cacheDir = new File(cacheDirStr); } private FileRepo lookupCachedFileRepo() { if (registry != null) { List repos = registry.getPlugins(FileRepo.class); for (FileRepo repo : repos) { if ("cache".equals(repo.getName())) return repo; } } return null; } public List getOBRIndexes() { return locations; } public synchronized File getCacheDirectory() { if (cacheDir == null) { FileRepo cacheRepo = lookupCachedFileRepo(); if (cacheRepo != null) { File temp = new File(cacheRepo.getRoot(), ".obr"); temp.mkdirs(); if (temp.exists()) cacheDir = temp; } } return cacheDir; } public void setCacheDirectory(File cacheDir) { this.cacheDir = cacheDir; } @Override public String getName() { if (name != null && name != this.getClass().getName()) return name; StringBuilder builder = new StringBuilder(); int count = 0; for (URL location : locations) { if (count++ > 0 ) builder.append(','); builder.append(location); } return builder.toString(); } public void setLocations(URL[] urls) { this.locations = Arrays.asList(urls); } } bnd-1.50.0/biz.aQute.bndlib/src/aQute/lib/deployer/obr/OBRSAXHandler.java0000644000175000017500000001004011656076535025520 0ustar drazzibdrazzibpackage aQute.lib.deployer.obr; import org.xml.sax.Attributes; import org.xml.sax.SAXException; import org.xml.sax.helpers.DefaultHandler; public class OBRSAXHandler extends DefaultHandler { private static final String TAG_RESOURCE = "resource"; private static final String ATTR_RESOURCE_ID = "id"; private static final String ATTR_RESOURCE_PRESENTATION_NAME = "presentationname"; private static final String ATTR_RESOURCE_SYMBOLIC_NAME = "symbolicname"; private static final String ATTR_RESOURCE_URI = "uri"; private static final String ATTR_RESOURCE_VERSION = "version"; private static final String TAG_REFERRAL = "referral"; private static final String ATTR_REFERRAL_URL = "url"; private static final String ATTR_REFERRAL_DEPTH = "depth"; private static final String TAG_CAPABILITY = "capability"; private static final String ATTR_CAPABILITY_NAME = "name"; private static final String TAG_REQUIRE = "require"; private static final String ATTR_REQUIRE_NAME = "name"; private static final String ATTR_REQUIRE_FILTER = "filter"; private static final String ATTR_REQUIRE_OPTIONAL = "optional"; private static final String TAG_PROPERTY = "p"; private static final String ATTR_PROPERTY_NAME = "n"; private static final String ATTR_PROPERTY_TYPE = "t"; private static final String ATTR_PROPERTY_VALUE = "v"; private final String baseUrl; private final IRepositoryListener resourceListener; private Resource.Builder resourceBuilder = null; private Capability.Builder capabilityBuilder = null; private Require require = null; private Referral referral = null; private int currentDepth; private int maxDepth; public OBRSAXHandler(String baseUrl, IRepositoryListener listener) { this.baseUrl = baseUrl; this.resourceListener = listener; this.currentDepth = 0; } public OBRSAXHandler(String baseUrl, IRepositoryListener listener, int maxDepth, int currentDepth) { this.baseUrl = baseUrl; this.resourceListener = listener; this.currentDepth = currentDepth; } @Override public void startElement(String uri, String localName, String qName, Attributes atts) throws SAXException { if (TAG_REFERRAL.equals(qName)) { referral = new Referral(atts.getValue(ATTR_REFERRAL_URL), parseInt(atts.getValue(ATTR_REFERRAL_DEPTH))); } else if (TAG_RESOURCE.equals(qName)) { resourceBuilder = new Resource.Builder() .setId(atts.getValue(ATTR_RESOURCE_ID)) .setPresentationName(atts.getValue(ATTR_RESOURCE_PRESENTATION_NAME)) .setSymbolicName(atts.getValue(ATTR_RESOURCE_SYMBOLIC_NAME)) .setUrl(atts.getValue(ATTR_RESOURCE_URI)) .setVersion(atts.getValue(ATTR_RESOURCE_VERSION)) .setBaseUrl(baseUrl); } else if (TAG_CAPABILITY.equals(qName)) { capabilityBuilder = new Capability.Builder() .setName(atts.getValue(ATTR_CAPABILITY_NAME)); } else if (TAG_REQUIRE.equals(qName)) { require = new Require(atts.getValue(ATTR_REQUIRE_NAME), atts.getValue(ATTR_REQUIRE_FILTER), "true".equalsIgnoreCase(atts.getValue(ATTR_REQUIRE_OPTIONAL))); } else if (TAG_PROPERTY.equals(qName)) { Property p = new Property(atts.getValue(ATTR_PROPERTY_NAME), atts.getValue(ATTR_PROPERTY_TYPE), atts.getValue(ATTR_PROPERTY_VALUE)); if (capabilityBuilder != null) capabilityBuilder.addProperty(p); } } @Override public void endElement(String uri, String localName, String qName) throws SAXException { if (TAG_CAPABILITY.equals(qName)) { resourceBuilder.addCapability(capabilityBuilder); capabilityBuilder = null; } else if (TAG_RESOURCE.equals(qName)) { if (!resourceListener.processResource(resourceBuilder.build())) throw new StopParseException(); resourceBuilder = null; } else if (TAG_REQUIRE.equals(qName)) { resourceBuilder.addRequire(require); require = null; } else if (TAG_REFERRAL.equals(qName)) { if (maxDepth == 0) { maxDepth = referral.getDepth(); } resourceListener.processReferral(baseUrl, referral, maxDepth, currentDepth + 1); referral = null; } } private static int parseInt(String value) { if (value == null || "".equals(value)) return 0; return Integer.parseInt(value); } } bnd-1.50.0/biz.aQute.bndlib/src/aQute/lib/deployer/obr/StopParseException.java0000644000175000017500000000025611656076535027033 0ustar drazzibdrazzibpackage aQute.lib.deployer.obr; import org.xml.sax.SAXException; public class StopParseException extends SAXException { private static final long serialVersionUID = 1L; } bnd-1.50.0/biz.aQute.bndlib/src/aQute/lib/deployer/obr/Require.java0000644000175000017500000000313311656076535024645 0ustar drazzibdrazzibpackage aQute.lib.deployer.obr; public class Require { private final String name; private final String filter; private final boolean optional; public Require(String name, String filter, boolean optional) { this.name = name; this.filter = filter; this.optional = optional; } public String getName() { return name; } public String getFilter() { return filter; } public boolean isOptional() { return optional; } @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append("Require ["); if (name != null) builder.append("name=").append(name).append(", "); if (filter != null) builder.append("filter=").append(filter).append(", "); builder.append("optional=").append(optional).append("]"); return builder.toString(); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((filter == null) ? 0 : filter.hashCode()); result = prime * result + ((name == null) ? 0 : name.hashCode()); result = prime * result + (optional ? 1231 : 1237); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Require other = (Require) obj; if (filter == null) { if (other.filter != null) return false; } else if (!filter.equals(other.filter)) return false; if (name == null) { if (other.name != null) return false; } else if (!name.equals(other.name)) return false; if (optional != other.optional) return false; return true; } } bnd-1.50.0/biz.aQute.bndlib/src/aQute/lib/deployer/obr/IRepositoryListener.java0000644000175000017500000000204711656076535027232 0ustar drazzibdrazzibpackage aQute.lib.deployer.obr; public interface IRepositoryListener { /** * Process an OBR resource descriptor from the index document, and possibly * request early termination of the parser. * * @param resource * The resource descriptor to be processed. * @return Whether to continue parsing the document; returning {@code false} * will result in the parser being stopped with a * {@link StopParseException}. */ boolean processResource(Resource resource); /** * Process an OBR referral * @param parentUrl The url of the Repository that referred to this Referral * @param referral The referral to be processed * @param maxDepth The depth of referrals this repository acknowledges. * @param currentDepth The current depth * @return Whether to continue parsing the document; returning {@code false} * will result in the parser being stopped with a * {@link StopParseException}. */ boolean processReferral(String parentUrl, Referral referral, int maxDepth, int currentDepth); } bnd-1.50.0/biz.aQute.bndlib/src/aQute/lib/deployer/obr/Capability.java0000644000175000017500000000415111656076535025313 0ustar drazzibdrazzibpackage aQute.lib.deployer.obr; import java.util.Collections; import java.util.LinkedList; import java.util.List; public class Capability { private final String name; private final List properties; private Capability(String name, List properties) { this.name = name; this.properties = properties; } public static class Builder { private String name; private final List properties = new LinkedList(); public Builder setName(String name) { this.name = name; return this; } public Builder addProperty(Property property) { this.properties.add(property); return this; } public Capability build() { if (name == null) throw new IllegalStateException("'name' field is not initialised."); return new Capability(name, Collections.unmodifiableList(properties)); } } public String getName() { return name; } public List getProperties() { return properties; } public Property findProperty(String propertyName) { assert propertyName != null; for (Property prop : properties) { if (propertyName.equals(prop.getName())) return prop; } return null; } @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append("Capability [name=").append(name).append(", properties=").append(properties).append("]"); return builder.toString(); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((name == null) ? 0 : name.hashCode()); result = prime * result + ((properties == null) ? 0 : properties.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Capability other = (Capability) obj; if (name == null) { if (other.name != null) return false; } else if (!name.equals(other.name)) return false; if (properties == null) { if (other.properties != null) return false; } else if (!properties.equals(other.properties)) return false; return true; } } bnd-1.50.0/biz.aQute.bndlib/src/aQute/lib/deployer/obr/Resource.java0000644000175000017500000001442211656076535025023 0ustar drazzibdrazzibpackage aQute.lib.deployer.obr; import java.util.Collections; import java.util.LinkedList; import java.util.List; /** * @immutable * @author Neil Bartlett */ public class Resource { private final String id; private final String presentationName; private final String symbolicName; private final String baseUrl; private final String url; private final String version; private final List capabilities; private final List requires; private Resource(String id, String presentationName, String symbolicName, String baseUrl, String url, String version, List capabilities, List requires) { this.id = id; this.presentationName = presentationName; this.symbolicName = symbolicName; this.baseUrl = baseUrl; this.url = url; this.version = version; this.capabilities = capabilities; this.requires = requires; } public static class Builder { private String id; private String presentationName; private String symbolicName; private String baseUrl; private String url; private String version; private final List capabilities = new LinkedList(); private final List requires = new LinkedList(); public Builder setId(String id) { this.id = id; return this; } public Builder setPresentationName(String presentationName) { this.presentationName = presentationName; return this; } public Builder setSymbolicName(String symbolicName) { this.symbolicName = symbolicName; return this; } public Builder setBaseUrl(String baseUrl) { this.baseUrl = baseUrl; return this; } public Builder setUrl(String url) { this.url = url; return this; } public Builder setVersion(String version) { this.version = version; return this; } public Builder addCapability(Capability capability) { this.capabilities.add(capability); return this; } public Builder addCapability(Capability.Builder capabilityBuilder) { this.capabilities.add(capabilityBuilder.build()); return this; } public Builder addRequire(Require require) { this.requires.add(require); return this; } public Resource build() { if (id == null) throw new IllegalStateException("'id' field is not initialised"); if (symbolicName == null) throw new IllegalStateException("'symbolicName' field is not initialised"); if (url == null) throw new IllegalStateException("'url' field is not initialised"); return new Resource(id, presentationName, symbolicName, baseUrl, url, version, Collections.unmodifiableList(capabilities), Collections.unmodifiableList(requires)); } } public String getId() { return id; } public String getPresentationName() { return presentationName; } public String getSymbolicName() { return symbolicName; } public String getBaseUrl() { return baseUrl; } public String getUrl() { return url; } public String getVersion() { return version; } public List getCapabilities() { return capabilities; } public Capability findPackageCapability(String pkgName) { for (Capability capability : capabilities) { if (CapabilityType.PACKAGE.getTypeName().equals(capability.getName())) { List props = capability.getProperties(); for (Property prop : props) { if (Property.PACKAGE.equals(prop.getName())) { if (pkgName.equals(prop.getValue())) return capability; else break; } } } } return null; } public List getRequires() { return requires; } public Require findRequire(String name) { for (Require require : requires) { if (name.equals(require.getName())) return require; } return null; } public Require findPackageRequire(String usesPkgName) { String matchString = String.format("(package=%s)", usesPkgName); for (Require require : requires) { if (CapabilityType.PACKAGE.getTypeName().equals(require.getName())) { String filter = require.getFilter(); if (filter.indexOf(matchString) > -1) return require; } } return null; } @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append("Resource [id=").append(id) .append(", presentationName=").append(presentationName) .append(", symbolicName=").append(symbolicName) .append(", baseUrl=").append(baseUrl) .append(", url=").append(url).append(", version=") .append(version).append(", capabilities=").append(capabilities) .append("]"); return builder.toString(); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((baseUrl == null) ? 0 : baseUrl.hashCode()); result = prime * result + ((capabilities == null) ? 0 : capabilities.hashCode()); result = prime * result + ((id == null) ? 0 : id.hashCode()); result = prime * result + ((presentationName == null) ? 0 : presentationName.hashCode()); result = prime * result + ((symbolicName == null) ? 0 : symbolicName.hashCode()); result = prime * result + ((url == null) ? 0 : url.hashCode()); result = prime * result + ((version == null) ? 0 : version.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Resource other = (Resource) obj; if (baseUrl == null) { if (other.baseUrl != null) return false; } else if (!baseUrl.equals(other.baseUrl)) return false; if (capabilities == null) { if (other.capabilities != null) return false; } else if (!capabilities.equals(other.capabilities)) return false; if (id == null) { if (other.id != null) return false; } else if (!id.equals(other.id)) return false; if (presentationName == null) { if (other.presentationName != null) return false; } else if (!presentationName.equals(other.presentationName)) return false; if (symbolicName == null) { if (other.symbolicName != null) return false; } else if (!symbolicName.equals(other.symbolicName)) return false; if (url == null) { if (other.url != null) return false; } else if (!url.equals(other.url)) return false; if (version == null) { if (other.version != null) return false; } else if (!version.equals(other.version)) return false; return true; } } bnd-1.50.0/biz.aQute.bndlib/src/aQute/lib/deployer/obr/CachingURLResourceHandle.java0000644000175000017500000001633711656076535030006 0ustar drazzibdrazzibpackage aQute.lib.deployer.obr; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.UnsupportedEncodingException; import java.net.URL; import java.net.URLEncoder; import aQute.bnd.service.ResourceHandle; import aQute.bnd.service.url.URLConnector; import aQute.lib.io.IO; import aQute.libg.reporter.Reporter; /** *

* This resource handler downloads remote resources on demand, and caches them * as local files. Resources that are already local (i.e. file:... * URLs) are returned directly. *

* *

* Two alternative caching modes are available. When the mode is * {@link CachingMode#PreferCache}, the cached file will always be returned if * it exists; therefore to refresh from the remote resource it will be necessary * to delete the cache. When the mode is {@link CachingMode#PreferRemote}, the * first call to {@link #request()} will always attempt to download the remote * resource, and only uses the pre-downloaded cache if the remote could not be * downloaded (e.g. because the network is offline). *

* * @author njbartlett * */ public class CachingURLResourceHandle implements ResourceHandle { public static enum CachingMode { /** * Always use the cached file, if it exists. */ PreferCache, /** * Download the remote resource if possible, falling back to the cached * file if remote fails. Subsequently the cached resource will be used. */ PreferRemote; } static final String FILE_SCHEME = "file:"; static final String HTTP_SCHEME = "http:"; static final String UTF_8 = "UTF-8"; final File cacheDir; final URLConnector connector; // The resolved, absolute URL of the resource final URL url; // The local file, if the resource IS a file, otherwise null. final File localFile; // The cached file copy of the resource, if it is remote and has been downloaded. final File cachedFile; final CachingMode mode; boolean downloaded = false; // only used with mode=PreferRemote Reporter reporter; public CachingURLResourceHandle(String url, String baseUrl, final File cacheDir, CachingMode mode) throws IOException { this(url, baseUrl, cacheDir, new DefaultURLConnector(), mode); } public CachingURLResourceHandle(String url, String baseUrl, final File cacheDir, URLConnector connector, CachingMode mode) throws IOException { this.cacheDir = cacheDir; this.connector = connector; this.mode = mode; if (url.startsWith(FILE_SCHEME)) { // File URL may be relative or absolute File file = new File(url.substring(FILE_SCHEME.length())); if (file.isAbsolute()) { this.localFile = file; } else { if (baseUrl == null || !baseUrl.startsWith(FILE_SCHEME)) throw new IllegalArgumentException("Relative file URLs cannot be resolved if the base URL is a non-file URL."); this.localFile = resolveFile(baseUrl.substring(FILE_SCHEME.length()), file.toString()); } this.url = localFile.toURI().toURL(); if (!localFile.isFile() && !localFile.isDirectory()) throw new FileNotFoundException("File URL " + this.url + " points at a non-existing file."); this.cachedFile = null; } else if (url.startsWith(HTTP_SCHEME)) { // HTTP URLs must be absolute this.url = new URL(url); this.localFile = null; this.cachedFile = mapRemoteURL(this.url); } else if (baseUrl == null) { // Some other scheme and no base => must be absolute this.url = new URL(url); this.localFile = null; this.cachedFile = mapRemoteURL(this.url); } else { // A path with no scheme means resolve relative to the base URL if (baseUrl.startsWith(FILE_SCHEME)) { this.localFile = resolveFile(baseUrl.substring(FILE_SCHEME.length()), url); this.url = localFile.toURI().toURL(); this.cachedFile = null; } else { URL base = new URL(baseUrl); this.url = new URL(base, url); this.localFile = null; this.cachedFile = mapRemoteURL(this.url); } } } public void setReporter(Reporter reporter) { this.reporter = reporter; } File resolveFile(String baseFileName, String fileName) { File resolved; File baseFile = new File(baseFileName); if (baseFile.isDirectory()) resolved = new File(baseFile, fileName); else if (baseFile.isFile()) resolved = new File(baseFile.getParentFile(), fileName); else throw new IllegalArgumentException("Cannot resolve relative to non-existant base file path: " + baseFileName); return resolved; } private File mapRemoteURL(URL url) throws UnsupportedEncodingException { String localDirName; String localFileName; String fullUrl = url.toExternalForm(); int lastSlashIndex = fullUrl.lastIndexOf('/'); File localDir; if (lastSlashIndex > -1) { localDirName = URLEncoder.encode(fullUrl.substring(0, lastSlashIndex), UTF_8); localDir = new File(cacheDir, localDirName); if (localDir.exists() && !localDir.isDirectory()) { localDir = cacheDir; localFileName = URLEncoder.encode(fullUrl, UTF_8); } else { localFileName = URLEncoder.encode(fullUrl.substring(lastSlashIndex + 1), UTF_8); } } else { localDir = cacheDir; localFileName = URLEncoder.encode(fullUrl, UTF_8); } localDir.mkdirs(); return new File(localDir, localFileName); } public String getName() { return url.toString(); } public Location getLocation() { Location result; if (localFile != null) result = Location.local; else if (cachedFile.exists()) result = Location.remote_cached; else result = Location.remote; return result; } public File request() throws IOException { if (localFile != null) return localFile; if (cachedFile == null) throw new IllegalStateException("Invalid URLResourceHandle: both local file and cache file location are uninitialised."); switch (mode) { case PreferCache: if (!cachedFile.exists()) { cacheDir.mkdirs(); downloadToFile(url, cachedFile); } return cachedFile; case PreferRemote: File tempFile = File.createTempFile("download", ".tmp"); try { downloadToFile(url, tempFile); // remote download succeeded... copy tmp to cache cacheDir.mkdirs(); IO.copy(tempFile, cachedFile); return cachedFile; } catch (IOException e) { // Remote download failed... use the cache if available if (cachedFile.exists()) { if (reporter != null) reporter.warning("Download of remote resource %s failed, using local cache %s.", url, cachedFile); return cachedFile; } else { throw new IOException(String.format("Download of remote resource %s failed and cached file %s not available!", url, cachedFile)); } } default: throw new IllegalArgumentException("Invalid caching mode"); } } void downloadToFile(URL url, File file) throws IOException { InputStream in = null; OutputStream out = null; try { in = connector.connect(url); out = new FileOutputStream(file); byte[] buf = new byte[1024]; for(;;) { int bytes = in.read(buf, 0, 1024); if (bytes < 0) break; out.write(buf, 0, bytes); } } finally { try { if (in != null) in.close(); } catch (IOException e) {}; try { if (out != null) in.close(); } catch (IOException e) {}; } } public URL getResolvedUrl() { return url; } } bnd-1.50.0/biz.aQute.bndlib/src/aQute/lib/deployer/obr/LocalOBR.java0000644000175000017500000001453111656076535024632 0ustar drazzibdrazzibpackage aQute.lib.deployer.obr; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.net.URL; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import javax.xml.transform.stream.StreamResult; import org.osgi.service.bindex.BundleIndexer; import org.xml.sax.InputSource; import org.xml.sax.XMLReader; import aQute.bnd.service.Refreshable; import aQute.lib.deployer.FileRepo; import aQute.lib.io.IO; import aQute.lib.osgi.Jar; import aQute.libg.reporter.Reporter; import aQute.libg.sax.SAXUtil; import aQute.libg.sax.filters.MergeContentFilter; import aQute.libg.version.Version; public class LocalOBR extends OBR implements Refreshable { public static final String PROP_LOCAL_DIR = "local"; public static final String PROP_READONLY = "readonly"; private final FileRepo storageRepo = new FileRepo(); private File storageDir; private File localIndex; private List indexUrls; @Override public void setReporter(Reporter reporter) { super.setReporter(reporter); storageRepo.setReporter(reporter); } @Override public void setProperties(Map map) { super.setProperties(map); // Load essential properties String localDirPath = map.get(PROP_LOCAL_DIR); if (localDirPath == null) throw new IllegalArgumentException(String.format("Attribute '%s' must be set on LocalOBR plugin.", PROP_LOCAL_DIR)); storageDir = new File(localDirPath); if (!storageDir.isDirectory()) throw new IllegalArgumentException(String.format("Local path '%s' does not exist or is not a directory.", localDirPath)); // Configure the storage repository Map storageRepoConfig = new HashMap(2); storageRepoConfig.put(FileRepo.LOCATION, localDirPath); storageRepoConfig.put(FileRepo.READONLY, map.get(PROP_READONLY)); storageRepo.setProperties(storageRepoConfig); // Set the local index and cache directory locations localIndex = new File(storageDir, REPOSITORY_FILE_NAME); if (localIndex.exists() && !localIndex.isFile()) throw new IllegalArgumentException(String.format("Cannot build local repository index: '%s' already exists but is not a plain file.", localIndex.getAbsolutePath())); cacheDir = new File(storageDir, ".obrcache"); if (cacheDir.exists() && !cacheDir.isDirectory()) throw new IllegalArgumentException(String.format("Cannot create repository cache: '%s' already exists but is not directory.", cacheDir.getAbsolutePath())); } @Override protected void initialiseIndexes() throws Exception { if (!localIndex.exists()) { regenerateIndex(); } try { Collection remotes = super.getOBRIndexes(); indexUrls = new ArrayList(remotes.size() + 1); indexUrls.add(localIndex.toURI().toURL()); indexUrls.addAll(remotes); } catch (IOException e) { throw new IllegalArgumentException("Error initialising local index URL", e); } } private void regenerateIndex() throws Exception { BundleIndexer indexer = registry.getPlugin(BundleIndexer.class); if (indexer == null) throw new IllegalStateException("Cannot index repository: no Bundle Indexer service or plugin found."); Set allFiles = new HashSet(); gatherFiles(allFiles); FileOutputStream out = null; try { out = new FileOutputStream(localIndex); if (!allFiles.isEmpty()) { Map config = new HashMap(); config.put(BundleIndexer.REPOSITORY_NAME, this.getName()); config.put(BundleIndexer.ROOT_URL, localIndex.getCanonicalFile().toURI().toURL().toString()); indexer.index(allFiles, out, config); } else { ByteArrayInputStream emptyRepo = new ByteArrayInputStream("\n".getBytes()); IO.copy(emptyRepo, out); } } finally { out.close(); } } private void gatherFiles(Set allFiles) throws Exception { List bsns = storageRepo.list(null); if (bsns != null) for (String bsn : bsns) { List versions = storageRepo.versions(bsn); if (versions != null) for (Version version : versions) { File file = storageRepo.get(bsn, version.toString(), Strategy.HIGHEST, null); if (file != null) allFiles.add(file.getCanonicalFile()); } } } @Override public List getOBRIndexes() { return indexUrls; } @Override public boolean canWrite() { return storageRepo.canWrite(); } @Override public synchronized File put(Jar jar) throws Exception { File newFile = storageRepo.put(jar); // Index the new file BundleIndexer indexer = registry.getPlugin(BundleIndexer.class); if (indexer == null) throw new IllegalStateException("Cannot index repository: no Bundle Indexer service or plugin found."); ByteArrayOutputStream newIndexBuffer = new ByteArrayOutputStream(); Map config = new HashMap(); config.put(BundleIndexer.REPOSITORY_NAME, this.getName()); config.put(BundleIndexer.ROOT_URL, localIndex.getCanonicalFile().toURI().toURL().toString()); indexer.index(Collections.singleton(newFile.getCanonicalFile()), newIndexBuffer, null); // Merge into main index File tempIndex = File.createTempFile("repository", ".xml"); FileOutputStream tempIndexOutput = new FileOutputStream(tempIndex); MergeContentFilter merger = new MergeContentFilter(); XMLReader reader = SAXUtil.buildPipeline(new StreamResult(tempIndexOutput), new UniqueResourceFilter(), merger); try { // Parse the newly generated index reader.parse(new InputSource(new ByteArrayInputStream(newIndexBuffer.toByteArray()))); // Parse the existing index (which may be empty/missing) try { reader.parse(new InputSource(new FileInputStream(localIndex))); } catch (Exception e) { reporter.warning("Existing local index is invalid or missing, overwriting (%s).", localIndex.getAbsolutePath()); } merger.closeRootAndDocument(); } finally { tempIndexOutput.flush(); tempIndexOutput.close(); } IO.copy(tempIndex, localIndex); // Re-read the index reset(); init(); return newFile; } public boolean refresh() { reset(); return true; } public File getRoot() { return storageDir; } } bnd-1.50.0/biz.aQute.bndlib/src/aQute/lib/deployer/obr/AbstractBaseOBR.java0000644000175000017500000004476411656076535026151 0ustar drazzibdrazzibpackage aQute.lib.deployer.obr; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Dictionary; import java.util.EnumSet; import java.util.HashMap; import java.util.Hashtable; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Properties; import java.util.Set; import java.util.SortedMap; import java.util.StringTokenizer; import java.util.TreeMap; import java.util.regex.Pattern; import javax.xml.parsers.ParserConfigurationException; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; import org.xml.sax.SAXException; import aQute.bnd.build.ResolverMode; import aQute.bnd.service.OBRIndexProvider; import aQute.bnd.service.OBRResolutionMode; import aQute.bnd.service.Plugin; import aQute.bnd.service.Registry; import aQute.bnd.service.RegistryPlugin; import aQute.bnd.service.RemoteRepositoryPlugin; import aQute.bnd.service.ResourceHandle; import aQute.bnd.service.ResourceHandle.Location; import aQute.bnd.service.url.URLConnector; import aQute.lib.deployer.obr.CachingURLResourceHandle.CachingMode; import aQute.lib.filter.Filter; import aQute.lib.osgi.Jar; import aQute.lib.osgi.URLResource; import aQute.libg.generics.Create; import aQute.libg.reporter.Reporter; import aQute.libg.version.Version; import aQute.libg.version.VersionRange; /** * Abstract base class for OBR-based repositories. * *

* The repository implementation is read-only by default. To implement a writable * repository, subclasses should override {@link #canWrite()} and {@link #put(Jar)}. * * @author Neil Bartlett * */ public abstract class AbstractBaseOBR implements RegistryPlugin, Plugin, RemoteRepositoryPlugin, OBRIndexProvider { public static final String PROP_NAME = "name"; public static final String PROP_RESOLUTION_MODE = "mode"; public static final String PROP_RESOLUTION_MODE_ANY = "any"; public static final String REPOSITORY_FILE_NAME = "repository.xml"; protected Registry registry; protected Reporter reporter; protected String name = this.getClass().getName(); protected Set supportedModes = EnumSet.allOf(OBRResolutionMode.class); private boolean initialised = false; private final Map> pkgResourceMap = new HashMap>(); private final Map> bsnMap = new HashMap>(); protected void addResourceToIndex(Resource resource) { addBundleSymbolicNameToIndex(resource); addPackagesToIndex(resource); } protected synchronized void reset() { initialised = false; } /** * Initialize the indexes prior to main initialisation of internal * data structures. This implementation does nothing, but subclasses * may override if they need to perform such initialisation. * @throws Exception */ protected void initialiseIndexes() throws Exception { } protected final synchronized void init() throws Exception { if (!initialised) { bsnMap.clear(); pkgResourceMap.clear(); initialiseIndexes(); final URLConnector connector = getConnector(); IRepositoryListener listener = new IRepositoryListener() { public boolean processResource(Resource resource) { addResourceToIndex(resource); return true; } public boolean processReferral(String fromUrl, Referral referral, int maxDepth, int currentDepth) { try { URL indexLocation = new URL(referral.getUrl()); try { CachingURLResourceHandle indexHandle = new CachingURLResourceHandle(indexLocation.toExternalForm(), null, getCacheDirectory(), connector, CachingMode.PreferRemote); indexHandle.setReporter(reporter); return readIndex(indexLocation.toString(), new FileInputStream(indexHandle.request()), this); } catch (Exception e) { reporter.error("Unable to read referral index at URL '%s' from parent index '%s': %s", indexLocation, fromUrl, e); } } catch (MalformedURLException e) { reporter.error("Invalid referral URL '%s' from parent index '%s': %s", referral.getUrl(), fromUrl, e); } return false; } }; Collection indexes = getOBRIndexes(); for (URL indexLocation : indexes) { try { CachingURLResourceHandle indexHandle = new CachingURLResourceHandle(indexLocation.toExternalForm(), null, getCacheDirectory(), connector, CachingMode.PreferRemote); indexHandle.setReporter(reporter); File indexFile = indexHandle.request(); readIndex(indexLocation.toExternalForm(), new FileInputStream(indexFile), listener); } catch (Exception e) { reporter.error("Unable to read index at URL '%s': %s", indexLocation, e); } } initialised = true; } } private URLConnector getConnector() { URLConnector connector; synchronized (this) { connector = registry.getPlugin(URLConnector.class); } if (connector == null) connector = new DefaultURLConnector(); return connector; } public synchronized final void setRegistry(Registry registry) { this.registry = registry; } public synchronized void setProperties(Map map) { if (map.containsKey(PROP_NAME)) name = map.get(PROP_NAME); if (map.containsKey(PROP_RESOLUTION_MODE)) { supportedModes = EnumSet.noneOf(OBRResolutionMode.class); StringTokenizer tokenizer = new StringTokenizer(map.get(PROP_RESOLUTION_MODE), ","); while (tokenizer.hasMoreTokens()) { String token = tokenizer.nextToken().trim(); if (PROP_RESOLUTION_MODE_ANY.equalsIgnoreCase(token)) supportedModes = EnumSet.allOf(OBRResolutionMode.class); else { try { supportedModes.add(OBRResolutionMode.valueOf(token)); } catch (Exception e) { if (reporter != null) reporter.error("Unknown OBR resolution mode: " + token); } } } } } public File[] get(String bsn, String range) throws Exception { ResourceHandle[] handles = getHandles(bsn, range); return requestAll(handles); } protected static File[] requestAll(ResourceHandle[] handles) throws IOException { File[] result = (handles == null) ? new File[0] : new File[handles.length]; for (int i = 0; i < result.length; i++) { result[i] = handles[i].request(); } return result; } protected ResourceHandle[] getHandles(String bsn, String rangeStr) throws Exception { init(); // If the range is set to "project", we cannot resolve it. if ("project".equals(rangeStr)) return null; SortedMap versionMap = bsnMap.get(bsn); if (versionMap == null || versionMap.isEmpty()) return null; List resources = narrowVersionsByVersionRange(versionMap, rangeStr); List handles = mapResourcesToHandles(resources); return (ResourceHandle[]) handles.toArray(new ResourceHandle[handles.size()]); } public synchronized void setReporter(Reporter reporter) { this.reporter = reporter; } public File get(String bsn, String range, Strategy strategy, Map properties) throws Exception { ResourceHandle handle = getHandle(bsn, range, strategy, properties); return handle != null ? handle.request() : null; } public ResourceHandle getHandle(String bsn, String range, Strategy strategy, Map properties) throws Exception { ResourceHandle result; if (bsn != null) result = resolveBundle(bsn, range, strategy); else { String pkgName = properties.get(CapabilityType.PACKAGE.getTypeName()); String modeName = properties.get(CapabilityType.MODE.getTypeName()); ResolverMode mode = (modeName != null) ? ResolverMode.valueOf(modeName) : null; if (pkgName != null) result = resolvePackage(pkgName, range, strategy, mode, properties); else throw new IllegalArgumentException("Cannot resolve bundle: neither bsn nor package specified."); } return result; } public boolean canWrite() { return false; } public File put(Jar jar) throws Exception { throw new UnsupportedOperationException("Read-only repository."); } public List list(String regex) throws Exception { init(); Pattern pattern = regex != null ? Pattern.compile(regex) : null; List result = new LinkedList(); for (String bsn : bsnMap.keySet()) { if (pattern == null || pattern.matcher(bsn).matches()) result.add(bsn); } return result; } public List versions(String bsn) throws Exception { init(); SortedMap versionMap = bsnMap.get(bsn); List list; if (versionMap != null) { list = new ArrayList(versionMap.size()); list.addAll(versionMap.keySet()); } else { list = Collections.emptyList(); } return list; } public synchronized String getName() { return name; } void addBundleSymbolicNameToIndex(Resource resource) { String bsn = resource.getSymbolicName(); Version version; String versionStr = resource.getVersion(); try { version = new Version(versionStr); } catch (Exception e) { version = new Version("0.0.0"); } SortedMap versionMap = bsnMap.get(bsn); if (versionMap == null) { versionMap = new TreeMap(); bsnMap.put(bsn, versionMap); } versionMap.put(version, resource); } void addPackagesToIndex(Resource resource) { for (Capability capability : resource.getCapabilities()) { if (CapabilityType.PACKAGE.getTypeName().equals(capability.getName())) { String pkgName = null; String versionStr = null; for (Property prop : capability.getProperties()) { if (Property.PACKAGE.equals(prop.getName())) pkgName = prop.getValue(); else if (Property.VERSION.equals(prop.getName())) versionStr = prop.getValue(); } Version version; try { version = new Version(versionStr); } catch (Exception e) { version = new Version("0.0.0"); } if (pkgName != null) { SortedMap versionMap = pkgResourceMap.get(pkgName); if (versionMap == null) { versionMap = new TreeMap(); pkgResourceMap.put(pkgName, versionMap); } versionMap.put(version, resource); } } } } /** * @return Whether to continue parsing other indexes * @throws IOException */ boolean readIndex(String baseUrl, InputStream stream, IRepositoryListener listener) throws ParserConfigurationException, SAXException, IOException { SAXParserFactory parserFactory = SAXParserFactory.newInstance(); SAXParser parser = parserFactory.newSAXParser(); try { parser.parse(stream, new OBRSAXHandler(baseUrl, listener)); return true; } catch (StopParseException e) { return false; } finally { stream.close(); } } List narrowVersionsByFilter(String pkgName, SortedMap versionMap, Filter filter) { List result = new ArrayList(versionMap.size()); Dictionary dict = new Hashtable(); dict.put("package", pkgName); for (Version version : versionMap.keySet()) { dict.put("version", version.toString()); if (filter.match(dict)) result.add(versionMap.get(version)); } return result; } List narrowVersionsByVersionRange(SortedMap versionMap, String rangeStr) { List result; if ("latest".equals(rangeStr)) { Version highest = versionMap.lastKey(); result = Create.list(new Resource[] { versionMap.get(highest) }); } else { VersionRange range = rangeStr != null ? new VersionRange(rangeStr) : null; // optimisation: skip versions definitely less than the range if (range != null && range.getLow() != null) versionMap = versionMap.tailMap(range.getLow()); result = new ArrayList(versionMap.size()); for (Version version : versionMap.keySet()) { if (range == null || range.includes(version)) result.add(versionMap.get(version)); // optimisation: skip versions definitely higher than the range if (range != null && range.isRange() && version.compareTo(range.getHigh()) >= 0) break; } } return result; } void filterResourcesByResolverMode(Collection resources, ResolverMode mode) { assert mode != null; Properties modeCapability = new Properties(); modeCapability.setProperty(CapabilityType.MODE.getTypeName(), mode.name()); for (Iterator iter = resources.iterator(); iter.hasNext(); ) { Resource resource = iter.next(); Require modeRequire = resource.findRequire(CapabilityType.MODE.getTypeName()); if (modeRequire == null) continue; else if (modeRequire.getFilter() == null) iter.remove(); else { try { Filter filter = new Filter(modeRequire.getFilter()); if (!filter.match(modeCapability)) iter.remove(); } catch (IllegalArgumentException e) { synchronized (this) { if (reporter != null) reporter.error("Error parsing mode filter requirement on resource %s: %s", resource.getUrl(), modeRequire.getFilter()); } iter.remove(); } } } } List mapResourcesToHandles(Collection resources) throws Exception { List result = new ArrayList(resources.size()); for (Resource resource : resources) { ResourceHandle handle = mapResourceToHandle(resource); if (handle != null) result.add(handle); } return result; } ResourceHandle mapResourceToHandle(Resource resource) throws Exception { ResourceHandle result = null; CachingURLResourceHandle handle ; try { handle = new CachingURLResourceHandle(resource.getUrl(), resource.getBaseUrl(), getCacheDirectory(), getConnector(), CachingMode.PreferCache); } catch (FileNotFoundException e) { throw new FileNotFoundException("Broken link in repository index: " + e.getMessage()); } if (handle.getLocation() == Location.local || getCacheDirectory() != null) result = handle; return result; } ResourceHandle resolveBundle(String bsn, String rangeStr, Strategy strategy) throws Exception { if (rangeStr == null) rangeStr = "0.0.0"; if (strategy == Strategy.EXACT) { return findExactMatch(bsn, rangeStr, bsnMap); } ResourceHandle[] handles = getHandles(bsn, rangeStr); ResourceHandle selected; if (handles == null || handles.length == 0) selected = null; else { switch(strategy) { case LOWEST: selected = handles[0]; break; default: selected = handles[handles.length - 1]; } } return selected; } ResourceHandle resolvePackage(String pkgName, String rangeStr, Strategy strategy, ResolverMode mode, Map props) throws Exception { init(); if (rangeStr == null) rangeStr = "0.0.0"; SortedMap versionMap = pkgResourceMap.get(pkgName); if (versionMap == null) return null; // Was a filter expression supplied? Filter filter = null; String filterStr = props.get("filter"); if (filterStr != null) { filter = new Filter(filterStr); } // Narrow the resources by version range string or filter. List resources; if (filter != null) resources = narrowVersionsByFilter(pkgName, versionMap, filter); else resources = narrowVersionsByVersionRange(versionMap, rangeStr); // Remove resources that are invalid for the current resolution mode if (mode != null) filterResourcesByResolverMode(resources, mode); // Select the most suitable one Resource selected; if (resources == null || resources.isEmpty()) selected = null; else { switch (strategy) { case LOWEST: selected = resources.get(0); break; default: selected = resources.get(resources.size() - 1); } expandPackageUses(pkgName, selected, props); } return selected != null ? mapResourceToHandle(selected) : null; } void expandPackageUses(String pkgName, Resource resource, Map props) { List internalUses = new LinkedList(); Map externalUses = new HashMap(); internalUses.add(pkgName); Capability capability = resource.findPackageCapability(pkgName); Property usesProp = capability.findProperty(Property.USES); if (usesProp != null) { StringTokenizer tokenizer = new StringTokenizer(usesProp.getValue(), ","); while (tokenizer.hasMoreTokens()) { String usesPkgName = tokenizer.nextToken(); Capability usesPkgCap = resource.findPackageCapability(usesPkgName); if (usesPkgCap != null) internalUses.add(usesPkgName); else { Require require = resource.findPackageRequire(usesPkgName); if (require != null) externalUses.put(usesPkgName, require); } } } props.put("packages", listToString(internalUses)); props.put("import-uses", formatPackageRequires(externalUses)); } String listToString(List list) { StringBuilder builder = new StringBuilder(); int count = 0; for (Object item : list) { if (count++ > 0) builder.append(','); builder.append(item); } return builder.toString(); } String formatPackageRequires(Map externalUses) { StringBuilder builder = new StringBuilder(); int count = 0; for (Entry entry : externalUses.entrySet()) { String pkgName = entry.getKey(); String filter = entry.getValue().getFilter(); if (count++ > 0) builder.append(','); builder.append(pkgName); builder.append(";filter='"); builder.append(filter); builder.append('\''); } return builder.toString(); } ResourceHandle findExactMatch(String identity, String version, Map> resourceMap) throws Exception { Resource resource; VersionRange range = new VersionRange(version); if (range.isRange()) return null; SortedMap versions = resourceMap.get(identity); resource = versions.get(range.getLow()); return mapResourceToHandle(resource); } /** * Utility function for parsing lists of URLs. * * @param locationsStr * Comma-separated list of URLs * @throws MalformedURLException */ protected static List parseLocations(String locationsStr) throws MalformedURLException { StringTokenizer tok = new StringTokenizer(locationsStr, ","); List urls = new ArrayList(tok.countTokens()); while (tok.hasMoreTokens()) { String urlStr = tok.nextToken().trim(); urls.add(new URL(urlStr)); } return urls; } public Set getSupportedModes() { return supportedModes; } } bnd-1.50.0/biz.aQute.bndlib/src/aQute/lib/deployer/obr/CapabilityType.java0000644000175000017500000000115711656076535026160 0ustar drazzibdrazzibpackage aQute.lib.deployer.obr; public enum CapabilityType { PACKAGE("package"), EE("ee"), BUNDLE("bundle"), MODE("mode"), OTHER(null); private String typeName; CapabilityType(String name) { this.typeName = name; } public String getTypeName() { return typeName; } /** * @throws IllegalArgumentException */ public static CapabilityType getForTypeName(String typeName) { for (CapabilityType type : CapabilityType.values()) { if (type.typeName != null && type.typeName.equals(typeName)) return type; } throw new IllegalArgumentException("Unknown capability type: " + typeName); } } bnd-1.50.0/biz.aQute.bndlib/src/aQute/lib/deployer/obr/UniqueResourceFilter.java0000644000175000017500000000266611656076535027367 0ustar drazzibdrazzibpackage aQute.lib.deployer.obr; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import org.xml.sax.Attributes; import aQute.libg.sax.filters.ElementSelectionFilter; public class UniqueResourceFilter extends ElementSelectionFilter { final Set uris = new HashSet(); final Map> filteredResources = new HashMap>(); @Override protected boolean select(int depth, String uri, String localName, String qName, Attributes attribs) { if ("resource".equals(qName)) { String resourceUri = attribs.getValue("uri"); if (uris.contains(resourceUri)) { addFilteredBundle(attribs.getValue("symbolicname"), attribs.getValue("version")); return false; } uris.add(resourceUri); } return true; } private void addFilteredBundle(String bsn, String version) { List versions = filteredResources.get(bsn); if (versions == null) { versions = new LinkedList(); filteredResources.put(bsn, versions); } versions.add(version); } public Collection getFilteredBSNs() { return filteredResources.keySet(); } public Collection getFilteredVersions(String bsn) { List list = filteredResources.get(bsn); if (list == null) list = Collections.emptyList(); return list; } } bnd-1.50.0/biz.aQute.bndlib/src/aQute/lib/deployer/obr/DefaultURLConnector.java0000644000175000017500000000057411656076535027061 0ustar drazzibdrazzibpackage aQute.lib.deployer.obr; import java.io.IOException; import java.io.InputStream; import java.net.URL; import aQute.bnd.service.url.URLConnector; public class DefaultURLConnector implements URLConnector { public InputStream connect(URL url) throws IOException { if (url == null) throw new IOException("Can't connect to null URL"); return url.openStream(); } } bnd-1.50.0/biz.aQute.bndlib/src/aQute/lib/deployer/obr/Referral.java0000644000175000017500000000220411656076535024771 0ustar drazzibdrazzibpackage aQute.lib.deployer.obr; public class Referral { private final String url; private final int depth; public Referral(String url, int depth) { this.url = url; this.depth = depth; } public String getUrl() { return url; } public int getDepth() { return depth; } @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append("Referral ["); if (url != null) builder.append("url=").append(url).append(", "); builder.append("depth=").append(depth).append(", "); return builder.toString(); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((url == null) ? 0 : url.hashCode()); result = prime * result + depth; return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Referral other = (Referral) obj; if (url == null) { if (other.url != null) return false; } else if (!url.equals(other.url)) return false; if (depth != other.depth) return false; return true; } } bnd-1.50.0/biz.aQute.bndlib/src/aQute/lib/deployer/http/0000755000175000017500000000000011656076535022563 5ustar drazzibdrazzibbnd-1.50.0/biz.aQute.bndlib/src/aQute/lib/deployer/http/HttpBasicAuthURLConnector.java0000644000175000017500000000642111656076535030372 0ustar drazzibdrazzibpackage aQute.lib.deployer.http; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.net.URLConnection; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.StringTokenizer; import java.util.concurrent.atomic.AtomicBoolean; import java.util.regex.Matcher; import aQute.bnd.service.Plugin; import aQute.bnd.service.url.URLConnector; import aQute.lib.base64.Base64; import aQute.lib.io.IO; import aQute.libg.glob.Glob; import aQute.libg.reporter.Reporter; public class HttpBasicAuthURLConnector implements URLConnector, Plugin { private static final String PREFIX_PATTERN = "pattern."; private static final String PREFIX_USER = "uid."; private static final String PREFIX_PASSWORD = "pwd."; private static class Mapping { Glob urlPattern; String user; String pass; Mapping(Glob urlPattern, String user, String pass) { this.urlPattern = urlPattern; this.user = user; this.pass = pass; } } private final AtomicBoolean inited = new AtomicBoolean(false); private final List mappings = new LinkedList(); private Reporter reporter; private String configFileList; public void setReporter(Reporter reporter) { this.reporter = reporter; } public void setProperties(Map map) { configFileList = map.get("configs"); if (configFileList == null) throw new IllegalArgumentException("'configs' must be specified on HttpBasicAuthURLConnector"); } protected void init() { if (inited.compareAndSet(false, true)) { mappings.clear(); StringTokenizer tokenizer = new StringTokenizer(configFileList, ","); while (tokenizer.hasMoreTokens()) { String configFileName = tokenizer.nextToken().trim(); File file = new File(configFileName); if (file.exists()) { Properties props = new Properties(); InputStream stream = null; try { stream = new FileInputStream(file); props.load(stream); for (Object key : props.keySet()) { String name = (String) key; if (name.startsWith(PREFIX_PATTERN)) { String id = name.substring(PREFIX_PATTERN.length()); Glob glob = new Glob(props.getProperty(name)); String uid = props.getProperty(PREFIX_USER + id); String pwd = props.getProperty(PREFIX_PASSWORD + id); mappings.add(new Mapping(glob, uid, pwd)); } } } catch (IOException e) { reporter.error("Failed to load %s", configFileName); } finally { if (stream != null) IO.close(stream); } } } } } public InputStream connect(URL url) throws IOException { init(); for (Mapping mapping : mappings) { Matcher matcher = mapping.urlPattern.matcher(url.toString()); if (matcher.find()) return connect(url, mapping.user, mapping.pass); } return url.openStream(); } private InputStream connect(URL url, String user, String pass) throws IOException { String authString = user + ":" + pass; String encoding = Base64.encodeBase64(authString.getBytes()); URLConnection connection = url.openConnection(); connection.setRequestProperty("Authorization", "Basic " + encoding); return connection.getInputStream(); } } bnd-1.50.0/biz.aQute.bndlib/src/aQute/bnd/0000755000175000017500000000000011656076535017756 5ustar drazzibdrazzibbnd-1.50.0/biz.aQute.bndlib/src/aQute/bnd/annotation/0000755000175000017500000000000011656076535022130 5ustar drazzibdrazzibbnd-1.50.0/biz.aQute.bndlib/src/aQute/bnd/annotation/component/0000755000175000017500000000000011656076535024132 5ustar drazzibdrazzibbnd-1.50.0/biz.aQute.bndlib/src/aQute/bnd/annotation/component/Activate.java0000644000175000017500000000035311656076535026536 0ustar drazzibdrazzibpackage aQute.bnd.annotation.component; import java.lang.annotation.*; @Retention(RetentionPolicy.CLASS) @Target(ElementType.METHOD) public @interface Activate { String RNAME = "LaQute/bnd/annotation/component/Activate;"; } bnd-1.50.0/biz.aQute.bndlib/src/aQute/bnd/annotation/component/Component.java0000644000175000017500000000207011656076535026736 0ustar drazzibdrazzibpackage aQute.bnd.annotation.component; import java.lang.annotation.*; @Retention(RetentionPolicy.CLASS) @Target(ElementType.TYPE) public @interface Component { String RNAME = "LaQute/bnd/annotation/component/Component;"; String PROVIDE = "provide"; String NAME = "name"; String FACTORY = "factory"; String SERVICEFACTORY = "servicefactory"; String IMMEDIATE = "immediate"; String CONFIGURATION_POLICY = "configurationPolicy"; String ENABLED = "enabled"; String PROPERTIES = "properties"; String VERSION = "version"; String DESIGNATE = "designate"; String DESIGNATE_FACTORY = "designateFactory"; String name() default ""; Class[] provide() default Object.class; String factory() default ""; boolean servicefactory() default false; boolean enabled() default true; boolean immediate() default false; ConfigurationPolicy configurationPolicy() default ConfigurationPolicy.optional; String[] properties() default {}; Class designate() default Object.class; Class designateFactory() default Object.class; } bnd-1.50.0/biz.aQute.bndlib/src/aQute/bnd/annotation/component/Deactivate.java0000644000175000017500000000035311656076535027047 0ustar drazzibdrazzibpackage aQute.bnd.annotation.component; import java.lang.annotation.*; @Retention(RetentionPolicy.CLASS) @Target(ElementType.METHOD) public @interface Deactivate { String RNAME = "LaQute/bnd/annotation/component/Deactivate;"; } bnd-1.50.0/biz.aQute.bndlib/src/aQute/bnd/annotation/component/packageinfo0000644000175000017500000000001711656076535026322 0ustar drazzibdrazzibversion 1.43.1 bnd-1.50.0/biz.aQute.bndlib/src/aQute/bnd/annotation/component/Reference.java0000644000175000017500000000142011656076535026670 0ustar drazzibdrazzibpackage aQute.bnd.annotation.component; import java.lang.annotation.*; @Retention(RetentionPolicy.CLASS) @Target(ElementType.METHOD) public @interface Reference { String RNAME = "LaQute/bnd/annotation/component/Reference;"; String NAME = "name"; String SERVICE = "service"; String OPTIONAL = "optional"; String MULTIPLE = "multiple"; String DYNAMIC = "dynamic"; String TARGET = "target"; String TYPE = "type"; String UNBIND = "unbind"; String name() default ""; Class service() default Object.class; boolean optional() default false; boolean multiple() default false; boolean dynamic() default false; String target() default ""; String unbind() default ""; char type() default 0; } bnd-1.50.0/biz.aQute.bndlib/src/aQute/bnd/annotation/component/Attribute.java0000644000175000017500000000025311656076535026740 0ustar drazzibdrazzibpackage aQute.bnd.annotation.component; public @interface Attribute { class C {} String name() default ""; String description() default ""; String[] options(); } bnd-1.50.0/biz.aQute.bndlib/src/aQute/bnd/annotation/component/ConfigurationPolicy.java0000644000175000017500000000015411656076535030764 0ustar drazzibdrazzibpackage aQute.bnd.annotation.component; public enum ConfigurationPolicy { optional, require, ignore; } bnd-1.50.0/biz.aQute.bndlib/src/aQute/bnd/annotation/component/Modified.java0000644000175000017500000000034711656076535026521 0ustar drazzibdrazzibpackage aQute.bnd.annotation.component; import java.lang.annotation.*; @Retention(RetentionPolicy.CLASS) @Target(ElementType.METHOD) public @interface Modified { String RNAME = "LaQute/bnd/annotation/component/Modified;"; } bnd-1.50.0/biz.aQute.bndlib/src/aQute/bnd/annotation/Export.java0000644000175000017500000000120011656076535024245 0ustar drazzibdrazzibpackage aQute.bnd.annotation; import java.lang.annotation.*; @Retention(RetentionPolicy.CLASS) @Target(ElementType.PACKAGE) public @interface Export { String MANDATORY = "mandatory"; String OPTIONAL = "optional"; String USES = "uses"; String EXCLUDE = "exclude"; String INCLUDE = "include"; String[] mandatory() default ""; String[] optional() default ""; Class[] exclude() default Object.class; Class[] include() default Object.class; /** * Use {@link @Version} annotation instead * @return */ @Deprecated() String version() default ""; } bnd-1.50.0/biz.aQute.bndlib/src/aQute/bnd/annotation/UsePolicy.java0000644000175000017500000000140111656076535024703 0ustar drazzibdrazzibpackage aQute.bnd.annotation; import java.lang.annotation.*; /** * This annotation can be applied to interface where an implementation should be * treated as a use policy, not an implementation policy. Many package have * interfaces that are very stable and can be maintained backward compatible for * implementers during minor changes. For example, in Event Admin, the * EventAdmin implementers should follow the minor version, e.g. [1.1,1.2), however, * an implementer of EventHandler should not require such a small range. Therefore * an interface like EventHandler should use this anotation. */ @Retention(RetentionPolicy.CLASS) @Target(ElementType.TYPE) @Deprecated public @interface UsePolicy { String RNAME = "LaQute/bnd/annotation/UsePolicy;"; } bnd-1.50.0/biz.aQute.bndlib/src/aQute/bnd/annotation/ConsumerType.java0000644000175000017500000000065511656076535025436 0ustar drazzibdrazzibpackage aQute.bnd.annotation; import java.lang.annotation.*; /** * Adding this annotation to a type in an API package indicates the the owner of * that package will not change this interface in a minor update. Any backward * compatible change to this interface requires a major update of the version of * this package. * */ @Retention(RetentionPolicy.CLASS) @Target(ElementType.TYPE) public @interface ConsumerType { } bnd-1.50.0/biz.aQute.bndlib/src/aQute/bnd/annotation/packageinfo0000644000175000017500000000001711656076535024320 0ustar drazzibdrazzibversion 1.43.1 bnd-1.50.0/biz.aQute.bndlib/src/aQute/bnd/annotation/Version.java0000644000175000017500000000025711656076535024424 0ustar drazzibdrazzibpackage aQute.bnd.annotation; import java.lang.annotation.*; @Retention(RetentionPolicy.CLASS) @Target({ElementType.PACKAGE}) public @interface Version { String value(); } bnd-1.50.0/biz.aQute.bndlib/src/aQute/bnd/annotation/metatype/0000755000175000017500000000000011656076535023760 5ustar drazzibdrazzibbnd-1.50.0/biz.aQute.bndlib/src/aQute/bnd/annotation/metatype/Meta.java0000644000175000017500000001104611656076535025513 0ustar drazzibdrazzibpackage aQute.bnd.annotation.metatype; import java.lang.annotation.*; /** * The Metadata interface provides access to the properties that underly a * Configurable interface. Any Configurable interface can implement this * interface. The interface provides the annotations that can be used to create * metatype objects. * * @ConsumerInterface */ public interface Meta { enum Type { Boolean, Byte, Character, Short, Integer, Long, Float, Double, String, Password } /** * Constant NULL for default usage */ final String NULL = "§NULL§"; /** * The OCD Annotation maps to the OCD element in the Metatype specification. * The only difference is that it is possible to create a Designate element * as well. * */ @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @interface OCD { /** * The name for this component. The default name is a the short class * name that us un-camel cased to make it more readable. * * @return The name of this component */ String name() default NULL; /** * The id of the component. Default the name of the class in FQN * notation but with nested classes using the $ as separator (not .). * * The Felix webconsole always uses this id as the PID and not the pid * in the Designate element. Reported as an error. * * @return the id */ String id() default NULL; /** * The localization prefix. The default localization prefix is the name * of the class with a $ separator for nested classes. * * @return the localization prefix. */ String localization() default NULL; /** * A description for this ocd. The default is empty. * * @return the description */ String description() default NULL; /** * Defines if this is for a factory or not. */ boolean factory() default false; } /** * The AD element in the Metatype specification. * */ @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) @interface AD { /** * A description of the attribute. Default is empty. * * @return The description of the attribute. */ String description() default NULL; /** * The name of the attribute. By default the un-camel cased version of * the method name. * * @return the name */ String name() default NULL; /** * The id of the attribute. By default the name of the method. The id is * the key used to access the properties. This is the reason the AD is a * runtime annotation so the runtime can find the proper key. * * @return the id */ String id() default NULL; /** * The type of the field. This must be one of the basic types in the * metatype specification. By default, the type is derived from the * return type of the method. This includes most collections and arrays. * Unrecognized types are defaulted to String. * * @return the type to be used. */ Type type() default Type.String; /** * The cardinality of the attribute. If not explicitly set it will be * derived from the attributes return type. Collections return * Integer.MIN_VALUE and arrays use Integer.MAX_VALUE. * * If a single string needs to be converted to a Collection or array * then the | will be used as a separator to split the line. * * @return the cardinality of the attribute */ int cardinality() default 0; /** * The minimum value. This string must be converted to the attribute * type before comparison takes place. * * @return the min value */ String min() default NULL; /** * The maximum value. This string must be converted to the attribute * type before comparison takes place. * * @return the max value */ String max() default NULL; /** * The default value. This value must be converted to the return type of * the attribute. For multi valued returns use the | as separator. * * @return the default value */ String deflt() default NULL; /** * Indicates that this attribute is required. By default attributes are * required. * * @return */ boolean required() default true; /** * Provide labels for options. These labels must match the values. If no * labels are set, the un-cameled version of the values are used (if * they are set of course). * * @return the option labels */ String[] optionLabels() default NULL; /** * The values of options. If not set and the return type is an enum * class then the values will be derived from this return type. * * @return the option labels */ String[] optionValues() default NULL; } } bnd-1.50.0/biz.aQute.bndlib/src/aQute/bnd/annotation/metatype/Configurable.java0000644000175000017500000001747111656076535027235 0ustar drazzibdrazzibpackage aQute.bnd.annotation.metatype; import java.lang.reflect.*; import java.util.*; import java.util.regex.*; public class Configurable { public static T createConfigurable(Class c, Map properties) { Object o = Proxy.newProxyInstance(c.getClassLoader(), new Class[] { c }, new ConfigurableHandler(properties, c.getClassLoader())); return c.cast(o); } public static T createConfigurable(Class c, Dictionary properties) { Map alt = new HashMap(); for( Enumeration e = properties.keys(); e.hasMoreElements(); ) { Object key = e.nextElement(); alt.put(key, properties.get(key)); } return createConfigurable(c, alt); } static class ConfigurableHandler implements InvocationHandler { final Map properties; final ClassLoader loader; ConfigurableHandler(Map properties, ClassLoader loader) { this.properties = properties; this.loader = loader; } public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { Meta.AD ad = method.getAnnotation(Meta.AD.class); String id = Configurable.mangleMethodName(method.getName()); if (ad != null && !ad.id().equals(Meta.NULL)) id = ad.id(); Object o = properties.get(id); if (o == null) { if (ad != null) { if (ad.required()) throw new IllegalStateException("Attribute is required but not set " + method.getName()); o = ad.deflt(); if (o.equals(Meta.NULL)) o = null; } } if (o == null) { if (method.getReturnType().isPrimitive() || Number.class.isAssignableFrom(method.getReturnType())) { o = "0"; } else return null; } return convert(method.getGenericReturnType(), o); } @SuppressWarnings( { "unchecked" }) public Object convert(Type type, Object o) throws Exception { if (type instanceof ParameterizedType) { ParameterizedType pType = (ParameterizedType) type; return convert(pType, o); } if (type instanceof GenericArrayType) { GenericArrayType gType = (GenericArrayType) type; return convertArray(gType.getGenericComponentType(), o); } Class resultType = (Class) type; if (resultType.isArray()) { return convertArray(resultType.getComponentType(), o); } Class actualType = o.getClass(); if (actualType.isAssignableFrom(resultType)) return o; if (resultType == boolean.class || resultType == Boolean.class) { if ( actualType == boolean.class || actualType == Boolean.class) return o; if (Number.class.isAssignableFrom(actualType)) { double b = ((Number) o).doubleValue(); if (b == 0) return false; else return true; } return true; } else if (resultType == byte.class || resultType == Byte.class) { if (Number.class.isAssignableFrom(actualType)) return ((Number) o).byteValue(); resultType = Byte.class; } else if (resultType == char.class) { resultType = Character.class; } else if (resultType == short.class) { if (Number.class.isAssignableFrom(actualType)) return ((Number) o).shortValue(); resultType = Short.class; } else if (resultType == int.class) { if (Number.class.isAssignableFrom(actualType)) return ((Number) o).intValue(); resultType = Integer.class; } else if (resultType == long.class) { if (Number.class.isAssignableFrom(actualType)) return ((Number) o).longValue(); resultType = Long.class; } else if (resultType == float.class) { if (Number.class.isAssignableFrom(actualType)) return ((Number) o).floatValue(); resultType = Float.class; } else if (resultType == double.class) { if (Number.class.isAssignableFrom(actualType)) return ((Number) o).doubleValue(); resultType = Double.class; } if (resultType.isPrimitive()) throw new IllegalArgumentException("Unknown primitive: " + resultType); if (Number.class.isAssignableFrom(resultType) && actualType == Boolean.class) { Boolean b = (Boolean) o; o = b ? "1" : "0"; } else if (actualType == String.class) { String input = (String) o; if (Enum.class.isAssignableFrom(resultType)) { return Enum.valueOf((Class) resultType, input); } if (resultType == Class.class && loader != null) { return loader.loadClass(input); } if (resultType == Pattern.class) { return Pattern.compile(input); } } try { Constructor c = resultType.getConstructor(String.class); return c.newInstance(o.toString()); } catch (Throwable t) { // handled on next line } throw new IllegalArgumentException("No conversion to " + resultType + " from " + actualType + " value " + o); } private Object convert(ParameterizedType pType, Object o) throws InstantiationException, IllegalAccessException, Exception { Class resultType = (Class) pType.getRawType(); if (Collection.class.isAssignableFrom(resultType)) { Collection input = toCollection(o); if (resultType.isInterface()) { if (resultType == Collection.class || resultType == List.class) resultType = ArrayList.class; else if (resultType == Set.class || resultType == SortedSet.class) resultType = TreeSet.class; else if (resultType == Queue.class /*|| resultType == Deque.class*/) resultType = LinkedList.class; else if (resultType == Queue.class /*|| resultType == Deque.class*/) resultType = LinkedList.class; else throw new IllegalArgumentException( "Unknown interface for a collection, no concrete class found: " + resultType); } @SuppressWarnings("unchecked") Collection result = (Collection) resultType .newInstance(); Type componentType = pType.getActualTypeArguments()[0]; for (Object i : input) { result.add(convert(componentType, i)); } return result; } else if (pType.getRawType() == Class.class) { return loader.loadClass(o.toString()); } throw new IllegalArgumentException("cannot convert to " + pType + " because it uses generics and is not a Collection"); } Object convertArray(Type componentType, Object o) throws Exception { Collection input = toCollection(o); Class componentClass = getRawClass(componentType); Object array = Array.newInstance(componentClass, input.size()); int i = 0; for (Object next : input) { Array.set(array, i++, convert(componentType, next)); } return array; } private Class getRawClass(Type type) { if (type instanceof Class) return (Class) type; if (type instanceof ParameterizedType) return (Class) ((ParameterizedType) type).getRawType(); throw new IllegalArgumentException( "For the raw type, type must be ParamaterizedType or Class but is " + type); } private Collection toCollection(Object o) { if (o instanceof Collection) return (Collection) o; if (o.getClass().isArray()) { if ( o.getClass().getComponentType().isPrimitive()) { int length = Array.getLength(o); List result = new ArrayList(length); for ( int i=0; i0) return Arrays.asList(s.split("\\|")); } return Arrays.asList(o); } } public static String mangleMethodName(String id) { StringBuilder sb = new StringBuilder(id); for ( int i =0; i>", Pattern.compile("(" + Verifier.URLPATTERN + "|<>)"), new Syntax( DESCRIPTION_ATTRIBUTE, "Human readable description of the license", "description=\"Described the license here\"", null, Verifier.ANYPATTERN), new Syntax(LINK_ATTRIBUTE, "", "", null, Verifier.URLPATTERN)), new Syntax( BUNDLE_LOCALIZATION, "The Bundle-Localization header contains the location in the bundle where localization files can be found. The default value is OSGI-INF/l10n/bundle. Translations are by default therefore OSGI-INF/l10n/bundle_de.properties, OSGI-INF/l10n/bundle_nl.properties, etc.", "Bundle-Localization: OSGI-INF/l10n/bundle", "OSGI-INF/l10n/bundle", Verifier.URLPATTERN), new Syntax( BUNDLE_MANIFESTVERSION, "This header is set by bnd automatically to 2. The Bundle-ManifestVersion header defines that the bundle follows the rules of this specification. The Bundle-ManifestVersion header determines whether the bundle follows the rules of this specification.", "# Bundle-ManifestVersion: 2", "2", Verifier.NUMBERPATTERN), new Syntax( BUNDLE_NAME, "This header will be derived from the Bundle-SymbolicName if not set. The Bundle-Name header defines a readable name for this bundle. This should be a short, human-readable name that can contain spaces.", "Bundle-Name: My Bundle", null, Verifier.ANYPATTERN), new Syntax( BUNDLE_NATIVECODE, "The Bundle-NativeCode header contains a specification of native code libraries contained in this bundle. ", "Bundle-NativeCode: /lib/http.DLL; osname = QNX; osversion = 3.1", null, Verifier.PATHPATTERN, new Syntax(OSNAME_ATTRIBUTE, "The name of the operating system", "osname=MacOS", Processor.join(Verifier.OSNAMES, ","), Verifier.ANYPATTERN), new Syntax(OSVERSION_ATTRIBUTE, "Operating System Version", "osversion=3.1", null, Verifier.ANYPATTERN), new Syntax(LANGUAGE_ATTRIBUTE, "Language ISO 639 code", "language=nl", null, Verifier.ISO639), new Syntax(PROCESSOR_ATTRIBUTE, "Processor name", "processor=x86", Processor.join( Verifier.PROCESSORNAMES, ","), Verifier.ANYPATTERN), new Syntax( SELECTION_FILTER_ATTRIBUTE, "The value of this attribute must be a filter expression that indicates if the native code clause should be selected or not.", "selection-filter=\"(com.acme.windowing=win32)\"", null, Verifier.FILTERPATTERN)), new Syntax( BUNDLE_REQUIREDEXECUTIONENVIRONMENT, "The Bundle-RequiredExecutionEnvironment contains a comma-separated list of execution environments that must be present on the Service Platform.", "Bundle-RequiredExecutionEnvironment: CDC-1.0/Foundation-1.0", Processor.join(Verifier.EES, ","), Verifier.ANYPATTERN), new Syntax( BUNDLE_SYMBOLICNAME, "The Bundle-SymbolicName header specifies a non-localizable name for this bundle. The bundle symbolic name together with a version must identify a unique bundle. The bundle symbolic name should be based on the reverse domain name convention", "Bundle-SymbolicName: com.acme.foo.daffy;singleton:=true", "${p}", Verifier.SYMBOLICNAME, new Syntax( SINGLETON_DIRECTIVE, " Indicates that the bundle can only have a single version resolved. A value of true indicates that the bundle is a singleton bundle. The default value is false. The Framework must resolve at most one bundle when multiple versions of a singleton bundle with the same symbolic name are installed. Singleton bundles do not affect the resolution of non-singleton bundles with the same symbolic name.", "false", "true,false", Verifier.TRUEORFALSEPATTERN), new Syntax( FRAGMENT_ATTACHMENT_DIRECTIVE, "Defines how fragments are allowed to be attached, see the fragments in Fragment Bundles on page73. The following values are valid for this directive:", "", "always|never|resolve-time", Pattern .compile("always|never|resolve-time")), new Syntax(BLUEPRINT_WAIT_FOR_DEPENDENCIES_ATTRIBUTE, "", "", "true,false", Verifier.TRUEORFALSEPATTERN), new Syntax(BLUEPRINT_TIMEOUT_ATTRIBUTE, "", "", "30000,60000,300000", Verifier.NUMBERPATTERN)), new Syntax( BUNDLE_UPDATELOCATION, "The Bundle-UpdateLocation header specifies a URL where an update for this bundle should come from. If the bundle is updated, this location should be used, if present, to retrieve the updated JAR file.", "Bundle-UpdateLocation: http://www.acme.com/Firewall/bundle.jar", null, Verifier.URLPATTERN), new Syntax( BUNDLE_VENDOR, "The Bundle-Vendor header contains a human-readable description of the bundle vendor. ", "Bundle-Vendor: OSGi Alliance ", null, null), new Syntax( BUNDLE_VERSION, "The Bundle-Version header specifies the version of this bundle", "Bundle-Version: 1.23.4.build200903221000", null, Verifier.VERSION), new Syntax( DYNAMICIMPORT_PACKAGE, "The DynamicImport-Package header contains a comma-separated list of package names that should be dynamically imported when needed.", "DynamicImport-Package: com.acme.plugin.*", "", Verifier.WILDCARDNAMEPATTERN, version, bundle_symbolic_name, bundle_version), new Syntax( EXPORT_PACKAGE, "The Export-Package header contains a declaration of exported packages.", "Export-Package: org.osgi.util.tracker;version=1.3", "${packages}", null, new Syntax( NO_IMPORT_DIRECTIVE, "By default, bnd makes all exports also imports. Adding a -noimport to an exported package will make it export only", "-noimport:=true", "true,false", Verifier.TRUEORFALSEPATTERN), new Syntax( USES_DIRECTIVE, "Calculated by bnd: It is a comma-separated list of package names that are used by the exported package", "Is calculated by bnd", null, null), new Syntax( MANDATORY_DIRECTIVE, "A comma-separated list of attribute names. Note that the use of a comma in the value requires it to be enclosed in double quotes. A bundle importing the package must specify the mandatory attributes, with a value that matches, to resolve to the exported package", "mandatory=\"bar,foo\"", null, null), new Syntax( INCLUDE_DIRECTIVE, "A comma-separated list of class names that must be visible to an importer", "include:=\"Qux*\"", null, null), new Syntax( EXCLUDE_DIRECTIVE, "A comma-separated list of class names that must not be visible to an importer", "exclude:=\"QuxImpl*,BarImpl\"", null, Verifier.WILDCARDNAMEPATTERN), new Syntax( IMPORT_DIRECTIVE, "Experimental", "", null, null) ), new Syntax(EXPORT_SERVICE, "Deprecated", "Export-Service: org.osgi.service.log.LogService ", "${classes;implementing;*}", null), new Syntax( FRAGMENT_HOST, "The Fragment-Host header defines the host bundle for this fragment.", "Fragment-Host: org.eclipse.swt; bundle-version=\"[3.0.0,4.0.0)\"", null, null, new Syntax( EXTENSION_DIRECTIVE, " Indicates this extension is a system or boot class path extension. It is only applicable when the Fragment-Host is the System Bundle", "extension:=framework", "framework,bootclasspath", Pattern.compile("framework|bootclasspath")), bundle_version), new Syntax( IMPORT_PACKAGE, "This header is normally calculated by bnd, however, you can decorate packages or skip packages. The Import-Package header declares the imported packages for this bundle", "Import-Package: !com.exotic.*, com.acme.foo;vendor=ACME, *", "${exported_packages}", Verifier.WILDCARDNAMEPATTERN, new Syntax( REMOVE_ATTRIBUTE_DIRECTIVE, "Remove the given attributes from matching imported packages", "-remove-attribute:=foo.*", null, Verifier.WILDCARDNAMEPATTERN), new Syntax( RESOLUTION_DIRECTIVE, "Indicates that the packages must be resolved if the value is mandatory, which is the default. If mandatory packages cannot be resolved, then the bundle must fail to resolve. A value of optional indicates that the packages are optional", "resolution:=optional", "mandatory,optional", Pattern.compile("mandatory|optional") ), version, bundle_symbolic_name, bundle_version), new Syntax( REQUIRE_BUNDLE, "The Require-Bundle header specifies the required exports from another bundle.", "Require-Bundle: com.acme.chess", null, Verifier.WILDCARDNAMEPATTERN, new Syntax( VISIBILITY_DIRECTIVE, " If the value is private (Default), then all visible packages from the required bundles are not re-exported. If the value is reexport then bundles that require this bundle will transitively have access to these required bundle’s exported packages.", "visibility:=private", "private,reexport", Pattern .compile("private|reexport")), new Syntax( RESOLUTION_DIRECTIVE, "If the value is mandatory (default) then the required bundle must exist for this bundle to resolve. If the value is optional, the bundle will resolve even if the required bundle does not exist.", "resolution:=optional", "mandatory,optional", Pattern.compile("mandatory|optional")), new Syntax( SPLIT_PACKAGE_DIRECTIVE, "Indicates how an imported package should be merged when it is split between different exporters. The default is merge-first with warning", "-split-package:=merge-first", "merge-first,merge-last,error,first", Pattern .compile("merge-first|merge-last|error|first")), bundle_version ), new Syntax( BUILDPATH, "Provides the class path for building the jar. The entries are references to the repository", "-buildpath=osgi;version=4.1", "${repo;bsns}", Verifier.SYMBOLICNAME, path_version), new Syntax( BUMPPOLICY, "Sets the version bump policy. This is a parameter to the ${version} macro.", "-bumppolicy==+0", "==+,=+0,+00", Pattern .compile("[=+-0][=+-0][=+-0]")), new Syntax( CONDUIT, "Allows a bnd file to point to files which will be returned when the bnd file is build", "-conduit= jar/osgi.jar", null, null), new Syntax( DEPENDSON, "List of project names that this project directly depends on. These projects are always build ahead of this project", "-dependson=org.acme.cm", "${projects}", null), new Syntax(DEPLOYREPO, "Specifies to which repo the project should be deployed.", "-deployrepo=cnf", "${repos}", null), new Syntax( DONOTCOPY, "Regular expression for names of files and directories that should not be copied when discovered", "-donotcopy=(CVS|\\.svn)", null, null), new Syntax( EXPORT_CONTENTS, "Build the JAR in the normal way but use this header for the Export-Package header manifest generation, same format", "-exportcontents=!*impl*,*;version=3.0", null, null), new Syntax( FAIL_OK, "Return with an ok status (0) even if the build generates errors", "-failok=true", "true,false", Verifier.TRUEORFALSEPATTERN), new Syntax( INCLUDE, "Include files. If an entry starts with '-', it does not have to exist. If it starts with '~', it must not overwrite any existing properties", "-include: -${java.user}/.bnd", null, null), new Syntax( INCLUDERESOURCE, "Include resources from the file system. You can specify a directory, or file. All files are copied to the root, unless a destination directory is indicated", "-includeresource: lib=jar", null, null), new Syntax( MAKE, "Set patterns for make plugins. These patterns are used to find a plugin that can make a resource that can not be found.", "-make: (*).jar;type=bnd; recipe=\"bnd/$1.bnd\"", null, null, new Syntax("type", "Type name for plugin", "type=bnd", "bnd", null), new Syntax("recipe", "Recipe for the plugin, can use back references", "recipe=\"bnd/$1.bnd\"", "bnd", null)), new Syntax( MANIFEST, "Directly include a manifest, do not use the calculated manifest", "-manifest = META-INF/MANIFEST.MF", null, null), new Syntax(NOEXTRAHEADERS, "Do not generate housekeeping headers", "-noextraheaders", "true,false", Verifier.TRUEORFALSEPATTERN), new Syntax(NOUSES, "Do not calculate the uses: directive on exports", "-nouses=true", "true,false", Verifier.TRUEORFALSEPATTERN), new Syntax(NOPE, "Deprecated, use -nobundles. ", "-nope=true", "true,false", Verifier.TRUEORFALSEPATTERN), new Syntax( PEDANTIC, "Warn about things that are not really wrong but still not right", "-nope=true", "true,false", Verifier.TRUEORFALSEPATTERN), new Syntax( PLUGIN, "Define the plugins", "-plugin=aQute.lib.spring.SpringComponent,aQute.lib.deployer.FileRepo;location=${repo}", null, null), new Syntax(SERVICE_COMPONENT, "The header for Declarative Services", "Service-Component=com.acme.Foo?;activate='start'", null, null), new Syntax(POM, "Generate a maven pom", "-pom=true", "true,false", Verifier.TRUEORFALSEPATTERN), new Syntax(RELEASEREPO, "Specifies to which repo the project should be released.", "-releaserepo=cnf", "${repos}", null), new Syntax(REMOVEHEADERS, "Remove all headers that match the regular expressions", "-removeheaders=FOO_.*,Proprietary", null, null), new Syntax( RESOURCEONLY, "Normally bnd warns when the JAR does not contain any classes, this option suppresses this warning", "-resourceonly=true", "true,false", Verifier.TRUEORFALSEPATTERN), new Syntax(SOURCES, "Include sources in the jar", "-sources=true", "true,false", Verifier.TRUEORFALSEPATTERN), new Syntax( SOURCEPATH, "List of directory names that used to source sources for -sources", "-sourcepath:= src, test", null, null), new Syntax( SUB, "Build a set of bnd files that use this bnd file as a basis. The list of bnd file can be specified with wildcards", "-sub=com.acme.*.bnd", null, null), new Syntax( RUNPROPERTIES, "Properties that are set as system properties before the framework is started", "-runproperties= foo=3, bar=4", null, null), new Syntax(RUNSYSTEMPACKAGES, "Add additional system packages to a framework run", "-runsystempackages=com.acme.foo,javax.management", null, null), new Syntax( RUNBUNDLES, "Add additional bundles, specified with their bsn and version like in -buildpath, that are started before the project is run", "-runbundles=osgi;version=\"[4.1,4.2)\", junit.junit, com.acme.foo;version=project", null, Verifier.SYMBOLICNAME, path_version), new Syntax( RUNPATH, "Additional JARs for the VM path, should include the framework", "-runpath=org.eclipse.osgi;version=3.5", null, null, path_version), new Syntax( RUNVM, "Additional arguments for the VM invokation. Keys that start with a - are added as options, otherwise they are treated as -D properties for the VM", "-runvm=-Xmax=30", null, null), new Syntax( VERSIONPOLICY, "Provides a version policy to imports that are calculated from exports", "-versionpolicy = \"[${version;==;${@}},${version;+;${@}})\"", null, null) }; public final static Map HELP = new HashMap(); static { for (Syntax s : syntaxes) { HELP.put(s.header, s); } } public Syntax(String header, String lead, String example, String values, Pattern pattern, Syntax... children) { this.header = header; this.children = children; this.lead = lead; this.example = example; this.values = values; this.pattern = pattern; } public String getLead() { return lead; } public String getExample() { return example; } public String getValues() { return values; } public String getPattern() { return lead; } public Syntax[] getChildren() { return children; } public String getHeader() { return header; } } bnd-1.50.0/biz.aQute.bndlib/src/aQute/bnd/help/syntax.properties0000644000175000017500000010032211656076535024350 0ustar drazzibdrazzibAdd=Holders of DmtPermission with the Add action present can create new nodes in the DMT, that is they are authorized to execute the createInteriorNode() and createLeafNode() methods of the DmtSession. Delete=Holders of DmtPermission with the Delete action present can delete nodes from the DMT, that is they are authorized to execute the deleteNode() method of the DmtSession. Exec=Holders of DmtPermission with the Exec action present can execute nodes in the DMT, that is they are authorized to call the execute() method of the DmtSession. Get=Holders of DmtPermission with the Get action present can query DMT node value or properties, that is they are authorized to execute the isLeafNode(), getNodeAcl(), getEffectiveNodeAcl(), getMetaNode(), getNodeValue(), getChildNodeNames(), getNodeTitle(), getNodeVersion(), getNodeTimeStamp(), getNodeSize() and getNodeType() methods of the DmtSession. Replace=Holders of DmtPermission with the Replace action present can update DMT node value or properties, that is they are authorized to execute the setNodeAcl(), setNodeTitle(), setNodeValue(), setNodeType() and renameNode() methods of the DmtSession. get=The action string get. register=The action string register. export=The action string export. exportonly=The action string exportonly. import=The action string import. System Bundle=Location identifier of the OSGi system bundle , which is defined to be "System Bundle". system.bundle=Alias for the symbolic name of the OSGi system bundle . Bundle-Category=Manifest header identifying the bundle's category. Bundle-ClassPath=Manifest header identifying a list of directories and embedded JAR files, which are bundle resources used to extend the bundle's classpath. Bundle-Copyright=Manifest header identifying the bundle's copyright information. Bundle-Description=Manifest header containing a brief description of the bundle's functionality. Bundle-Name=Manifest header identifying the bundle's name. Bundle-NativeCode=Manifest header identifying a number of hardware environments and the native language code libraries that the bundle is carrying for each of these environments. Export-Package=Manifest header identifying the packages that the bundle offers to the Framework for export. Export-Service=Manifest header identifying the fully qualified class names of the services that the bundle may register (used for informational purposes only). Import-Package=Manifest header identifying the packages on which the bundle depends. DynamicImport-Package=Manifest header identifying the packages that the bundle may dynamically import during execution. Import-Service=Manifest header identifying the fully qualified class names of the services that the bundle requires (used for informational purposes only). Bundle-Vendor=Manifest header identifying the bundle's vendor. Bundle-Version=Manifest header identifying the bundle's version. Bundle-DocURL=Manifest header identifying the bundle's documentation URL, from which further information about the bundle may be obtained. Bundle-ContactAddress=Manifest header identifying the contact address where problems with the bundle may be reported; for example, an email address. Bundle-Activator=Manifest header attribute identifying the bundle's activator class. Bundle-UpdateLocation=Manifest header identifying the location from which a new bundle version is obtained during a bundle update operation. specification-version=Manifest header attribute identifying the version of a package specified in the Export-Package or Import-Package manifest header. processor=Manifest header attribute identifying the processor required to run native bundle code specified in the Bundle-NativeCode manifest header). osname=Manifest header attribute identifying the operating system required to run native bundle code specified in the Bundle-NativeCode manifest header). osversion=Manifest header attribute identifying the operating system version required to run native bundle code specified in the Bundle-NativeCode manifest header). language=Manifest header attribute identifying the language in which the native bundle code is written specified in the Bundle-NativeCode manifest header. Bundle-RequiredExecutionEnvironment=Manifest header identifying the required execution environment for the bundle. Bundle-SymbolicName=Manifest header identifying the bundle's symbolic name. singleton=Manifest header directive identifying whether a bundle is a singleton. fragment-attachment=Manifest header directive identifying if and when a fragment may attach to a host bundle. always=Manifest header directive value identifying a fragment attachment type of always. resolve-time=Manifest header directive value identifying a fragment attachment type of resolve-time. never=Manifest header directive value identifying a fragment attachment type of never. Bundle-Localization=Manifest header identifying the base name of the bundle's localization entries. OSGI-INF/l10n/bundle=Default value for the Bundle-Localization manifest header. Require-Bundle=Manifest header identifying the symbolic names of other bundles required by the bundle. bundle-version=Manifest header attribute identifying a range of versions for a bundle specified in the Require-Bundle or Fragment-Host manifest headers. Fragment-Host=Manifest header identifying the symbolic name of another bundle for which that the bundle is a fragment. selection-filter=Manifest header attribute is used for selection by filtering based upon system properties. Bundle-ManifestVersion=Manifest header identifying the bundle manifest version. version=Manifest header attribute identifying the version of a package specified in the Export-Package or Import-Package manifest header. bundle-symbolic-name=Manifest header attribute identifying the symbolic name of a bundle that exports a package specified in the Import-Package manifest header. resolution=Manifest header directive identifying the resolution type in the Import-Package or Require-Bundle manifest header. mandatory=Manifest header directive value identifying a mandatory resolution type. optional=Manifest header directive value identifying an optional resolution type. uses=Manifest header directive identifying a list of packages that an exported package uses. include=Manifest header directive identifying a list of classes to include in the exported package. exclude=Manifest header directive identifying a list of classes to exclude in the exported package.. mandatory=Manifest header directive identifying names of matching attributes which must be specified by matching Import-Package statements in the Export-Package manifest header. visibility=Manifest header directive identifying the visibility of a required bundle in the Require-Bundle manifest header. private=Manifest header directive value identifying a private visibility type. reexport=Manifest header directive value identifying a reexport visibility type. extension=Manifest header directive identifying the type of the extension fragment. framework=Manifest header directive value identifying the type of extension fragment. bootclasspath=Manifest header directive value identifying the type of extension fragment. Bundle-ActivationPolicy=Manifest header identifying the bundle's activation policy. lazy=Bundle activation policy declaring the bundle must be activated when the first class load is made from the bundle. org.osgi.framework.version=Framework environment property identifying the Framework version. org.osgi.framework.vendor=Framework environment property identifying the Framework implementation vendor. org.osgi.framework.language=Framework environment property identifying the Framework implementation language (see ISO 639 for possible values). org.osgi.framework.os.name=Framework environment property identifying the Framework host-computer's operating system. org.osgi.framework.os.version=Framework environment property identifying the Framework host-computer's operating system version number. org.osgi.framework.processor=Framework environment property identifying the Framework host-computer's processor name. org.osgi.framework.executionenvironment=Framework environment property identifying execution environments provided by the Framework. org.osgi.framework.bootdelegation=Framework environment property identifying packages for which the Framework must delegate class loading to the parent class loader of the bundle. org.osgi.framework.system.packages=Framework environment property identifying packages which the system bundle must export. org.osgi.framework.system.packages.extra=Framework environment property identifying extra packages which the system bundle must export from the current execution environment. org.osgi.supports.framework.extension=Framework environment property identifying whether the Framework supports framework extension bundles. org.osgi.supports.bootclasspath.extension=Framework environment property identifying whether the Framework supports bootclasspath extension bundles. org.osgi.supports.framework.fragment=Framework environment property identifying whether the Framework supports fragment bundles. org.osgi.supports.framework.requirebundle=Framework environment property identifying whether the Framework supports the Require-Bundle manifest header. org.osgi.framework.security=Specifies the type of security manager the framework must use. osgi=Specifies that a security manager that supports all security aspects of the OSGi core specification including postponed conditions must be installed. org.osgi.framework.storage=Specified the persistent storage area used by the framework. org.osgi.framework.storage.clean=Specifies if and when the persistent storage area for the framework should be cleaned. onFirstInit=Specifies that the framework storage area must be cleaned before the framework is initialized for the first time. org.osgi.framework.library.extensions=Specifies a comma separated list of additional library file extensions that must be used when a bundle's class loader is searching for native libraries. org.osgi.framework.command.execpermission=Specifies an optional OS specific command to set file permissions on extracted native code. org.osgi.framework.trust.repositories=Specifies the trust repositories used by the framework. org.osgi.framework.windowsystem=Specifies the current windowing system. org.osgi.framework.startlevel.beginning=Specifies the beginning start level of the framework. org.osgi.framework.bundle.parent=Specifies the parent class loader type for all bundle class loaders. boot=Specifies to use of the boot class loader as the parent class loader for all bundle class loaders. app=Specifies to use the application class loader as the parent class loader for all bundle class loaders. ext=Specifies to use the extension class loader as the parent class loader for all bundle class loaders. framework=Specifies to use the framework class loader as the parent class loader for all bundle class loaders. objectClass=Service property identifying all of the class names under which a service was registered in the Framework. service.id=Service property identifying a service's registration number. service.pid=Service property identifying a service's persistent identifier. service.ranking=Service property identifying a service's ranking number. service.vendor=Service property identifying a service's vendor. service.description=Service property identifying a service's description. provide=The action string provide. require=The action string require. host=The action string host. fragment=The action string fragment. class=The action string class. execute=The action string execute. extensionLifecycle=The action string extensionLifecycle. lifecycle=The action string lifecycle. listener=The action string listener. metadata=The action string metadata. resolve=The action string resolve. resource=The action string resource. startlevel=The action string startlevel. context=The action string context. service.pid=The property key for the identifier of the application being scheduled. schedule.id=The property key for the schedule identifier. org.osgi.triggeringevent=The key for the startup argument used to pass the event object that triggered the schedule to launch the application instance. org/osgi/application/timer=The topic name for the virtual timer topic. year=The name of the year attribute of a virtual timer event. month=The name of the month attribute of a virtual timer event. day_of_month=The name of the day of month attribute of a virtual timer event. day_of_week=The name of the day of week attribute of a virtual timer event. hour_of_day=The name of the hour of day attribute of a virtual timer event. minute=The name of the minute attribute of a virtual timer event. service.pid=The property key for the unique identifier (PID) of the application instance. application.descriptor=The property key for the pid of the corresponding application descriptor. application.state=The property key for the state of this application instance. application.supports.exitvalue=The property key for the supports exit value property of this application instance. RUNNING=The application instance is running. STOPPING=The application instance is being stopped. application.name=The property key for the localized name of the application. application.icon=The property key for the localized icon of the application. service.pid=The property key for the unique identifier (PID) of the application. application.version=The property key for the version of the application. service.vendor=The property key for the name of the application vendor. application.visible=The property key for the visibility property of the application. application.launchable=The property key for the launchable property of the application. application.locked=The property key for the locked property of the application. application.description=The property key for the localized description of the application. application.documentation=The property key for the localized documentation of the application. application.copyright=The property key for the localized copyright notice of the application. application.license=The property key for the localized license of the application. application.container=The property key for the application container of the application. application.location=The property key for the location of the application. lifecycle=Allows the lifecycle management of the target applications. schedule=Allows scheduling of the target applications. lock=Allows setting/unsetting the locking state of the target applications. bundle.version=The version property defining the bundle on whose behalf a module context event has been issued. extender.bundle=The extender bundle property defining the extender bundle processing the module context for which an event has been issued. extender.bundle.id=The extender bundle id property defining the id of the extender bundle processing the module context for which an event has been issued. extender.bundle.symbolicName=The extender bundle symbolic name property defining the symbolic name of the extender bundle processing the module context for which an event has been issued. org/osgi/service/blueprint=Topic prefix for all events issued by the Blueprint Service org/osgi/service/blueprint/context/CREATING=Topic for Blueprint Service CREATING events org/osgi/service/blueprint/context/CREATED=Topic for Blueprint Service CREATED events org/osgi/service/blueprint/context/DESTROYING=Topic for Blueprint Service DESTROYING events org/osgi/service/blueprint/context/DESTROYED=Topic for Blueprint Service DESTROYED events org/osgi/service/blueprint/context/WAITING=Topic for Blueprint Service WAITING events org/osgi/service/blueprint/context/FAILURE=Topic for Blueprint Service FAILURE events singleton= prototype= bundle= cm.target=A service property to limit the Managed Service or Managed Service Factory configuration dictionaries a Configuration Plugin service receives. service.cmRanking=A service property to specify the order in which plugins are invoked. configure=The action string configure. service.factoryPid=Service property naming the Factory PID in the configuration dictionary. service.bundleLocation=Service property naming the location of the bundle that is associated with a a Configuration object. osgi.converter.classes=This property is a string, or array of strings, and defines the classes or interfaces that this converter recognizes. osgi.command.scope=The scope of commands provided by this service. osgi.command.function=A String, array, or list of method names that may be called for this command provider. Service-Component=Manifest header specifying the XML documents within a bundle that contain the bundle's Service Component descriptions. component.name=A component property for a component configuration that contains the name of the component as specified in the name attribute of the component element. component.id=A component property that contains the generated id for a component configuration. component.factory=A service registration property for a Component Factory that contains the value of the factory attribute. .target=The suffix for reference target properties. allow=This string is used to indicate that a row in the Conditional Permission Table should return an access decision of "allow" if the conditions are all satisfied and at least one of the permissions is implied. deny=This string is used to indicate that a row in the Conditional Permission Table should return an access decision of "deny" if the conditions are all satisfied and at least one of the permissions is implied. deploymentpackage.name=The name of the Deployment Package. deploymentpackage.readablename=The human readable name of the DP localized to the default locale. deploymentpackage.currentversion=The currently installed version of the Deployment Package. deploymentpackage.nextversion=The version of DP after the successful completion of the install operation (used in INSTALL event only). install=Constant String to the "install" action. list=Constant String to the "list" action. uninstall=Constant String to the "uninstall" action. uninstall_forced=Constant String to the "uninstall_forced" action. cancel=Constant String to the "cancel" action. metadata=Constant String to the "metadata" action. privatearea=Constant String to the "privatearea" action. -1=Return value from DriverSelector.select, if no Driver service should be attached to the Device service. DRIVER_ID=Property (named "DRIVER_ID") identifying a driver. DEVICE_CATEGORY=Property (named "DEVICE_CATEGORY") containing a human readable description of the device categories implemented by a device. DEVICE_SERIAL=Property (named "DEVICE_SERIAL") specifying a device's serial number. DEVICE_DESCRIPTION=Property (named "DEVICE_DESCRIPTION") containing a human readable string describing the actual hardware device. service.interface=Mandatory ServiceRegistration property which contains a collection of full qualified interface names offered by the advertised service endpoint. service.interface.version=Optional ServiceRegistration property which contains a collection of interface names with their associated version attributes separated by SEPARATOR e.g. osgi.remote.endpoint.interface=Optional ServiceRegistration property which contains a collection of interface names with their associated (non-Java) endpoint interface names separated by SEPARATOR e.g.: 'my.company.foo|MyWebService my.company.zoo|MyWebService'. This (non-Java) endpoint interface name is usually a communication protocol specific interface, for instance a web service interface name. service.properties=Optional ServiceRegistration property which contains a map of properties of the published service. osgi.remote.endpoint.location=Optional property of the published service identifying its location. osgi.remote.endpoint.id=Optional property of the published service uniquely identifying its endpoint. |=Separator constant for association of interface-specific values with the particular interface name. osgi.remote.discovery.product=Service Registration property for the name of the Discovery product. osgi.remote.discovery.product.version=Service Registration property for the version of the Discovery product. osgi.remote.discovery.vendor=Service Registration property for the Discovery product vendor name. osgi.remote.discovery.supported_protocols=Service Registration property that lists the discovery protocols used by this Discovery service. osgi.discovery.interest.interfaces=Optional ServiceRegistration property which contains service interfaces this tracker is interested in. osgi.discovery.interest.filters=Optional ServiceRegistration property which contains filters for services this tracker is interested in. osgi.remote.distribution.product=Service Registration property for the name of the Distribution Provider product. osgi.remote.distribution.product.version=Service Registration property for the version of the Distribution Provider product. osgi.remote.distribution.vendor=Service Registration property for the Distribution Provider product vendor name. osgi.remote.distribition.supported_intents=Service Registration property that lists the intents supported by this DistributionProvider. publish=The action string publish. subscribe=The action string subscribe. event.topics=Service registration property (named event.topics) specifying the Event topics of interest to a Event Handler service. event.filter=Service Registration property (named event.filter) specifying a filter to further select Event s of interest to a Event Handler service. bundle.signer=The Distinguished Names of the signers of the bundle relevant to the event. bundle.symbolicName=The Bundle Symbolic Name of the bundle relevant to the event. bundle.id=The Bundle id of the bundle relevant to the event. bundle=The Bundle object of the bundle relevant to the event. bundle.version=The version of the bundle relevant to the event. event=The forwarded event object. exception=An exception or error. exception.class=The name of the exception type. exception.message=The exception message. message=A human-readable message that is usually not localized. service=A service reference. service.id=A service's id. service.objectClass=A service's objectClass. service.pid=A service's persistent identity. timestamp=The time when the event occurred, as reported by System.currentTimeMillis(). exception.class=This constant was released with an incorrectly spelled name. CompositeServiceFilter-Import=Manifest header (named "CompositeServiceFilter-Import") identifying the service filters that are used by a composite bundle to select services that will be registered into a child framework by its associated surrogate bundle. CompositeServiceFilter-Export=Manifest header (named "CompositeServiceFilter-Export") identifying the service filters that are used by a surrogate bundle to select services that will be registered into a parent framework by its associated composite bundle. org.osgi.service.http.authentication.remote.user=HttpServletRequest attribute specifying the name of the authenticated user. org.osgi.service.http.authentication.type=HttpServletRequest attribute specifying the scheme used in authentication. org.osgi.service.useradmin.authorization=HttpServletRequest attribute specifying the Authorization object obtained from the org.osgi.service.useradmin.UserAdmin service. io.scheme=Service property containing the scheme(s) for which this Connection Factory can create Connection objects. -1=Argument for getAttributeDefinitions(int). OSGI-INF/metatype=Location of meta type documents. read=Holders of MonitorPermission with the read action present are allowed to read the value of the StatusVariables specified in the permission's target field. reset=Holders of MonitorPermission with the reset action present are allowed to reset the value of the StatusVariables specified in the permission's target field. publish=Holders of MonitorPermission with the publish action present are Monitorable services that are allowed to publish the StatusVariables specified in the permission's target field. startjob=Holders of MonitorPermission with the startjob action present are allowed to initiate monitoring jobs involving the StatusVariables specified in the permission's target field. switchevents=Holders of MonitorPermission with the switchevents action present are allowed to switch event sending on or off for the value of the StatusVariables specified in the permission's target field. license= description= documentation= copyright= source= symbolicname= presentationname= id= version= url= size= provisioning.spid=The key to the provisioning information that uniquely identifies the Service Platform. provisioning.reference=The key to the provisioning information that contains the location of the provision data provider. provisioning.agent.config=The key to the provisioning information that contains the initial configuration information of the initial Management Agent. provisioning.update.count=The key to the provisioning information that contains the update count of the info data. provisioning.start.bundle=The key to the provisioning information that contains the location of the bundle to start with AllPermission. provisioning.rootx509=The key to the provisioning information that contains the root X509 certificate used to establish trust with operator when using HTTPS. provisioning.rsh.secret=The key to the provisioning information that contains the shared secret used in conjunction with the RSH protocol. text/plain;charset=utf-8=MIME type to be used in the InitialProvisioning-Entries header or stored in the extra field of a ZipEntry object for String data. application/octet-stream=MIME type to be used in the InitialProvisioning-Entries header or stored stored in the extra field of a ZipEntry object for byte[] data. application/vnd.osgi.bundle=MIME type to be used in the InitialProvisioning-Entries header or stored stored in the extra field of a ZipEntry object for an installable bundle file. application/x-osgi-bundle=Alternative MIME type to be used in the InitialProvisioning-Entries header or stored stored in the extra field of a ZipEntry object for an installable bundle file. text/x-osgi-bundle-url=MIME type to be stored in the extra field of a ZipEntry for a String that represents a URL for a bundle. InitialProvisioning-Entries=Name of the header that specifies the (MIME) type information for the ZIP file entries. ui1=Unsigned 1 Byte int. ui2=Unsigned 2 Byte int. ui4=Unsigned 4 Byte int. i1=1 Byte int. i2=2 Byte int. i4=4 Byte int. int=Integer number. r4=4 Byte float. r8=8 Byte float. number=Same as r8. fixed.14.4=Same as r8 but no more than 14 digits to the left of the decimal point and no more than 4 to the right. float=Floating-point number. char=Unicode string. string=Unicode string. date=A calendar date. dateTime=A specific instant of time. dateTime.tz=A specific instant of time. time=An instant of time that recurs every day. time.tz=An instant of time that recurs every day. boolean=True or false. bin.base64=MIME-style Base64 encoded binary BLOB. bin.hex=Hexadecimal digits representing octets. uri=Universal Resource Identifier. uuid=Universally Unique ID. UPnP.service.type=Property key for the optional service type uri. UPnP.service.id=Property key for the optional service id. upnp.filter=Key for a service property having a value that is an object of type org.osgi.framework.Filter and that is used to limit received events. UPnP=Constant for the value of the service property DEVICE_CATEGORY used for all UPnP devices. UPnP.export=The UPnP.export service property is a hint that marks a device to be picked up and exported by the UPnP Service. UPnP.device.UDN=Property key for the Unique Device Name (UDN) property. UPnP.device.UDN=Property key for the Unique Device ID property. UPnP.device.type=Property key for the UPnP Device Type property. UPnP.device.manufacturer=Mandatory property key for the device manufacturer's property. UPnP.device.modelName=Mandatory property key for the device model name. UPnP.device.friendlyName=Mandatory property key for a short user friendly version of the device name. UPnP.device.manufacturerURL=Optional property key for a URL to the device manufacturers Web site. UPnP.device.modelDescription=Optional (but recommended) property key for a String object with a long description of the device for the end user. UPnP.device.modelNumber=Optional (but recommended) property key for a String class typed property holding the model number of the device. UPnP.device.modelURL=Optional property key for a String typed property holding a string representing the URL to the Web site for this model. UPnP.device.serialNumber=Optional (but recommended) property key for a String typed property holding the serial number of the device. UPnP.device.UPC=Optional property key for a String typed property holding the Universal Product Code (UPC) of the device. UPnP.presentationURL=Optional (but recommended) property key for a String typed property holding a string representing the URL to a device representation Web page. UPnP.device.parentUDN=The property key that must be set for all embedded devices. UPnP.device.childrenUDN=The property key that must be set for all devices containing other embedded devices. url.handler.protocol=Service property naming the protocols serviced by a URLStreamHandlerService. url.content.mimetype=Service property naming the MIME types serviced by a java.net.ContentHandler. admin=The permission name "admin". changeProperty=The action string "changeProperty". changeCredential=The action string "changeCredential". getCredential=The action string "getCredential". user.anyone=The name of the predefined role, user.anyone, that all users and groups belong to. produce=The action string for the produce action. consume=The action string for the consume action. wireadmin.pid=Wire property key (named wireadmin.pid) specifying the persistent identity (PID) of this Wire object. wireadmin.producer.composite=A service registration property for a Producer service that is composite. wireadmin.consumer.composite=A service registration property for a Consumer service that is composite. wireadmin.producer.scope=Service registration property key (named wireadmin.producer.scope) specifying a list of names that may be used to define the scope of this Wire object. wireadmin.consumer.scope=Service registration property key (named wireadmin.consumer.scope) specifying a list of names that may be used to define the scope of this Wire object. wireadmin.producer.pid=Wire property key (named wireadmin.producer.pid) specifying the service.pid of the associated Producer service. wireadmin.consumer.pid=Wire property key (named wireadmin.consumer.pid) specifying the service.pid of the associated Consumer service. wireadmin.filter=Wire property key (named wireadmin.filter) specifying a filter used to control the delivery rate of data between the Producer and the Consumer service. wirevalue.current=Wire object's filter attribute (named wirevalue.current) representing the current value. wirevalue.previous=Wire object's filter attribute (named wirevalue.previous) representing the previous value. wirevalue.delta.absolute=Wire object's filter attribute (named wirevalue.delta.absolute) representing the absolute delta. wirevalue.delta.relative=Wire object's filter attribute (named wirevalue.delta.relative) representing the relative delta. wirevalue.elapsed=Wire object's filter attribute (named wirevalue.elapsed) representing the elapsed time, in ms, between this filter evaluation and the last update of the Consumer service. wireadmin.producer.filters=Service Registration property (named wireadmin.producer.filters). wireadmin.consumer.flavors=Service Registration property (named wireadmin.consumer.flavors) specifying the list of data types understood by this Consumer service. wireadmin.producer.flavors=Service Registration property (named wireadmin.producer.flavors) specifying the list of data types available from this Producer service. wireadmin.events=Service Registration property (named wireadmin.events) specifying the WireAdminEvent type of interest to a Wire Admin Listener service. javax.xml.parsers.SAXParserFactory=Filename containing the SAX Parser Factory Class name. javax.xml.parsers.DocumentBuilderFactory=Filename containing the DOM Parser Factory Class name. /META-INF/services/javax.xml.parsers.SAXParserFactory=Fully qualified path name of SAX Parser Factory Class Name file /META-INF/services/javax.xml.parsers.DocumentBuilderFactory=Fully qualified path name of DOM Parser Factory Class Name file parser.validating=Service property specifying if factory is configured to support validating parsers. parser.namespaceAware=Service property specifying if factory is configured to support namespace aware parsers. bnd-1.50.0/biz.aQute.bndlib/src/aQute/bnd/help/Errors.java0000644000175000017500000000006611656076535023027 0ustar drazzibdrazzibpackage aQute.bnd.help; public interface Errors { } bnd-1.50.0/biz.aQute.bndlib/src/aQute/bnd/help/packageinfo0000644000175000017500000000001311656076535023072 0ustar drazzibdrazzibversion 1.0bnd-1.50.0/biz.aQute.bndlib/src/aQute/bnd/help/changed.txt0000644000175000017500000000077511656076535023051 0ustar drazzibdrazzib0.0.325 - No longer flattening properties starting with - because for version policy, the context macro ${@} is not valid. I think this is true for more things. So they are now unexpanded. - toclasspath can now take a suffix parameter, possibly empty - Include-Resource can now take optional parameters: flatten:= (true|false). Default is false. Create recursive directories in the output or not. recursive:= (true|false) Default is true. Will descend any directories or not bnd-1.50.0/biz.aQute.bndlib/src/aQute/bnd/make/0000755000175000017500000000000011656076535020673 5ustar drazzibdrazzibbnd-1.50.0/biz.aQute.bndlib/src/aQute/bnd/make/coverage/0000755000175000017500000000000011656076535022466 5ustar drazzibdrazzibbnd-1.50.0/biz.aQute.bndlib/src/aQute/bnd/make/coverage/CoverageResource.java0000644000175000017500000000577111656076535026606 0ustar drazzibdrazzibpackage aQute.bnd.make.coverage; import static aQute.bnd.make.coverage.Coverage.*; import java.io.*; import java.lang.reflect.*; import java.util.*; import aQute.lib.osgi.*; import aQute.lib.osgi.Clazz.*; import aQute.lib.tag.*; /** * Creates an XML Coverage report. This class can be used as a resource so the * report is created only when the JAR is written. * */ public class CoverageResource extends WriteResource { Collection testsuite; Collection service; public CoverageResource(Collection testsuite, Collection service) { this.testsuite = testsuite; this.service = service; } @Override public long lastModified() { return 0; } @Override public void write(OutputStream out) throws IOException { try { Map> table = getCrossRef(testsuite, service); Tag coverage = toTag(table); PrintWriter pw = new PrintWriter(new OutputStreamWriter(out, Constants.DEFAULT_CHARSET)); try { coverage.print(0, pw); } finally { pw.flush(); } } catch (Exception e) { e.printStackTrace(); } } public static Tag toTag(Map> catalog) { Tag coverage = new Tag("coverage"); String currentClass = null; Tag classTag = null; for (Map.Entry> m : catalog.entrySet()) { String className = m.getKey().clazz; if (!className.equals(currentClass)) { classTag = new Tag("class"); classTag.addAttribute("name", className); classTag.addAttribute("package", Clazz.getPackage(className)); classTag.addAttribute("short", Clazz.getShortName(className)); coverage.addContent(classTag); currentClass = className; } Tag method = doMethod(new Tag("method"), m.getKey()); classTag.addContent(method); for (MethodDef r : m.getValue()) { Tag ref = doMethod(new Tag("ref"), r); method.addContent(ref); } } return coverage; } private static Tag doMethod(Tag tag, MethodDef method) { tag.addAttribute("pretty", method.getPretty()); if (Modifier.isPublic(method.access)) tag.addAttribute("public", true); if (Modifier.isStatic(method.access)) tag.addAttribute("static", true); if (Modifier.isProtected(method.access)) tag.addAttribute("protected", true); if (Modifier.isInterface(method.access)) tag.addAttribute("interface", true); tag.addAttribute("constructor", method.isConstructor()); if (!method.isConstructor()) tag.addAttribute("name", method.name); tag.addAttribute("descriptor", method.descriptor); return tag; } } bnd-1.50.0/biz.aQute.bndlib/src/aQute/bnd/make/coverage/Coverage.java0000644000175000017500000000653411656076535025074 0ustar drazzibdrazzibpackage aQute.bnd.make.coverage; import java.io.*; import java.lang.reflect.*; import java.util.*; import aQute.lib.osgi.*; import aQute.lib.osgi.Clazz.*; /** * This class can create a coverage table between two classspaces. The * destination class space is used to create a table of methods. All source * methods that refer to a specific dest are then filled into the table. * */ public class Coverage { /** * Create a cross reference table from source to dest. * * @param source * The methods that refer to dest * @param dest * The methods that are being referred to * @return A mapping of source methods to destination methods. * @throws IOException */ public static Map> getCrossRef( Collection source, Collection dest) throws Exception { final Map> catalog = buildCatalog(dest); crossRef(source, catalog); return catalog; } private static void crossRef(Collection source, final Map> catalog) throws Exception { for (final Clazz clazz : source) { clazz.parseClassFileWithCollector(new ClassDataCollector() { MethodDef source; public void implementsInterfaces(String names[]) { MethodDef def = new MethodDef(0, clazz.getFQN(), "", "()V"); for (String interfaceName : names) { interfaceName = Clazz.internalToFqn(interfaceName); for (Map.Entry> entry : catalog .entrySet()) { String catalogClass = entry.getKey().clazz; List references = entry.getValue(); if (catalogClass.equals(interfaceName)) { references.add(def); } } } } // Method definitions public void method(MethodDef source) { this.source = source; } public void reference(MethodDef reference) { List references = catalog.get(reference); if (references != null) { references.add(source); } } }); } } private static Map> buildCatalog( Collection sources) throws Exception { final Map> catalog = new TreeMap>(); for (final Clazz clazz : sources) { clazz.parseClassFileWithCollector(new ClassDataCollector() { public boolean classStart(int access, String name) { return clazz.isPublic(); } public void method(MethodDef source) { if (java.lang.reflect.Modifier.isPublic(source.access) || Modifier.isProtected(source.access)) catalog.put(source, new ArrayList()); } }); } return catalog; } } bnd-1.50.0/biz.aQute.bndlib/src/aQute/bnd/make/component/0000755000175000017500000000000011656076535022675 5ustar drazzibdrazzibbnd-1.50.0/biz.aQute.bndlib/src/aQute/bnd/make/component/ServiceComponent.java0000644000175000017500000004503311656076535027030 0ustar drazzibdrazzibpackage aQute.bnd.make.component; import java.io.*; import java.util.*; import java.util.regex.*; import aQute.bnd.annotation.component.*; import aQute.bnd.make.metatype.*; import aQute.bnd.service.*; import aQute.lib.osgi.*; import aQute.lib.osgi.Clazz.*; import aQute.libg.version.*; /** * This class is an analyzer plugin. It looks at the properties and tries to * find out if the Service-Component header contains the bnd shortut syntax. If * not, the header is copied to the output, if it does, an XML file is created * and added to the JAR and the header is modified appropriately. */ public class ServiceComponent implements AnalyzerPlugin { public boolean analyzeJar(Analyzer analyzer) throws Exception { ComponentMaker m = new ComponentMaker(analyzer); Map> l = m.doServiceComponent(); analyzer.setProperty(Constants.SERVICE_COMPONENT, Processor.printClauses(l)); analyzer.getInfo(m, "Service-Component: "); m.close(); return false; } private static class ComponentMaker extends Processor { Analyzer analyzer; ComponentMaker(Analyzer analyzer) { super(analyzer); this.analyzer = analyzer; } /** * Iterate over the Service Component entries. There are two cases: *
    *
  1. An XML file reference
  2. *
  3. A FQN/wildcard with a set of attributes
  4. *
* * An XML reference is immediately expanded, an FQN/wildcard is more * complicated and is delegated to * {@link #componentEntry(Map, String, Map)}. * * @throws Exception */ Map> doServiceComponent() throws Exception { Map> serviceComponents = newMap(); String header = getProperty(SERVICE_COMPONENT); Map> sc = parseHeader(header); for (Map.Entry> entry : sc.entrySet()) { String name = entry.getKey(); Map info = entry.getValue(); try { if (name.indexOf('/') >= 0 || name.endsWith(".xml")) { // Normal service component, we do not process it serviceComponents.put(name, EMPTY); } else { componentEntry(serviceComponents, name, info); } } catch (Exception e) { e.printStackTrace(); error("Invalid Service-Component header: %s %s, throws %s", name, info, e); } } return serviceComponents; } /** * Parse an entry in the Service-Component header. This header supports * the following types: *
    *
  1. An FQN + attributes describing a component
  2. *
  3. A wildcard expression for finding annotated components.
  4. *
* The problem is the distinction between an FQN and a wildcard because * an FQN can also be used as a wildcard. * * If the info specifies {@link Constants#NOANNOTATIONS} then wildcards * are an error and the component must be fully described by the info. * Otherwise the FQN/wildcard is expanded into a list of classes with * annotations. If this list is empty, the FQN case is interpreted as a * complete component definition. For the wildcard case, it is checked * if any matching classes for the wildcard have been compiled for a * class file format that does not support annotations, this can be a * problem with JSR14 who silently ignores annotations. An error is * reported in such a case. * * @param serviceComponents * @param name * @param info * @throws Exception * @throws IOException */ private void componentEntry(Map> serviceComponents, String name, Map info) throws Exception, IOException { boolean annotations = !Processor.isTrue(info.get(NOANNOTATIONS)); boolean fqn = Verifier.isFQN(name); if (annotations) { // Annotations possible! Collection annotatedComponents = analyzer.getClasses("", QUERY.ANNOTATION.toString(), Component.class.getName(), // QUERY.NAMED.toString(), name // ); if (fqn) { if (annotatedComponents.isEmpty()) { // No annotations, fully specified in header createComponentResource(serviceComponents, name, info); } else { // We had a FQN so expect only one for (Clazz c : annotatedComponents) { annotated(serviceComponents, c, info); } } } else { // We did not have an FQN, so expect the use of wildcards if (annotatedComponents.isEmpty()) checkAnnotationsFeasible(name); else for (Clazz c : annotatedComponents) { annotated(serviceComponents, c, info); } } } else { // No annotations if (fqn) createComponentResource(serviceComponents, name, info); else error("Set to %s but entry %s is not an FQN ", NOANNOTATIONS, name); } } /** * Check if annotations are actually feasible looking at the class * format. If the class format does not provide annotations then it is * no use specifying annotated components. * * @param name * @return * @throws Exception */ private Collection checkAnnotationsFeasible(String name) throws Exception { Collection not = analyzer.getClasses("", QUERY.NAMED.toString(), name // ); if (not.isEmpty()) if ( "*".equals(name)) return not; else error("Specified %s but could not find any class matching this pattern", name); for (Clazz c : not) { if (c.getFormat().hasAnnotations()) return not; } warning("Wildcards are used (%s) requiring annotations to decide what is a component. Wildcard maps to classes that are compiled with java.target < 1.5. Annotations were introduced in Java 1.5", name); return not; } void annotated(Map> components, Clazz c, Map info) throws Exception { // Get the component definition // from the annotations Map map = ComponentAnnotationReader.getDefinition(c, this); // Pick the name, the annotation can override // the name. String localname = map.get(COMPONENT_NAME); if (localname == null) localname = c.getFQN(); // Override the component info without manifest // entries. We merge the properties though. String merged = Processor.merge(info.remove(COMPONENT_PROPERTIES), map.remove(COMPONENT_PROPERTIES)); if (merged != null && merged.length() > 0) map.put(COMPONENT_PROPERTIES, merged); map.putAll(info); createComponentResource(components, localname, map); } private void createComponentResource(Map> components, String name, Map info) throws IOException { // We can override the name in the parameters if (info.containsKey(COMPONENT_NAME)) name = info.get(COMPONENT_NAME); // Assume the impl==name, but allow override String impl = name; if (info.containsKey(COMPONENT_IMPLEMENTATION)) impl = info.get(COMPONENT_IMPLEMENTATION); // Check if such a class exists analyzer.referTo(impl); boolean designate = designate(name, info.get(COMPONENT_DESIGNATE), false) || designate(name, info.get(COMPONENT_DESIGNATEFACTORY), true); // If we had a designate, we want a default configuration policy of // require. if (designate && info.get(COMPONENT_CONFIGURATION_POLICY) == null) info.put(COMPONENT_CONFIGURATION_POLICY, "require"); // We have a definition, so make an XML resources Resource resource = createComponentResource(name, impl, info); analyzer.getJar().putResource("OSGI-INF/" + name + ".xml", resource); components.put("OSGI-INF/" + name + ".xml", EMPTY); } /** * Create a Metatype and Designate record out of the given * configurations. * * @param name * @param config */ private boolean designate(String name, String config, boolean factory) { if (config == null) return false; for (String c : Processor.split(config)) { Clazz clazz = analyzer.getClassspace().get(Clazz.fqnToPath(c)); if (clazz != null) { analyzer.referTo(c); MetaTypeReader r = new MetaTypeReader(clazz, analyzer); r.setDesignate(name, factory); String rname = "OSGI-INF/metatype/" + name + ".xml"; analyzer.getJar().putResource(rname, r); } else { analyzer.error( "Cannot find designated configuration class %s for component %s", c, name); } } return true; } /** * Create the resource for a DS component. * * @param list * @param name * @param info * @throws UnsupportedEncodingException */ Resource createComponentResource(String name, String impl, Map info) throws IOException { String namespace = getNamespace(info); ByteArrayOutputStream out = new ByteArrayOutputStream(); PrintWriter pw = new PrintWriter(new OutputStreamWriter(out, Constants.DEFAULT_CHARSET)); pw.println(""); if (namespace != null) pw.print(""); // Allow override of the implementation when people // want to choose their own name pw.println(" "); String provides = info.get(COMPONENT_PROVIDE); boolean servicefactory = Processor.isTrue(info.get(COMPONENT_SERVICEFACTORY)); if (servicefactory && Processor.isTrue(info.get(COMPONENT_IMMEDIATE))) { // TODO can become error() if it is up to me warning("For a Service Component, the immediate option and the servicefactory option are mutually exclusive for %(%s)", name, impl); } provide(pw, provides, servicefactory, impl); properties(pw, info); reference(info, pw); if (namespace != null) pw.println(""); else pw.println(""); pw.close(); byte[] data = out.toByteArray(); out.close(); return new EmbeddedResource(data, 0); } private void doAttribute(PrintWriter pw, String value, String name, String... matches) { if (value != null) { if (matches.length != 0) { if (matches.length == 1 && matches[0].equals(JIDENTIFIER)) { if (!Verifier.isIdentifier(value)) error("Component attribute %s has value %s but is not a Java identifier", name, value); } else { if (!Verifier.isMember(value, matches)) error("Component attribute %s has value %s but is not a member of %s", name, value, Arrays.toString(matches)); } } pw.print(" "); pw.print(name); pw.print("='"); pw.print(value); pw.print("'"); } } /** * Check if we need to use the v1.1 namespace (or later). * * @param info * @return */ private String getNamespace(Map info) { String version = info.get(COMPONENT_VERSION); if (version != null) { try { Version v = new Version(version); return NAMESPACE_STEM + "/v" + v; } catch (Exception e) { error("version: specified on component header but not a valid version: " + version); return null; } } for (String key : info.keySet()) { if (SET_COMPONENT_DIRECTIVES_1_1.contains(key)) { return NAMESPACE_STEM + "/v1.1.0"; } } return null; } /** * Print the Service-Component properties element * * @param pw * @param info */ void properties(PrintWriter pw, Map info) { Collection properties = split(info.get(COMPONENT_PROPERTIES)); for (Iterator p = properties.iterator(); p.hasNext();) { String clause = p.next(); int n = clause.indexOf('='); if (n <= 0) { error("Not a valid property in service component: " + clause); } else { String type = null; String name = clause.substring(0, n); if (name.indexOf('@') >= 0) { String parts[] = name.split("@"); name = parts[1]; type = parts[0]; } else if (name.indexOf(':') >= 0) { String parts[] = name.split(":"); name = parts[0]; type = parts[1]; } String value = clause.substring(n + 1).trim(); // TODO verify validity of name and value. pw.print(" 1) { pw.println(">"); for (String part : parts) { pw.println(part); } pw.println(""); } else { pw.print(" value='"); pw.print(parts[0]); pw.println("'/>"); } } } } /** * @param pw * @param provides */ void provide(PrintWriter pw, String provides, boolean servicefactory, String impl) { if (provides != null) { if (!servicefactory) pw.println(" "); else pw.println(" "); StringTokenizer st = new StringTokenizer(provides, ","); while (st.hasMoreTokens()) { String interfaceName = st.nextToken(); pw.println(" "); analyzer.referTo(interfaceName); // TODO verifies the impl. class extends or implements the // interface } pw.println(" "); } else if (servicefactory) warning("The servicefactory:=true directive is set but no service is provided, ignoring it"); } public final static Pattern REFERENCE = Pattern.compile("([^(]+)(\\(.+\\))?"); /** * @param info * @param pw */ void reference(Map info, PrintWriter pw) { Collection dynamic = new ArrayList(split(info.get(COMPONENT_DYNAMIC))); Collection optional = new ArrayList(split(info.get(COMPONENT_OPTIONAL))); Collection multiple = new ArrayList(split(info.get(COMPONENT_MULTIPLE))); Collection descriptors = split(info.get(COMPONENT_DESCRIPTORS)); for (Map.Entry entry : info.entrySet()) { // Skip directives String referenceName = entry.getKey(); if (referenceName.endsWith(":")) { if (!SET_COMPONENT_DIRECTIVES.contains(referenceName)) error("Unrecognized directive in Service-Component header: " + referenceName); continue; } // Parse the bind/unbind methods from the name // if set. They are separated by '/' String bind = null; String unbind = null; boolean unbindCalculated = false; if (referenceName.indexOf('/') >= 0) { String parts[] = referenceName.split("/"); referenceName = parts[0]; bind = parts[1]; if (parts.length > 2) { unbind = parts[2]; } else { unbindCalculated = true; if (bind.startsWith("add")) unbind = bind.replaceAll("add(.+)", "remove$1"); else unbind = "un" + bind; } } else if (Character.isLowerCase(referenceName.charAt(0))) { unbindCalculated = true; bind = "set" + Character.toUpperCase(referenceName.charAt(0)) + referenceName.substring(1); unbind = "un" + bind; } String interfaceName = entry.getValue(); if (interfaceName == null || interfaceName.length() == 0) { error("Invalid Interface Name for references in Service Component: " + referenceName + "=" + interfaceName); continue; } // If we have descriptors, we have analyzed the component. // So why not check the methods if (descriptors.size() > 0) { // Verify that the bind method exists if (!descriptors.contains(bind)) error("The bind method %s for %s not defined", bind, referenceName); // Check if the unbind method exists if (!descriptors.contains(unbind)) { if (unbindCalculated) // remove it unbind = null; else error("The unbind method %s for %s not defined", unbind, referenceName); } } // Check tje cardinality by looking at the last // character of the value char c = interfaceName.charAt(interfaceName.length() - 1); if ("?+*~".indexOf(c) >= 0) { if (c == '?' || c == '*' || c == '~') optional.add(referenceName); if (c == '+' || c == '*') multiple.add(referenceName); if (c == '+' || c == '*' || c == '?') dynamic.add(referenceName); interfaceName = interfaceName.substring(0, interfaceName.length() - 1); } // Parse the target from the interface name // The target is a filter. String target = null; Matcher m = REFERENCE.matcher(interfaceName); if (m.matches()) { interfaceName = m.group(1); target = m.group(2); } analyzer.referTo(interfaceName); pw.printf(" "); } } } /** * Escape a string, do entity conversion. */ static String escape(String s) { StringBuffer sb = new StringBuffer(); for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); switch (c) { case '<': sb.append("<"); break; case '>': sb.append(">"); break; case '&': sb.append("&"); break; case '\'': sb.append("""); break; default: sb.append(c); break; } } return sb.toString(); } } bnd-1.50.0/biz.aQute.bndlib/src/aQute/bnd/make/component/ComponentAnnotationReader.java0000644000175000017500000002440611656076535030666 0ustar drazzibdrazzibpackage aQute.bnd.make.component; import static aQute.lib.osgi.Constants.*; import java.lang.reflect.*; import java.util.*; import java.util.regex.*; import aQute.lib.osgi.Annotation; import aQute.bnd.annotation.component.*; import aQute.lib.osgi.*; import aQute.libg.reporter.*; public class ComponentAnnotationReader extends ClassDataCollector { String EMPTY[] = new String[0]; private static final String V1_1 = "1.1.0"; // "1.1.0" static Pattern BINDDESCRIPTOR = Pattern .compile("\\(L([^;]*);(Ljava/util/Map;|Lorg/osgi/framework/ServiceReference;)*\\)V"); static Pattern BINDMETHOD = Pattern.compile("(set|bind|add)(.)(.*)"); static Pattern ACTIVATEDESCRIPTOR = Pattern .compile("\\(((Lorg/osgi/service/component/ComponentContext;)|(Lorg/osgi/framework/BundleContext;)|(Ljava/util/Map;))*\\)V"); static Pattern OLDACTIVATEDESCRIPTOR = Pattern .compile("\\(Lorg/osgi/service/component/ComponentContext;\\)V"); static Pattern OLDBINDDESCRIPTOR = Pattern.compile("\\(L([^;]*);\\)V"); static Pattern REFERENCEBINDDESCRIPTOR = Pattern .compile("\\(Lorg/osgi/framework/ServiceReference;\\)V"); Reporter reporter = new Processor(); String method; String methodDescriptor; int methodAccess; String className; Clazz clazz; String interfaces[]; Set multiple = new HashSet(); Set optional = new HashSet(); Set dynamic = new HashSet(); Map map = new TreeMap(); Set descriptors = new HashSet(); List properties = new ArrayList(); String version = null; // TODO make patterns for descriptors ComponentAnnotationReader(Clazz clazz) { this.clazz = clazz; } public void setReporter(Reporter reporter) { this.reporter = reporter; } public Reporter getReporter() { return this.reporter; } public static Map getDefinition(Clazz c) throws Exception { return getDefinition(c, new Processor()); } public static Map getDefinition(Clazz c, Reporter reporter) throws Exception { ComponentAnnotationReader r = new ComponentAnnotationReader(c); r.setReporter(reporter); c.parseClassFileWithCollector(r); r.finish(); return r.map; } public void annotation(Annotation annotation) { if (annotation.getName().equals(Component.RNAME)) { set(COMPONENT_NAME, annotation.get(Component.NAME), "<>"); set(COMPONENT_FACTORY, annotation.get(Component.FACTORY), false); setBoolean(COMPONENT_ENABLED, annotation.get(Component.ENABLED), true); setBoolean(COMPONENT_IMMEDIATE, annotation.get(Component.IMMEDIATE), false); setBoolean(COMPONENT_SERVICEFACTORY, annotation.get(Component.SERVICEFACTORY), false); if (annotation.get(Component.DESIGNATE) != null) { String configs = annotation.get(Component.DESIGNATE); if (configs != null) { set(COMPONENT_DESIGNATE, Clazz.objectDescriptorToFQN(configs), ""); } } if (annotation.get(Component.DESIGNATE_FACTORY) != null) { String configs = annotation.get(Component.DESIGNATE_FACTORY); if (configs != null) { set(COMPONENT_DESIGNATEFACTORY, Clazz.objectDescriptorToFQN(configs), ""); } } setVersion((String) annotation.get(Component.VERSION)); String configurationPolicy = annotation.get(Component.CONFIGURATION_POLICY); if (configurationPolicy != null) set(COMPONENT_CONFIGURATION_POLICY, configurationPolicy.toLowerCase(), ""); doProperties(annotation); Object[] provides = (Object[]) annotation.get(Component.PROVIDE); String[] p; if (provides == null) { // Use the found interfaces, but convert from internal to // fqn. if (interfaces != null) { List result = new ArrayList(); for (int i = 0; i < interfaces.length; i++) { if (!interfaces[i].equals("scala/ScalaObject") ) result.add(Clazz.internalToFqn(interfaces[i])); } p = result.toArray(EMPTY); } else p = EMPTY; } else { // We have explicit interfaces set p = new String[provides.length]; for (int i = 0; i < provides.length; i++) { p[i] = descriptorToFQN(provides[i].toString()); } } if (p.length > 0) { set(COMPONENT_PROVIDE, Processor.join(Arrays.asList(p)), "<>"); } } else if (annotation.getName().equals(Activate.RNAME)) { if (!checkMethod()) setVersion(V1_1); if (!ACTIVATEDESCRIPTOR.matcher(methodDescriptor).matches()) reporter.error( "Activate method for %s does not have an acceptable prototype, only Map, ComponentContext, or BundleContext is allowed. Found: %s", className, methodDescriptor); if (method.equals("activate") && OLDACTIVATEDESCRIPTOR.matcher(methodDescriptor).matches()) { // this is the default! } else { setVersion(V1_1); set(COMPONENT_ACTIVATE, method, "<>"); } } else if (annotation.getName().equals(Deactivate.RNAME)) { if (!checkMethod()) setVersion(V1_1); if (!ACTIVATEDESCRIPTOR.matcher(methodDescriptor).matches()) reporter.error( "Deactivate method for %s does not have an acceptable prototype, only Map, ComponentContext, or BundleContext is allowed. Found: %s", className, methodDescriptor); if (method.equals("deactivate") && OLDACTIVATEDESCRIPTOR.matcher(methodDescriptor).matches()) { // This is the default! } else { setVersion(V1_1); set(COMPONENT_DEACTIVATE, method, "<>"); } } else if (annotation.getName().equals(Modified.RNAME)) { set(COMPONENT_MODIFIED, method, "<>"); setVersion(V1_1); } else if (annotation.getName().equals(Reference.RNAME)) { String name = (String) annotation.get(Reference.NAME); String bind = method; String unbind = null; if (name == null) { Matcher m = BINDMETHOD.matcher(method); if (m.matches()) { name = m.group(2).toLowerCase() + m.group(3); } else { name = method.toLowerCase(); } } String simpleName = name; unbind = annotation.get(Reference.UNBIND); if (bind != null) { name = name + "/" + bind; if (unbind != null) name = name + "/" + unbind; } String service = annotation.get(Reference.SERVICE); if (service != null) { service = Clazz.objectDescriptorToFQN(service); } else { // We have to find the type of the current method to // link it to the referenced service. Matcher m = BINDDESCRIPTOR.matcher(methodDescriptor); if (m.matches()) { service = Clazz.internalToFqn(m.group(1)); } else throw new IllegalArgumentException( "Cannot detect the type of a Component Reference from the descriptor: " + methodDescriptor); } // Check if we have a target, this must be a filter String target = annotation.get(Reference.TARGET); if (target != null) { Verifier.verifyFilter(target, 0); service = service + target; } Integer c = annotation.get(Reference.TYPE); if (c != null && !c.equals(0) && !c.equals((int) '1')) { service = service + (char) c.intValue(); } if (map.containsKey(name)) reporter.error( "In component %s, Multiple references with the same name: %s. Previous def: %s, this def: %s", name, map.get(name), service, ""); map.put(name, service); if (isTrue(annotation.get(Reference.MULTIPLE))) multiple.add(simpleName); if (isTrue(annotation.get(Reference.OPTIONAL))) optional.add(simpleName); if (isTrue(annotation.get(Reference.DYNAMIC))) dynamic.add(simpleName); if (!checkMethod()) setVersion(V1_1); else if (REFERENCEBINDDESCRIPTOR.matcher(methodDescriptor).matches() || !OLDBINDDESCRIPTOR.matcher(methodDescriptor).matches()) setVersion(V1_1); } } private void setVersion(String v) { if (v == null) return; if (version == null) version = v; else if (v.compareTo(version) > 0) // we're safe to 9.9.9 version = v; } private boolean checkMethod() { return Modifier.isPublic(methodAccess) || Modifier.isProtected(methodAccess); } static Pattern PROPERTY_PATTERN = Pattern.compile("[^=]+=.+"); private void doProperties(aQute.lib.osgi.Annotation annotation) { Object[] properties = annotation.get(Component.PROPERTIES); if (properties != null) { for (Object o : properties) { String p = (String) o; if (PROPERTY_PATTERN.matcher(p).matches()) this.properties.add(p); else throw new IllegalArgumentException("Malformed property '" + p + "' on: " + annotation.get(Component.NAME)); } } } private boolean isTrue(Object object) { if (object == null) return false; return (Boolean) object; } private void setBoolean(String string, Object object, boolean b) { if (object == null) object = b; Boolean bb = (Boolean) object; if (bb == b) return; map.put(string, bb.toString()); } private void set(String string, Object object, Object deflt) { if (object == null || object.equals(deflt)) return; map.put(string, object.toString()); } /** * Skip L and ; and replace / for . in an object descriptor. * * A string like Lcom/acme/Foo; becomes com.acme.Foo * * @param string * @return */ private String descriptorToFQN(String string) { StringBuilder sb = new StringBuilder(); for (int i = 1; i < string.length() - 1; i++) { char c = string.charAt(i); if (c == '/') c = '.'; sb.append(c); } return sb.toString(); } @Override public void classBegin(int access, String name) { className = name; } @Override public void implementsInterfaces(String[] interfaces) { this.interfaces = interfaces; } @Override public void method(int access, String name, String descriptor) { this.method = name; this.methodDescriptor = descriptor; this.methodAccess = access; descriptors.add(method); } void set(String name, Collection l) { if (l.size() == 0) return; set(name, Processor.join(l), "<>"); } public void finish() { set(COMPONENT_MULTIPLE, multiple); set(COMPONENT_DYNAMIC, dynamic); set(COMPONENT_OPTIONAL, optional); set(COMPONENT_IMPLEMENTATION, clazz.getFQN(), "<>"); set(COMPONENT_PROPERTIES, properties); if (version != null) { set(COMPONENT_VERSION, version, "<>"); reporter.trace("Component %s is v1.1", map); } set(COMPONENT_DESCRIPTORS, descriptors); } } bnd-1.50.0/biz.aQute.bndlib/src/aQute/bnd/make/MakeCopy.java0000644000175000017500000000262711656076535023255 0ustar drazzibdrazzibpackage aQute.bnd.make; import java.io.*; import java.net.*; import java.util.*; import aQute.bnd.service.*; import aQute.lib.osgi.*; public class MakeCopy implements MakePlugin { public Resource make(Builder builder, String destination, Map argumentsOnMake) throws Exception { String type = argumentsOnMake.get("type"); if (!type.equals("copy")) return null; String from = argumentsOnMake.get("from"); if (from == null) { String content = argumentsOnMake.get("content"); if (content == null) throw new IllegalArgumentException( "No 'from' or 'content' field in copy " + argumentsOnMake); return new EmbeddedResource(content.getBytes("UTF-8"),0); } else { File f = builder.getFile(from); if (f.isFile()) return new FileResource(f); else { try { URL url = new URL(from); return new URLResource(url); } catch(MalformedURLException mfue) { // We ignore this } throw new IllegalArgumentException( "Copy source does not exist " + from + " for destination " + destination); } } } } bnd-1.50.0/biz.aQute.bndlib/src/aQute/bnd/make/calltree/0000755000175000017500000000000011656076535022466 5ustar drazzibdrazzibbnd-1.50.0/biz.aQute.bndlib/src/aQute/bnd/make/calltree/CalltreeResource.java0000644000175000017500000001304311656076535026575 0ustar drazzibdrazzibpackage aQute.bnd.make.calltree; import java.io.*; import java.lang.reflect.*; import java.util.*; import aQute.lib.osgi.*; /** * Create an XML call tree of a set of classes. The structure of the XML is: * *
 *    calltree ::= <using> <usedby>
 *    using    ::= <method> *
 *    usedby   ::= <method> *
 *    method   ::= <ref> 
 * 
* * The using element contains methods in the set of classes and * their references. The usedby element contains the used methods * and their references to the set of classes. The ref element * contains the class, the method name, the descriptor, and a pretty print * version of the method. * * The XML does not contain an XML processor instruction to make it easier to * include in other XML. The encoding is always UTF-8. * * This class can be used as a resource, just add it to a JAR and the data is * generated when the resource is written (saving time when the JAR is up to * date and does not have to be generated). However, the actual write method is * a static method and can be called as well: * {@link #writeCalltree(PrintWriter, Collection)}. */ public class CalltreeResource extends WriteResource { Collection classes; /** * Create a resource for inclusion that will print a call tree. * * @param values the classes for which the call tree is generated. */ public CalltreeResource(Collection values) { this.classes = values; System.out.println(values); } /** * We set the last modified to 0 so this resource does not force * a new JAR if all other resources are up to date. */ public long lastModified() { return 0; } /** * The write method is called to write the resource. We just call the static * method. */ public void write(OutputStream out) throws Exception { OutputStreamWriter osw = new OutputStreamWriter(out, Constants.DEFAULT_CHARSET); PrintWriter pw = new PrintWriter(osw); try { writeCalltree(pw, classes); } finally { pw.flush(); } } /** * Print the call tree in XML. * * @param out The output writer * @param classes The set of classes * @throws IOException Any errors */ public static void writeCalltree(PrintWriter out, Collection classes) throws Exception { final Map> using = new TreeMap>(); final Map> usedby = new TreeMap>(); ClassDataCollector cd = new ClassDataCollector() { Clazz.MethodDef source; // Before a method is parsed public void method(Clazz.MethodDef source) { this.source = source; xref(using, source, null); xref(usedby, source, null); } // For any reference in the previous method. public void reference(Clazz.MethodDef reference) { xref(using, source, reference); xref(usedby, reference, source); } }; for (Clazz clazz : classes) { clazz.parseClassFileWithCollector(cd); } out.println(""); xref(out, "using", using); xref(out, "usedby", usedby); out.println(""); } /* * Add a new reference */ private static void xref( Map> references, Clazz.MethodDef source, Clazz.MethodDef reference) { Set set = references.get(source); if (set == null) references.put(source, set=new TreeSet()); if ( reference != null) set.add(reference); } /* * Print out either using or usedby sets */ private static void xref(PrintWriter out, String group, Map> references) { out.println(" <" + group + ">"); for (Map.Entry> entry : references .entrySet()) { Clazz.MethodDef source = entry.getKey(); Set refs = entry.getValue(); method(out, "method", source, ">"); for (Clazz.MethodDef ref : refs) { method(out, "ref", ref, "/>"); } out.println(" "); } out.println(" "); } /* * Print out a method. */ private static void method(PrintWriter out, String element, Clazz.MethodDef source, String closeElement) { out.println(" <" + element + " class='" + source.clazz + "'" + getAccess(source.access) + ( source.isConstructor() ? "" : " name='" + source.name + "'") + " descriptor='" + source.descriptor + "' pretty='" + source.getPretty() + "'" + closeElement); } private static String getAccess(int access) { StringBuilder sb = new StringBuilder(); if ( Modifier.isPublic(access) ) sb.append(" public='true'"); if ( Modifier.isStatic(access) ) sb.append(" static='true'"); if ( Modifier.isProtected(access) ) sb.append(" protected='true'"); if ( Modifier.isInterface(access) ) sb.append(" interface='true'"); return sb.toString(); } } bnd-1.50.0/biz.aQute.bndlib/src/aQute/bnd/make/MakeBnd.java0000644000175000017500000000464111656076535023044 0ustar drazzibdrazzibpackage aQute.bnd.make; import java.io.*; import java.util.*; import java.util.regex.*; import aQute.bnd.build.*; import aQute.bnd.service.*; import aQute.lib.osgi.*; public class MakeBnd implements MakePlugin, Constants { final static Pattern JARFILE = Pattern.compile("(.+)\\.(jar|ipa)"); public Resource make(Builder builder, String destination, Map argumentsOnMake) throws Exception { String type = (String) argumentsOnMake.get("type"); if (!"bnd".equals(type)) return null; String recipe = (String) argumentsOnMake.get("recipe"); if (recipe == null) { builder.error("No recipe specified on a make instruction for " + destination); return null; } File bndfile = builder.getFile(recipe); if (bndfile.isFile()) { // We do not use a parent because then we would // build ourselves again. So we can not blindly // inherit the properties. Builder bchild = builder.getSubBuilder(); bchild.removeBundleSpecificHeaders(); // We must make sure that we do not include ourselves again! bchild.setProperty(Analyzer.INCLUDE_RESOURCE, ""); bchild.setProperty(Analyzer.INCLUDERESOURCE, ""); bchild.setProperties(bndfile, builder.getBase()); Jar jar = bchild.build(); Jar dot = builder.getTarget(); if (builder.hasSources()) { for (String key : jar.getResources().keySet()) { if (key.startsWith("OSGI-OPT/src")) dot.putResource(key, (Resource) jar.getResource(key)); } } builder.getInfo(bchild, bndfile.getName() +": "); String debug = bchild.getProperty(DEBUG); if (Processor.isTrue(debug)) { if ( builder instanceof ProjectBuilder ) { ProjectBuilder pb = (ProjectBuilder) builder; File target = pb.getProject().getTarget(); String bsn = bchild.getBsn(); File output = new File(target, bsn+".jar"); jar.write(output); pb.getProject().getWorkspace().changedFile(output); } } return new JarResource(jar); } else return null; } } bnd-1.50.0/biz.aQute.bndlib/src/aQute/bnd/make/Make.java0000644000175000017500000000673111656076535022422 0ustar drazzibdrazzibpackage aQute.bnd.make; import java.util.*; import java.util.regex.*; import aQute.bnd.service.*; import aQute.lib.osgi.*; public class Make { Builder builder; Map> make; public Make(Builder builder) { this.builder = builder; } public Resource process(String source) { Map> make = getMakeHeader(); builder.trace("make " + source); for (Map.Entry> entry : make .entrySet()) { Instruction instr = entry.getKey(); Matcher m = instr.getMatcher(source); if (m.matches() || instr.isNegated()) { Map arguments = replace(m, entry.getValue()); List plugins = builder.getPlugins(MakePlugin.class); for (MakePlugin plugin : plugins) { try { Resource resource = plugin.make(builder, source, arguments); if (resource != null) { builder.trace("Made " + source + " from args " + arguments + " with " + plugin); return resource; } } catch (Exception e) { builder.error("Plugin " + plugin + " generates error when use in making " + source + " with args " + arguments, e); } } } } return null; } private Map replace(Matcher m, Map value) { Map newArgs = Processor.newMap(); for (Map.Entry entry : value.entrySet()) { String s = entry.getValue(); s = replace(m, s); newArgs.put(entry.getKey(), s); } return newArgs; } String replace(Matcher m, CharSequence s) { StringBuffer sb = new StringBuffer(); int max = '0' + m.groupCount() + 1; for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); if (c == '$' && i < s.length() - 1) { c = s.charAt(++i); if (c >= '0' && c <= max) { int index = c - '0'; String replacement = m.group(index); if (replacement != null) sb.append(replacement); } else { if (c == '$') i++; sb.append(c); } } else sb.append(c); } return sb.toString(); } Map> getMakeHeader() { if (make != null) return make; make = Processor.newMap(); String s = builder.getProperty(Builder.MAKE); Map> make = builder.parseHeader(s); for (Iterator>> e = make .entrySet().iterator(); e.hasNext();) { Map.Entry> entry = e.next(); String pattern = Processor.removeDuplicateMarker(entry.getKey()); Instruction instr = Instruction.getPattern(pattern); this.make.put(instr, entry.getValue()); } return this.make; } } bnd-1.50.0/biz.aQute.bndlib/src/aQute/bnd/make/metatype/0000755000175000017500000000000011656076535022523 5ustar drazzibdrazzibbnd-1.50.0/biz.aQute.bndlib/src/aQute/bnd/make/metatype/MetatypePlugin.java0000644000175000017500000000162411656076535026340 0ustar drazzibdrazzibpackage aQute.bnd.make.metatype; import java.util.*; import aQute.bnd.annotation.metatype.*; import aQute.bnd.service.*; import aQute.lib.osgi.*; import aQute.lib.osgi.Clazz.*; /** * This class is responsible for meta type types. It is a plugin that can * @author aqute * */ public class MetatypePlugin implements AnalyzerPlugin { public boolean analyzeJar(Analyzer analyzer) throws Exception { Map> map = analyzer.parseHeader(analyzer .getProperty(Constants.METATYPE)); Jar jar = analyzer.getJar(); for (String name : map.keySet()) { Collection metatypes = analyzer.getClasses("", QUERY.ANNOTATION.toString(), Meta.OCD.class.getName(), // QUERY.NAMED.toString(), name // ); for (Clazz c : metatypes) { jar.putResource("OSGI-INF/metatype/" + c.getFQN() + ".xml", new MetaTypeReader(c, analyzer)); } } return false; } } bnd-1.50.0/biz.aQute.bndlib/src/aQute/bnd/make/metatype/MetaTypeReader.java0000644000175000017500000002142311656076535026243 0ustar drazzibdrazzibpackage aQute.bnd.make.metatype; import java.io.*; import java.util.*; import java.util.concurrent.*; import java.util.regex.*; import aQute.bnd.annotation.metatype.*; import aQute.lib.io.*; import aQute.lib.osgi.*; import aQute.lib.osgi.Clazz.MethodDef; import aQute.lib.tag.*; import aQute.libg.generics.*; public class MetaTypeReader extends ClassDataCollector implements Resource { final Analyzer reporter; Clazz clazz; String interfaces[]; Tag metadata = new Tag("metatype:MetaData", new String[] { "xmlns:metatype", "http://www.osgi.org/xmlns/metatype/v1.1.0" }); Tag ocd = new Tag(metadata, "OCD"); Tag designate = new Tag(metadata, "Designate"); Tag object = new Tag(designate, "Object"); // Resource String extra; // One time init boolean finished; // Designate boolean override; String designatePid; boolean factory; // AD Map methods = new LinkedHashMap(); // OCD Annotation ocdAnnotation; MethodDef method; public MetaTypeReader(Clazz clazz, Analyzer reporter) { this.clazz = clazz; this.reporter = reporter; } public void annotation(Annotation annotation) { try { Meta.OCD ocd = annotation.getAnnotation(Meta.OCD.class); Meta.AD ad = annotation.getAnnotation(Meta.AD.class); if (ocd != null) { this.ocdAnnotation = annotation; } if (ad != null) { assert method != null; methods.put(method, ad); } } catch (Exception e) { reporter.error("Error during annotation parsing %s : %s", clazz, e); e.printStackTrace(); } } /** * @param id * @param name * @param cardinality * @param required * @param deflt * @param type * @param max * @param min * @param optionLabels * @param optionValues */ static Pattern COLLECTION = Pattern .compile("(.*(Collection|Set|List|Queue|Stack|Deque))<(L.+;)>"); private void addMethod(MethodDef method, Meta.AD ad) throws Exception { // Set all the defaults. String rtype = method.getReturnType(); String id = Configurable.mangleMethodName(method.name); String name = Clazz.unCamel(id); int cardinality = 0; if (rtype.endsWith("[]")) { cardinality = Integer.MAX_VALUE; rtype = rtype.substring(0, rtype.length() - 2); } if (rtype.indexOf('<') > 0) { if (cardinality != 0) reporter.error( "AD for %s.%s uses an array of collections in return type (%s), Metatype allows either Vector or array", clazz.getFQN(), method.name, method.getReturnType()); Matcher m = COLLECTION.matcher(rtype); if (m.matches()) { rtype = Clazz.objectDescriptorToFQN(m.group(3)); cardinality = Integer.MIN_VALUE; } } Meta.Type type = getType(rtype); boolean required = ad ==null || ad.required(); String deflt = null; String max = null; String min = null; String[] optionLabels = null; String[] optionValues = null; String description = null; Clazz c = reporter.findClass(Clazz.fqnToPath(rtype)); if (c != null && c.isEnum()) { optionValues = parseOptionValues(c); } // Now parse the annotation for any overrides if (ad != null) { if (ad.id() != null) id = ad.id(); if (ad.name() != null) name = ad.name(); if (ad.cardinality() != 0) cardinality = ad.cardinality(); if (ad.type() != null) type = ad.type(); if (ad.required() || ad.deflt() == null) required = true; if (ad.description() != null) description = ad.description(); if (ad.optionLabels() != null) optionLabels = ad.optionLabels(); if (ad.optionValues() != null ) optionValues = ad.optionValues(); if (ad.min() != null) min = ad.min(); if (ad.max() != null) max = ad.max(); if (ad.deflt() != null) deflt = ad.deflt(); } if (optionValues != null) { if (optionLabels == null || optionLabels.length == 0) { optionLabels = new String[optionValues.length]; for (int i = 0; i < optionValues.length; i++) optionLabels[i] = Clazz.unCamel(optionValues[i]); } if (optionLabels.length != optionValues.length) { reporter.error("Option labels and option values not the same length for %s", id); optionLabels = optionValues; } } Tag adt = new Tag(this.ocd, "AD"); adt.addAttribute("name", name); adt.addAttribute("id", id); adt.addAttribute("cardinality", cardinality); adt.addAttribute("required", required); adt.addAttribute("default", deflt); adt.addAttribute("type", type); adt.addAttribute("max", max); adt.addAttribute("min", min); adt.addAttribute("description", description); if (optionLabels != null) { for (int i = 0; i < optionLabels.length; i++) { Tag option = new Tag(adt, "Option"); option.addAttribute("label", optionLabels[i]); option.addAttribute("value", optionValues[i]); } } } private String[] parseOptionValues(Clazz c) throws Exception { final List values = Create.list(); c.parseClassFileWithCollector(new ClassDataCollector() { public void field(Clazz.FieldDef def) { if (def.isEnum()) { values.add(def.name); } } }); return values.toArray(new String[values.size()]); } Meta.Type getType(String rtype) { if (rtype.endsWith("[]")) { rtype = rtype.substring(0, rtype.length() - 2); if (rtype.endsWith("[]")) throw new IllegalArgumentException("Can only handle array of depth one"); } if ("boolean".equals(rtype) || Boolean.class.getName().equals(rtype)) return Meta.Type.Boolean; else if ("byte".equals(rtype) || Byte.class.getName().equals(rtype)) return Meta.Type.Byte; else if ("char".equals(rtype) || Character.class.getName().equals(rtype)) return Meta.Type.Character; else if ("short".equals(rtype) || Short.class.getName().equals(rtype)) return Meta.Type.Short; else if ("int".equals(rtype) || Integer.class.getName().equals(rtype)) return Meta.Type.Integer; else if ("long".equals(rtype) || Long.class.getName().equals(rtype)) return Meta.Type.Long; else if ("float".equals(rtype) || Float.class.getName().equals(rtype)) return Meta.Type.Float; else if ("double".equals(rtype) || Double.class.getName().equals(rtype)) return Meta.Type.Double; else return Meta.Type.String; } @Override public void method(MethodDef mdef) { method = mdef; methods.put(mdef, null); } public String getExtra() { return extra; } public long lastModified() { return 0; } public InputStream openInputStream() throws IOException { final PipedInputStream pin = new PipedInputStream(); final PipedOutputStream pout = new PipedOutputStream(pin); getExecutor().execute(new Runnable() { public void run() { try { write(pout); } catch (IOException e) { // Cause an exception in the other end IO.close(pin); } IO.close(pout); } }); return pin; } private Executor getExecutor() { return reporter.getPlugin(Executor.class); } public void setExtra(String extra) { this.extra = extra; } public void write(OutputStream out) throws IOException { try { finish(); } catch (Exception e) { throw new RuntimeException(e); } PrintWriter pw = new PrintWriter(new OutputStreamWriter(out, "UTF-8")); pw.println(""); metadata.print(0, pw); pw.flush(); } void finish() throws Exception { if (!finished) { finished = true; clazz.parseClassFileWithCollector(this); Meta.OCD ocd = null; if (this.ocdAnnotation != null) ocd = this.ocdAnnotation.getAnnotation(Meta.OCD.class); else ocd = Configurable.createConfigurable(Meta.OCD.class, new HashMap()); // defaults String id = clazz.getFQN(); String name = Clazz.unCamel(Clazz.getShortName(clazz.getFQN())); String description = null; String localization = id; boolean factory = this.factory; if (ocd.id() != null) id = ocd.id(); if (ocd.name() != null) name = ocd.name(); if (ocd.localization() != null) localization = ocd.localization(); if (ocd.description() != null) description = ocd.description(); String pid = id; if (override) { pid = this.designatePid; factory = this.factory; id = this.designatePid; // for the felix problems } else { if (ocdAnnotation.get("factory") != null) { factory = true; } } this.ocd.addAttribute("name", name); this.ocd.addAttribute("id", id); this.ocd.addAttribute("description", description); this.ocd.addAttribute("localization", localization); // do ADs for (Map.Entry entry : methods.entrySet()) addMethod(entry.getKey(), entry.getValue()); this.designate.addAttribute("pid", pid); if (factory) this.designate.addAttribute("factoryPid", pid); this.object.addAttribute("ocdref", id); } } public void setDesignate(String pid, boolean factory) { this.override = true; this.factory = factory; this.designatePid = pid; } } bnd-1.50.0/biz.aQute.bndlib/src/aQute/bnd/build/0000755000175000017500000000000011656076535021055 5ustar drazzibdrazzibbnd-1.50.0/biz.aQute.bndlib/src/aQute/bnd/build/ReflectAction.java0000644000175000017500000000072611656076535024447 0ustar drazzibdrazzibpackage aQute.bnd.build; import java.lang.reflect.*; import aQute.bnd.service.action.*; public class ReflectAction implements Action { String what; public ReflectAction(String what) { this.what = what; } public void execute(Project project, String action) throws Exception { Method m = project.getClass().getMethod(what); m.invoke(project); } public String toString() { return "ra:" + what; } } bnd-1.50.0/biz.aQute.bndlib/src/aQute/bnd/build/ResolverMode.java0000644000175000017500000000010711656076535024324 0ustar drazzibdrazzibpackage aQute.bnd.build; public enum ResolverMode { build, runtime } bnd-1.50.0/biz.aQute.bndlib/src/aQute/bnd/build/ProjectBuilder.java0000644000175000017500000000327411656076535024643 0ustar drazzibdrazzibpackage aQute.bnd.build; import java.io.*; import java.util.*; import aQute.lib.osgi.*; public class ProjectBuilder extends Builder { Project project; boolean initialized; public ProjectBuilder(Project project) { super(project); this.project = project; } public ProjectBuilder(ProjectBuilder builder) { super(builder); this.project = builder.project; } @Override public long lastModified() { return Math.max(project.lastModified(), super.lastModified()); } /** * We put our project and our workspace on the macro path. */ protected Object[] getMacroDomains() { return new Object[] { project, project.getWorkspace() }; } public Builder getSubBuilder() throws Exception { return project.getBuilder(this); } public Project getProject() { return project; } public void init() { try { if (!initialized) { initialized = true; for (Container file : project.getBuildpath()) { addClasspath(file.getFile()); } for (Container file : project.getBootclasspath()) { addClasspath(file.getFile()); } for (File file : project.getAllsourcepath()) { addSourcepath(file); } } } catch (Exception e) { error("init project builder fails", e); } } public List getClasspath() { init(); return super.getClasspath(); } @Override protected void changedFile(File f) { project.getWorkspace().changedFile(f); } } bnd-1.50.0/biz.aQute.bndlib/src/aQute/bnd/build/ProjectLauncher.java0000644000175000017500000002275711656076535025025 0ustar drazzibdrazzibpackage aQute.bnd.build; import java.io.*; import java.util.*; import java.util.concurrent.*; import java.util.jar.*; import aQute.bnd.service.RepositoryPlugin.Strategy; import aQute.lib.osgi.*; import aQute.libg.command.*; import aQute.libg.generics.*; /** * A Project Launcher is a base class to be extended by launchers. Launchers are * JARs that launch a framework and install a number of bundles and then run the * framework. A launcher jar must specify a Launcher-Class manifest header. This * class is instantiated and cast to a LauncherPlugin. This plug in is then * asked to provide a ProjectLauncher. This project launcher is then used by the * project to run the code. Launchers must extend this class. * */ public abstract class ProjectLauncher { private final Project project; private long timeout = 0; private final Collection classpath = new ArrayList(); private List runbundles = Create.list(); private final List runvm = new ArrayList(); private Map runproperties; private Command java; private Map> runsystempackages; private final List activators = Create.list(); private File storageDir; private final List warnings = Create.list(); private final List errors = Create.list(); private boolean trace; private boolean keep; private int framework; public final static int SERVICES = 10111; public final static int NONE = 20123; // MUST BE ALIGNED WITH LAUNCHER public final static int OK = 0; public final static int WARNING = -1; public final static int ERROR = -2; public final static int TIMEDOUT = -3; public final static int UPDATE_NEEDED = -4; public final static int CANCELED = -5; public final static int DUPLICATE_BUNDLE = -6; public final static int RESOLVE_ERROR = -7; public final static int ACTIVATOR_ERROR = -8; public final static int CUSTOM_LAUNCHER = -128; public final static String EMBEDDED_ACTIVATOR = "Embedded-Activator"; public ProjectLauncher(Project project) throws Exception { this.project = project; updateFromProject(); } /** * Collect all the aspect from the project and set the local fields from * them. Should be called * * @throws Exception */ protected void updateFromProject() throws Exception { // pkr: could not use this because this is killing the runtests. // project.refresh(); runbundles.clear(); Collection run = project.getRunbundles(); for (Container container : run) { File file = container.getFile(); if (file != null && (file.isFile() || file.isDirectory())) { runbundles.add(file.getAbsolutePath()); } else { warning("Bundle file \"%s\" does not exist", file.getAbsolutePath()); } } if (project.getRunBuilds()) { File[] builds = project.build(); if (builds != null) for (File file : builds) runbundles.add(file.getAbsolutePath()); } Collection runpath = project.getRunpath(); runsystempackages = project.parseHeader(project.getProperty(Constants.RUNSYSTEMPACKAGES)); framework = getRunframework(project.getProperty(Constants.RUNFRAMEWORK)); trace = Processor.isTrue(project.getProperty(Constants.RUNTRACE)); timeout = Processor.getDuration(project.getProperty(Constants.RUNTIMEOUT), 0); trace = Processor.isTrue(project.getProperty(Constants.RUNTRACE)); // For backward compatibility with bndtools launcher List fws = project.getBundles(Strategy.HIGHEST, project.getProperty("-runfw"), "-runfw"); runpath.addAll(fws); for (Container c : runpath) { addClasspath(c); } runvm.addAll(project.getRunVM()); runproperties = project.getRunProperties(); storageDir = project.getRunStorage(); if (storageDir == null) { storageDir = new File(project.getTarget(), "fw"); } } private int getRunframework(String property) { if (Constants.RUNFRAMEWORK_NONE.equalsIgnoreCase(property)) return NONE; else if (Constants.RUNFRAMEWORK_SERVICES.equalsIgnoreCase(property)) return SERVICES; return SERVICES; } public void addClasspath(Container container) throws Exception { if (container.getError() != null) { project.error("Cannot launch because %s has reported %s", container.getProject(), container.getError()); } else { Collection members = container.getMembers(); for (Container m : members) { String path = m.getFile().getAbsolutePath(); if (!classpath.contains(path)) { classpath.add(path); Manifest manifest = m.getManifest(); if (manifest != null) { Map> exports = project.parseHeader(manifest .getMainAttributes().getValue(Constants.EXPORT_PACKAGE)); for (Map.Entry> e : exports.entrySet()) { if (!runsystempackages.containsKey(e.getKey())) runsystempackages.put(e.getKey(), e.getValue()); } // Allow activators on the runpath. They are called // after // the framework is completely initialized wit the // system // context. String activator = manifest.getMainAttributes() .getValue(EMBEDDED_ACTIVATOR); if (activator != null) activators.add(activator); } } } } } public void addRunBundle(String f) { runbundles.add(f); } public Collection getRunBundles() { return runbundles; } public void addRunVM(String arg) { runvm.add(arg); } public Collection getRunpath() { return classpath; } public Collection getClasspath() { return classpath; } public Collection getRunVM() { return runvm; } public Collection getArguments() { return Collections.emptySet(); } public Map getRunProperties() { return runproperties; } public File getStorageDir() { return storageDir; } public abstract String getMainTypeName(); public abstract void update() throws Exception; public int launch() throws Exception { prepare(); java = new Command(); java.add(project.getProperty("java", "java")); java.add("-cp"); java.add(Processor.join(getClasspath(), File.pathSeparator)); java.addAll(getRunVM()); java.add(getMainTypeName()); java.addAll(getArguments()); if (timeout != 0) java.setTimeout(timeout + 1000, TimeUnit.MILLISECONDS); int result = java.execute(System.in, System.out, System.err); if (result == Integer.MIN_VALUE) return TIMEDOUT; reportResult(result); return result; } protected void reportResult(int result) { switch (result) { case OK: project.trace("Command terminated normal %s", java); break; case TIMEDOUT: project.error("Launch timedout: %s", java); break; case ERROR: project.error("Launch errored: %s", java); break; case WARNING: project.warning("Launch had a warning %s", java); break; default: project.warning("Unknown code %d from launcher: %s", result, java); break; } } public void setTimeout(long timeout, TimeUnit unit) { this.timeout = unit.convert(timeout, TimeUnit.MILLISECONDS); } public long getTimeout() { return this.timeout; } public void cancel() { java.cancel(); } public Map> getSystemPackages() { return runsystempackages; } public void setKeep(boolean keep) { this.keep = keep; } public boolean isKeep() { return keep; } public void setTrace(boolean level) { this.trace = level; } public boolean getTrace() { return this.trace; } /** * Should be called when all the changes to the launchers are set. Will * calculate whatever is necessary for the launcher. * * @throws Exception */ public abstract void prepare() throws Exception; public Project getProject() { return project; } public boolean addActivator(String e) { return activators.add(e); } public Collection getActivators() { return Collections.unmodifiableCollection(activators); } /** * Either NONE or SERVICES to indicate how the remote end launches. NONE * means it should not use the classpath to run a framework. This likely * requires some dummy framework support. SERVICES means it should load the * framework from the claspath. * * @return */ public int getRunFramework() { return framework; } public void setRunFramework(int n) { assert n == NONE || n == SERVICES; this.framework = n; } /** * Add the specification for a set of bundles the runpath if it does not * already is included. This can be used by subclasses to ensure the proper * jars are on the classpath. * * @param defaultSpec * The default spec for default jars */ public void addDefault(String defaultSpec) throws Exception { Collection deflts = project.getBundles(Strategy.HIGHEST, defaultSpec, null); for (Container c : deflts) addClasspath(c); } /** * Create a self executable. */ public Jar executable() throws Exception { throw new UnsupportedOperationException(); } public void clear() { errors.clear(); warnings.clear(); } public List getErrors() { return Collections.unmodifiableList(errors); } public List getWarnings() { return Collections.unmodifiableList(warnings); } protected void error(String message, Object... args) { String formatted = String.format(message, args); errors.add(formatted); } protected void warning(String message, Object... args) { String formatted = String.format(message, args); warnings.add(formatted); } } bnd-1.50.0/biz.aQute.bndlib/src/aQute/bnd/build/CircularDependencyException.java0000644000175000017500000000034511656076535027344 0ustar drazzibdrazzibpackage aQute.bnd.build; public class CircularDependencyException extends Exception { public CircularDependencyException(String string) { super(string); } private static final long serialVersionUID = 1L; } bnd-1.50.0/biz.aQute.bndlib/src/aQute/bnd/build/ScriptAction.java0000644000175000017500000000062011656076535024320 0ustar drazzibdrazzibpackage aQute.bnd.build; import aQute.bnd.service.action.*; public class ScriptAction implements Action { final String script; final String type; public ScriptAction(String type, String script) { this.script = script; this.type = type; } public void execute(Project project, String action) throws Exception { project.script(type, script); } } bnd-1.50.0/biz.aQute.bndlib/src/aQute/bnd/build/Workspace.java0000644000175000017500000001755011656076535023666 0ustar drazzibdrazzibpackage aQute.bnd.build; import java.io.*; import java.lang.ref.*; import java.util.*; import java.util.concurrent.*; import java.util.concurrent.locks.*; import java.util.jar.*; import javax.naming.*; import aQute.bnd.maven.support.*; import aQute.bnd.service.*; import aQute.bnd.service.action.*; import aQute.lib.deployer.*; import aQute.lib.io.*; import aQute.lib.osgi.*; import aQute.libg.reporter.*; public class Workspace extends Processor { public static final String BUILDFILE = "build.bnd"; public static final String CNFDIR = "cnf"; public static final String BNDDIR = "bnd"; public static final String CACHEDIR = "cache"; static Map> cache = newHashMap(); final Map models = newHashMap(); final Map commands = newMap(); final CachedFileRepo cachedRepo; final File buildDir; final Maven maven = new Maven(Processor.getExecutor()); private boolean postpone; /** * This static method finds the workspace and creates a project (or returns * an existing project) * * @param projectDir * @return */ public static Project getProject(File projectDir) throws Exception { projectDir = projectDir.getAbsoluteFile(); assert projectDir.isDirectory(); Workspace ws = getWorkspace(projectDir.getParentFile()); return ws.getProject(projectDir.getName()); } public static Workspace getWorkspace(File parent) throws Exception { File workspaceDir = parent.getAbsoluteFile(); // the cnf directory can actually be a // file that redirects while (workspaceDir.isDirectory()) { File test = new File(workspaceDir, CNFDIR); if (!test.exists()) test = new File(workspaceDir, BNDDIR); if (test.isDirectory()) break; if (test.isFile()) { String redirect = IO.collect(test).trim(); test = getFile(test.getParentFile(), redirect).getAbsoluteFile(); workspaceDir = test; } if (!test.exists()) throw new IllegalArgumentException("No Workspace found from: " + parent); } synchronized (cache) { WeakReference wsr = cache.get(workspaceDir); Workspace ws; if (wsr == null || (ws = wsr.get()) == null) { ws = new Workspace(workspaceDir); cache.put(workspaceDir, new WeakReference(ws)); } return ws; } } public Workspace(File dir) throws Exception { dir = dir.getAbsoluteFile(); dir.mkdirs(); assert dir.isDirectory(); File buildDir = new File(dir, BNDDIR).getAbsoluteFile(); if (!buildDir.isDirectory()) buildDir = new File(dir, CNFDIR).getAbsoluteFile(); this.buildDir = buildDir; File buildFile = new File(buildDir, BUILDFILE).getAbsoluteFile(); if (!buildFile.isFile()) warning("No Build File in " + dir); setProperties(buildFile, dir); propertiesChanged(); cachedRepo = new CachedFileRepo(); } public Project getProject(String bsn) throws Exception { synchronized (models) { Project project = models.get(bsn); if (project != null) return project; File projectDir = getFile(bsn); project = new Project(this, projectDir); if (!project.isValid()) return null; models.put(bsn, project); return project; } } public boolean isPresent(String name) { return models.containsKey(name); } public Collection getCurrentProjects() { return models.values(); } public boolean refresh() { if (super.refresh()) { for (Project project : getCurrentProjects()) { project.propertiesChanged(); } return true; } return false; } @Override public void propertiesChanged() { super.propertiesChanged(); File extDir = new File(this.buildDir, "ext"); File[] extensions = extDir.listFiles(); if (extensions != null) { for (File extension : extensions) { if (extension.getName().endsWith(".bnd")) { try { doIncludeFile(extension, false, getProperties()); } catch (Exception e) { error("PropertiesChanged: " + e.getMessage()); } } } } } public String _workspace(String args[]) { return getBase().getAbsolutePath(); } public void addCommand(String menu, Action action) { commands.put(menu, action); } public void removeCommand(String menu) { commands.remove(menu); } public void fillActions(Map all) { all.putAll(commands); } public Collection getAllProjects() throws Exception { List projects = new ArrayList(); for (File file : getBase().listFiles()) { if (new File(file, Project.BNDFILE).isFile()) projects.add(getProject(file)); } return projects; } /** * Inform any listeners that we changed a file (created/deleted/changed). * * @param f * The changed file */ public void changedFile(File f) { List listeners = getPlugins(BndListener.class); for (BndListener l : listeners) try { l.changed(f); } catch (Exception e) { e.printStackTrace(); } } public void bracket(boolean begin) { List listeners = getPlugins(BndListener.class); for (BndListener l : listeners) try { if (begin) l.begin(); else l.end(); } catch (Exception e) { // who cares? } } /** * Signal a BndListener plugin. * We ran an infinite bug loop :-( */ final ThreadLocal signalBusy = new ThreadLocal(); public void signal(Reporter reporter) { if ( signalBusy.get() != null) return; signalBusy.set(reporter); try { List listeners = getPlugins(BndListener.class); for (BndListener l : listeners) try { l.signal(this); } catch (Exception e) { // who cares? } } catch (Exception e) { // Ignore } finally { signalBusy.set(null); } } @Override public void signal() { signal(this); } private void copy(InputStream in, OutputStream out) throws Exception { byte data[] = new byte[10000]; int size = in.read(data); while (size > 0) { out.write(data, 0, size); size = in.read(data); } } class CachedFileRepo extends FileRepo { final Lock lock = new ReentrantLock(); boolean inited; CachedFileRepo() { super("cache", getFile(buildDir, CACHEDIR), false); } protected void init() throws Exception { if (lock.tryLock(50, TimeUnit.SECONDS) == false) throw new TimeLimitExceededException( "Cached File Repo is locked and can't acquire it"); try { if (!inited) { inited = true; root.mkdirs(); if (!root.isDirectory()) throw new IllegalArgumentException("Cannot create cache dir " + root); InputStream in = getClass().getResourceAsStream(EMBEDDED_REPO); if (in != null) unzip(in, root); else { System.out.println("!!!! Couldn't find embedded-repo.jar in bundle "); error("Couldn't find embedded-repo.jar in bundle "); } } } finally { lock.unlock(); } } void unzip(InputStream in, File dir) throws Exception { try { JarInputStream jin = new JarInputStream(in); JarEntry jentry = jin.getNextJarEntry(); while (jentry != null) { if (!jentry.isDirectory()) { File dest = Processor.getFile(dir, jentry.getName()); if (!dest.isFile() || dest.lastModified() < jentry.getTime() || jentry.getTime() == 0) { dest.getParentFile().mkdirs(); FileOutputStream out = new FileOutputStream(dest); try { copy(jin, out); } finally { out.close(); } } } jentry = jin.getNextJarEntry(); } } finally { in.close(); } } } public List getRepositories() { return getPlugins(RepositoryPlugin.class); } public static Workspace getWorkspace(String path) throws Exception { File file = IO.getFile(new File(""), path); return getWorkspace(file); } public Maven getMaven() { return maven; } @Override protected void setTypeSpecificPlugins(Set list) { super.setTypeSpecificPlugins(list); list.add(maven); list.add(cachedRepo); } } bnd-1.50.0/biz.aQute.bndlib/src/aQute/bnd/build/Container.java0000644000175000017500000001105511656076535023644 0ustar drazzibdrazzibpackage aQute.bnd.build; import java.io.*; import java.util.*; import java.util.jar.*; import aQute.bnd.service.RepositoryPlugin.Strategy; import aQute.lib.osgi.*; public class Container { public enum TYPE { REPO, PROJECT, PROJECT_BUNDLE, EXTERNAL, LIBRARY, ERROR } final File file; final TYPE type; final String bsn; final String version; final String error; final Project project; volatile Map attributes; private long manifestTime; private Manifest manifest; Container(Project project, String bsn, String version, TYPE type, File source, String error, Map attributes) { this.bsn = bsn; this.version = version; this.type = type; this.file = source != null ? source : new File("/" + bsn + ":" + version + ":" + type); this.project = project; this.error = error; if (attributes == null || attributes.isEmpty()) this.attributes = Collections.emptyMap(); else this.attributes = attributes; } public Container(Project project, File file) { this(project, file.getName(), "project", TYPE.PROJECT, file, null, null); } public Container(File file) { this(null, file.getName(), "project", TYPE.EXTERNAL, file, null, null); } public File getFile() { return file; } /** * Iterate over the containers and get the files they represent * * @param files * @return * @throws Exception */ public boolean contributeFiles(List files, Processor reporter) throws Exception { switch (type) { case EXTERNAL: case REPO: files.add(file); return true; case PROJECT: File[] fs = project.build(); reporter.getInfo(project); if (fs == null) return false; for (File f : fs) files.add(f); return true; case LIBRARY: List containers = getMembers(); for (Container container : containers) { if (!container.contributeFiles(files, reporter)) return false; } return true; case ERROR: reporter.error(error); return false; } return false; } public String getBundleSymbolicName() { return bsn; } public String getVersion() { return version; } public TYPE getType() { return type; } public String getError() { return error; } public boolean equals(Object other) { if (other instanceof Container) return file.equals(((Container) other).file); else return false; } public int hashCode() { return file.hashCode(); } public Project getProject() { return project; } /** * Must show the file name or the error formatted as a file name * * @return */ public String toString() { if (getError() != null) return "/error/" + getError(); else return getFile().getAbsolutePath(); } public Map getAttributes() { return attributes; } public void putAttribute(String name, String value) { if (attributes == Collections.emptyMap()) attributes = new HashMap(1); attributes.put(name, value); } /** * Return the this if this is anything else but a library. If it is a * library, return the members. This could work recursively, e.g., libraries * can point to libraries. * * @return * @throws Exception */ public List getMembers() throws Exception { List result = project.newList(); // Are ww a library? If no, we are the result if (getType() == TYPE.LIBRARY) { // We are a library, parse the file. This is // basically a specification clause per line. // I.e. you can do bsn; version, bsn2; version. But also // spread it out over lines. InputStream in = new FileInputStream(file); BufferedReader rd = new BufferedReader(new InputStreamReader(in, Constants.DEFAULT_CHARSET)); try { String line; while ((line = rd.readLine()) != null) { line = line.trim(); if (!line.startsWith("#") && line.length() > 0) { List list = project.getBundles(Strategy.HIGHEST, line, null); result.addAll(list); } } } finally { in.close(); } } else result.add(this); return result; } /** * Answer the manifest for this container (if possible). Manifest is cached * until the file is renewed. */ public Manifest getManifest() throws Exception { if (getError() != null || getFile() == null) return null; if (manifestTime < getFile().lastModified()) { InputStream in = new FileInputStream(getFile()); try { JarInputStream jin = new JarInputStream(in); manifest = jin.getManifest(); jin.close(); manifestTime = getFile().lastModified(); } finally { in.close(); } } return manifest; } } bnd-1.50.0/biz.aQute.bndlib/src/aQute/bnd/build/Project.java0000644000175000017500000015206511656076535023337 0ustar drazzibdrazzibpackage aQute.bnd.build; import java.io.*; import java.lang.reflect.*; import java.net.*; import java.util.*; import java.util.Map.Entry; import java.util.concurrent.*; import java.util.concurrent.locks.*; import java.util.jar.*; import aQute.bnd.help.*; import aQute.bnd.maven.support.*; import aQute.bnd.service.*; import aQute.bnd.service.RepositoryPlugin.Strategy; import aQute.bnd.service.action.*; import aQute.lib.io.*; import aQute.lib.osgi.*; import aQute.lib.osgi.eclipse.*; import aQute.libg.generics.*; import aQute.libg.header.*; import aQute.libg.sed.*; import aQute.libg.version.*; /** * This class is NOT threadsafe * * @author aqute * */ public class Project extends Processor { final static String DEFAULT_ACTIONS = "build; label='Build', test; label='Test', run; label='Run', clean; label='Clean', release; label='Release', refreshAll; label=Refresh, deploy;label=Deploy"; public final static String BNDFILE = "bnd.bnd"; public final static String BNDCNF = "cnf"; final Workspace workspace; boolean preparedPaths; final Collection dependson = new LinkedHashSet(); final Collection buildpath = new LinkedHashSet(); final Collection testpath = new LinkedHashSet(); final Collection runpath = new LinkedHashSet(); final Collection runbundles = new LinkedHashSet(); File runstorage; final Collection sourcepath = new LinkedHashSet(); final Collection allsourcepath = new LinkedHashSet(); final Collection bootclasspath = new LinkedHashSet(); final Lock lock = new ReentrantLock(true); volatile String lockingReason; volatile Thread lockingThread; File output; File target; boolean inPrepare; int revision; File files[]; private long buildtime; static List trail = new ArrayList(); boolean delayRunDependencies = false; public Project(Workspace workspace, File projectDir, File buildFile) throws Exception { super(workspace); this.workspace = workspace; setFileMustExist(false); setProperties(buildFile); assert workspace != null; // For backward compatibility reasons, we also read readBuildProperties(); } public Project(Workspace workspace, File buildDir) throws Exception { this(workspace, buildDir, new File(buildDir, BNDFILE)); } private void readBuildProperties() throws Exception { try { File f = getFile("build.properties"); if (f.isFile()) { Properties p = loadProperties(f); for (Enumeration e = p.propertyNames(); e.hasMoreElements();) { String key = (String) e.nextElement(); String newkey = key; if (key.indexOf('$') >= 0) { newkey = getReplacer().process(key); } setProperty(newkey, p.getProperty(key)); } } } catch (Exception e) { e.printStackTrace(); } } public static Project getUnparented(File propertiesFile) throws Exception { propertiesFile = propertiesFile.getAbsoluteFile(); Workspace workspace = new Workspace(propertiesFile.getParentFile()); Project project = new Project(workspace, propertiesFile.getParentFile()); project.setProperties(propertiesFile); project.setFileMustExist(true); return project; } public synchronized boolean isValid() { return getBase().isDirectory() && getPropertiesFile().isFile(); } /** * Return a new builder that is nicely setup for this project. Please close * this builder after use. * * @param parent * The project builder to use as parent, use this project if null * @return * @throws Exception */ public synchronized ProjectBuilder getBuilder(ProjectBuilder parent) throws Exception { ProjectBuilder builder; if (parent == null) builder = new ProjectBuilder(this); else builder = new ProjectBuilder(parent); builder.setBase(getBase()); return builder; } public synchronized int getChanged() { return revision; } /* * Indicate a change in the external world that affects our build. This will * clear any cached results. */ public synchronized void setChanged() { // if (refresh()) { preparedPaths = false; files = null; revision++; // } } public Workspace getWorkspace() { return workspace; } public String toString() { return getBase().getName(); } /** * Set up all the paths */ public synchronized void prepare() throws Exception { if (!isValid()) { warning("Invalid project attempts to prepare: %s", this); return; } if (inPrepare) throw new CircularDependencyException(trail.toString() + "," + this); trail.add(this); try { if (!preparedPaths) { inPrepare = true; try { dependson.clear(); buildpath.clear(); sourcepath.clear(); allsourcepath.clear(); bootclasspath.clear(); testpath.clear(); runpath.clear(); runbundles.clear(); // We use a builder to construct all the properties for // use. setProperty("basedir", getBase().getAbsolutePath()); // If a bnd.bnd file exists, we read it. // Otherwise, we just do the build properties. if (!getPropertiesFile().isFile() && new File(getBase(), ".classpath").isFile()) { // Get our Eclipse info, we might depend on other // projects // though ideally this should become empty and void doEclipseClasspath(); } // Calculate our source directory File src = getSrc(); if (src.isDirectory()) { sourcepath.add(src); allsourcepath.add(src); } else sourcepath.add(getBase()); // Set default bin directory output = getFile(getProperty("bin", "bin")).getAbsoluteFile(); if (!output.exists()) { output.mkdirs(); getWorkspace().changedFile(output); } if (!output.isDirectory()) error("Can not find output directory: " + output); else if (!buildpath.contains(output)) buildpath.add(new Container(this, output)); // Where we store all our generated stuff. target = getFile(getProperty("target", "generated")); if (!target.exists()) { target.mkdirs(); getWorkspace().changedFile(target); } // Where the launched OSGi framework stores stuff String runStorageStr = getProperty(Constants.RUNSTORAGE); runstorage = runStorageStr != null ? getFile(runStorageStr) : null; // We might have some other projects we want build // before we do anything, but these projects are not in // our path. The -dependson allows you to build them before. List dependencies = new ArrayList(); // dependencies.add( getWorkspace().getProject("cnf")); String dp = getProperty(Constants.DEPENDSON); Set requiredProjectNames = parseHeader(dp).keySet(); List dcs = getPlugins(DependencyContributor.class); for (DependencyContributor dc : dcs) dc.addDependencies(this, requiredProjectNames); for (String p : requiredProjectNames) { Project required = getWorkspace().getProject(p); if (required == null) error("No such project " + required + " on " + Constants.DEPENDSON); else { dependencies.add(required); } } // We have two paths that consists of repo files, projects, // or some other stuff. The doPath routine adds them to the // path and extracts the projects so we can build them // before. doPath(buildpath, dependencies, parseBuildpath(), bootclasspath); doPath(testpath, dependencies, parseTestpath(), bootclasspath); if (!delayRunDependencies) { doPath(runpath, dependencies, parseRunpath(), null); doPath(runbundles, dependencies, parseRunbundles(), null); } // We now know all dependent projects. But we also depend // on whatever those projects depend on. This creates an // ordered list without any duplicates. This of course // assumes // that there is no circularity. However, this is checked // by the inPrepare flag, will throw an exception if we // are circular. Set done = new HashSet(); done.add(this); allsourcepath.addAll(sourcepath); for (Project project : dependencies) project.traverse(dependson, done); for (Project project : dependson) { allsourcepath.addAll(project.getSourcePath()); } if (isOk()) preparedPaths = true; } finally { inPrepare = false; } } } finally { trail.remove(this); } } public File getSrc() { return new File(getBase(), getProperty("src", "src")); } private void traverse(Collection dependencies, Set visited) throws Exception { if (visited.contains(this)) return; visited.add(this); for (Project project : getDependson()) project.traverse(dependencies, visited); dependencies.add(this); } /** * Iterate over the entries and place the projects on the projects list and * all the files of the entries on the resultpath. * * @param resultpath * The list that gets all the files * @param projects * The list that gets any projects that are entries * @param entries * The input list of classpath entries */ private void doPath(Collection resultpath, Collection projects, Collection entries, Collection bootclasspath) { for (Container cpe : entries) { if (cpe.getError() != null) error(cpe.getError()); else { if (cpe.getType() == Container.TYPE.PROJECT) { projects.add(cpe.getProject()); } if (bootclasspath != null && cpe.getBundleSymbolicName().startsWith("ee.") || cpe.getAttributes().containsKey("boot")) bootclasspath.add(cpe); else resultpath.add(cpe); } } } /** * Parse the list of bundles that are a prerequisite to this project. * * Bundles are listed in repo specific names. So we just let our repo * plugins iterate over the list of bundles and we get the highest version * from them. * * @return */ private List parseBuildpath() throws Exception { List bundles = getBundles(Strategy.LOWEST, getProperty(Constants.BUILDPATH), Constants.BUILDPATH); appendPackages(Strategy.LOWEST, getProperty(Constants.BUILDPACKAGES), bundles, ResolverMode.build); return bundles; } private List parseRunpath() throws Exception { return getBundles(Strategy.HIGHEST, getProperty(Constants.RUNPATH), Constants.RUNPATH); } private List parseRunbundles() throws Exception { return getBundles(Strategy.HIGHEST, getProperty(Constants.RUNBUNDLES), Constants.RUNBUNDLES); } private List parseTestpath() throws Exception { return getBundles(Strategy.HIGHEST, getProperty(Constants.TESTPATH), Constants.TESTPATH); } /** * Analyze the header and return a list of files that should be on the * build, test or some other path. The list is assumed to be a list of bsns * with a version specification. The special case of version=project * indicates there is a project in the same workspace. The path to the * output directory is calculated. The default directory ${bin} can be * overridden with the output attribute. * * @param strategy * STRATEGY_LOWEST or STRATEGY_HIGHEST * @param spec * The header * @return */ public List getBundles(Strategy strategyx, String spec, String source) throws Exception { List result = new ArrayList(); Map> bundles = parseHeader(spec); try { for (Iterator>> i = bundles.entrySet().iterator(); i .hasNext();) { Map.Entry> entry = i.next(); String bsn = entry.getKey(); Map attrs = entry.getValue(); Container found = null; // Check if we have to use the maven pom ... if (bsn.equals("pom")) { doMavenPom(strategyx, result, attrs.get("scope")); continue; } String versionRange = attrs.get("version"); if (versionRange != null) { if (versionRange.equals("latest") || versionRange.equals("snapshot")) { found = getBundle(bsn, versionRange, strategyx, attrs); } } if (found == null) { if (versionRange != null && (versionRange.equals("project") || versionRange.equals("latest"))) { Project project = getWorkspace().getProject(bsn); if (project != null && project.exists()) { File f = project.getOutput(); found = new Container(project, bsn, versionRange, Container.TYPE.PROJECT, f, null, attrs); } else { error("Reference to project that does not exist in workspace\n" + " Project %s\n" + " Specification %s", bsn, spec); continue; } } else if (versionRange != null && versionRange.equals("file")) { File f = getFile(bsn); String error = null; if (!f.exists()) error = "File does not exist: " + f.getAbsolutePath(); if (f.getName().endsWith(".lib")) { found = new Container(this, bsn, "file", Container.TYPE.LIBRARY, f, error, attrs); } else { found = new Container(this, bsn, "file", Container.TYPE.EXTERNAL, f, error, attrs); } } else { found = getBundle(bsn, versionRange, strategyx, attrs); } } if (found != null) { List libs = found.getMembers(); for (Container cc : libs) { if (result.contains(cc)) warning("Multiple bundles with the same final URL: " + cc); result.add(cc); } } else { // Oops, not a bundle in sight :-( Container x = new Container(this, bsn, versionRange, Container.TYPE.ERROR, null, bsn + ";version=" + versionRange + " not found", attrs); result.add(x); warning("Can not find URL for bsn " + bsn); } } } catch (CircularDependencyException e) { String message = e.getMessage(); if (source != null) message = String.format("%s (from property: %s)", message, source); error("Circular dependency detected from project %s: %s", e, getName(), message); } catch (Exception e) { error("Unexpected error while trying to get the bundles from " + spec, e); e.printStackTrace(); } return result; } /** * Just calls a new method with a default parm. * * @throws Exception * */ Collection getBundles(Strategy strategy, String spec) throws Exception { return getBundles(strategy, spec, null); } /** * Calculates the containers required to fulfil the {@code -buildpackages} * instruction, and appends them to the existing list of containers. * * @param strategyx * The package-version disambiguation strategy. * @param spec * The value of the @{code -buildpackages} instruction. * @throws Exception */ public void appendPackages(Strategy strategyx, String spec, List resolvedBundles, ResolverMode mode) throws Exception { Map pkgResolvedBundles = new HashMap(); List>> queue = new LinkedList>>(); queue.addAll(parseHeader(spec).entrySet()); while (!queue.isEmpty()) { Entry> entry = queue.remove(0); String pkgName = entry.getKey(); Map attrs = entry.getValue(); Container found = null; String versionRange = attrs.get(Constants.VERSION_ATTRIBUTE); if ("latest".equals(versionRange) || "snapshot".equals(versionRange)) found = getPackage(pkgName, versionRange, strategyx, attrs, mode); if (found == null) found = getPackage(pkgName, versionRange, strategyx, attrs, mode); if (found != null) { if (resolvedBundles.contains(found)) { // Don't add his bundle because it was already included // using -buildpath } else { List libs = found.getMembers(); for (Container cc : libs) { Container existing = pkgResolvedBundles.get(cc.file); if (existing != null) addToPackageList(existing, attrs.get("packages")); else { addToPackageList(cc, attrs.get("packages")); pkgResolvedBundles.put(cc.file, cc); } String importUses = cc.getAttributes().get("import-uses"); if (importUses != null) queue.addAll(0, parseHeader(importUses).entrySet()); } } } else { // Unable to resolve Container x = new Container(this, "X", versionRange, Container.TYPE.ERROR, null, "package " + pkgName + ";version=" + versionRange + " not found", attrs); resolvedBundles.add(x); warning("Can not find URL for package " + pkgName); } } for (Container container : pkgResolvedBundles.values()) { resolvedBundles.add(container); } } static void mergeNames(String names, Set set) { StringTokenizer tokenizer = new StringTokenizer(names, ","); while (tokenizer.hasMoreTokens()) set.add(tokenizer.nextToken().trim()); } static String flatten(Set names) { StringBuilder builder = new StringBuilder(); boolean first = true; for (String name : names) { if (!first) builder.append(','); builder.append(name); first = false; } return builder.toString(); } static void addToPackageList(Container container, String newPackageNames) { Set merged = new HashSet(); String packageListStr = container.attributes.get("packages"); if (packageListStr != null) mergeNames(packageListStr, merged); if (newPackageNames != null) mergeNames(newPackageNames, merged); container.putAttribute("packages", flatten(merged)); } /** * Find a container to fulfil a package requirement * * @param packageName * The package required * @param range * The package version range required * @param strategyx * The package-version disambiguation strategy * @param attrs * Other attributes specified by the search. * @return * @throws Exception */ public Container getPackage(String packageName, String range, Strategy strategyx, Map attrs, ResolverMode mode) throws Exception { if ("snapshot".equals(range)) return new Container(this, "", range, Container.TYPE.ERROR, null, "snapshot not supported for package lookups", null); if (attrs == null) attrs = new HashMap(2); attrs.put("package", packageName); attrs.put("mode", mode.name()); Strategy useStrategy = findStrategy(attrs, strategyx, range); List plugins = getPlugins(RepositoryPlugin.class); for (RepositoryPlugin plugin : plugins) { try { File result = plugin.get(null, range, useStrategy, attrs); if (result != null) { if (result.getName().endsWith("lib")) return new Container(this, result.getName(), range, Container.TYPE.LIBRARY, result, null, attrs); else return new Container(this, result.getName(), range, Container.TYPE.REPO, result, null, attrs); } } catch (Exception e) { // Ignore... lots of repos will fail here } } return new Container(this, "X", range, Container.TYPE.ERROR, null, "package " + packageName + ";version=" + range + " Not found in " + plugins, null); } private Strategy findStrategy(Map attrs, Strategy defaultStrategy, String versionRange) { Strategy useStrategy = defaultStrategy; String overrideStrategy = attrs.get("strategy"); if (overrideStrategy != null) { if ("highest".equalsIgnoreCase(overrideStrategy)) useStrategy = Strategy.HIGHEST; else if ("lowest".equalsIgnoreCase(overrideStrategy)) useStrategy = Strategy.LOWEST; else if ("exact".equalsIgnoreCase(overrideStrategy)) useStrategy = Strategy.EXACT; } if ("latest".equals(versionRange)) useStrategy = Strategy.HIGHEST; return useStrategy; } /** * The user selected pom in a path. This will place the pom as well as its * dependencies on the list * * @param strategyx * the strategy to use. * @param result * The list of result containers * @param attrs * The attributes * @throws Exception * anything goes wrong */ public void doMavenPom(Strategy strategyx, List result, String action) throws Exception { File pomFile = getFile("pom.xml"); if (!pomFile.isFile()) error("Specified to use pom.xml but the project directory does not contain a pom.xml file"); else { ProjectPom pom = getWorkspace().getMaven().createProjectModel(pomFile); if (action == null) action = "compile"; Pom.Scope act = Pom.Scope.valueOf(action); Set dependencies = pom.getDependencies(act); for (Pom sub : dependencies) { File artifact = sub.getArtifact(); Container container = new Container(artifact); result.add(container); } } } public Collection getDependson() throws Exception { prepare(); return dependson; } public Collection getBuildpath() throws Exception { prepare(); return buildpath; } public Collection getTestpath() throws Exception { prepare(); return testpath; } /** * Handle dependencies for paths that are calculated on demand. * * @param testpath2 * @param parseTestpath */ private void justInTime(Collection path, List entries) { if (delayRunDependencies && path.isEmpty()) doPath(path, dependson, entries, null); } public Collection getRunpath() throws Exception { prepare(); justInTime(runpath, parseRunpath()); return runpath; } public Collection getRunbundles() throws Exception { prepare(); justInTime(runbundles, parseRunbundles()); return runbundles; } public File getRunStorage() throws Exception { prepare(); return runstorage; } public boolean getRunBuilds() { boolean result; String runBuildsStr = getProperty(Constants.RUNBUILDS); if (runBuildsStr == null) result = !getPropertiesFile().getName().toLowerCase() .endsWith(Constants.DEFAULT_BNDRUN_EXTENSION); else result = Boolean.parseBoolean(runBuildsStr); return result; } public Collection getSourcePath() throws Exception { prepare(); return sourcepath; } public Collection getAllsourcepath() throws Exception { prepare(); return allsourcepath; } public Collection getBootclasspath() throws Exception { prepare(); return bootclasspath; } public File getOutput() throws Exception { prepare(); return output; } private void doEclipseClasspath() throws Exception { EclipseClasspath eclipse = new EclipseClasspath(this, getWorkspace().getBase(), getBase()); eclipse.setRecurse(false); // We get the file directories but in this case we need // to tell ant that the project names for (File dependent : eclipse.getDependents()) { Project required = workspace.getProject(dependent.getName()); dependson.add(required); } for (File f : eclipse.getClasspath()) { buildpath.add(new Container(f)); } for (File f : eclipse.getBootclasspath()) { bootclasspath.add(new Container(f)); } sourcepath.addAll(eclipse.getSourcepath()); allsourcepath.addAll(eclipse.getAllSources()); output = eclipse.getOutput(); } public String _p_dependson(String args[]) throws Exception { return list(args, toFiles(getDependson())); } private Collection toFiles(Collection projects) { List files = new ArrayList(); for (Project p : projects) { files.add(p.getBase()); } return files; } public String _p_buildpath(String args[]) throws Exception { return list(args, getBuildpath()); } public String _p_testpath(String args[]) throws Exception { return list(args, getRunpath()); } public String _p_sourcepath(String args[]) throws Exception { return list(args, getSourcePath()); } public String _p_allsourcepath(String args[]) throws Exception { return list(args, getAllsourcepath()); } public String _p_bootclasspath(String args[]) throws Exception { return list(args, getBootclasspath()); } public String _p_output(String args[]) throws Exception { if (args.length != 1) throw new IllegalArgumentException("${output} should not have arguments"); return getOutput().getAbsolutePath(); } private String list(String[] args, Collection list) { if (args.length > 3) throw new IllegalArgumentException("${" + args[0] + "[;]} can only take a separator as argument, has " + Arrays.toString(args)); String separator = ","; if (args.length == 2) { separator = args[1]; } return join(list, separator); } protected Object[] getMacroDomains() { return new Object[] { workspace }; } public File release(Jar jar) throws Exception { String name = getProperty(Constants.RELEASEREPO); return release(name, jar); } /** * Release * * @param name * The repository name * @param jar * @return * @throws Exception */ public File release(String name, Jar jar) throws Exception { trace("release %s", name); List plugins = getPlugins(RepositoryPlugin.class); RepositoryPlugin rp = null; for (RepositoryPlugin plugin : plugins) { if (!plugin.canWrite()) { continue; } if (name == null) { rp = plugin; break; } else if (name.equals(plugin.getName())) { rp = plugin; break; } } if (rp != null) { try { File file = rp.put(jar); trace("Released %s to file %s in repository %s", jar.getName(), file, rp); } catch (Exception e) { error("Deploying " + jar.getName() + " on " + rp.getName(), e); } finally { jar.close(); } } else if (name == null) error("There is no writable repository (no repo name specified)"); else error("Cannot find a writeable repository with the name %s from the repositiories %s", name, plugins); return null; } public void release(boolean test) throws Exception { String name = getProperty(Constants.RELEASEREPO); release(name, test); } /** * Release * * @param name * The respository name * @param test * Run testcases * @throws Exception */ public void release(String name, boolean test) throws Exception { trace("release"); File[] jars = build(test); // If build fails jars will be null if (jars == null) { trace("no jars being build"); return; } trace("build ", Arrays.toString(jars)); for (File jar : jars) { Jar j = new Jar(jar); try { release(name, j); } finally { j.close(); } } } /** * Get a bundle from one of the plugin repositories. If an exact version is * required we just return the first repository found (in declaration order * in the build.bnd file). * * @param bsn * The bundle symbolic name * @param range * The version range * @param lowest * set to LOWEST or HIGHEST * @return the file object that points to the bundle or null if not found * @throws Exception * when something goes wrong */ public Container getBundle(String bsn, String range, Strategy strategy, Map attrs) throws Exception { if (range == null) range = "0"; if ("snapshot".equals(range)) { return getBundleFromProject(bsn, attrs); } Strategy useStrategy = strategy; if ("latest".equals(range)) { Container c = getBundleFromProject(bsn, attrs); if (c != null) return c; useStrategy = Strategy.HIGHEST; } useStrategy = overrideStrategy(attrs, useStrategy); List plugins = getPlugins(RepositoryPlugin.class); if (useStrategy == Strategy.EXACT) { // For an exact range we just iterate over the repos // and return the first we find. for (RepositoryPlugin plugin : plugins) { File result = plugin.get(bsn, range, Strategy.EXACT, attrs); if (result != null) return toContainer(bsn, range, attrs, result); } } else { VersionRange versionRange = "latest".equals(range) ? new VersionRange("0") : new VersionRange(range); // We have a range search. Gather all the versions in all the repos // and make a decision on that choice. If the same version is found // in // multiple repos we take the first SortedMap versions = new TreeMap(); for (RepositoryPlugin plugin : plugins) { try { List vs = plugin.versions(bsn); if (vs != null) { for (Version v : vs) { if (!versions.containsKey(v) && versionRange.includes(v)) versions.put(v, plugin); } } } catch (UnsupportedOperationException ose) { // We have a plugin that cannot list versions, try // if it has this specific version // The main reaosn for this code was the Maven Remote Repository // To query, we must have a real version if (!versions.isEmpty() && Verifier.isVersion(range)) { File file = plugin.get(bsn, range, useStrategy, attrs); // and the entry must exist // if it does, return this as a result if (file != null) return toContainer(bsn, range, attrs, file); } } } // Verify if we found any, if so, we use the strategy to pick // the first or last if (!versions.isEmpty()) { Version provider = null; switch (useStrategy) { case HIGHEST: provider = versions.lastKey(); break; case LOWEST: provider = versions.firstKey(); break; } if (provider != null) { RepositoryPlugin repo = versions.get(provider); String version = provider.toString(); File result = repo.get(bsn, version, Strategy.EXACT, attrs); return toContainer(bsn, version, attrs, result); } else error("Unexpected, found versions %s but then not provider for startegy %s?", versions, useStrategy); } } // // If we get this far we ran into an error somewhere return new Container(this, bsn, range, Container.TYPE.ERROR, null, bsn + ";version=" + range + " Not found in " + plugins, null); } /** * @param attrs * @param useStrategy * @return */ protected Strategy overrideStrategy(Map attrs, Strategy useStrategy) { if (attrs != null) { String overrideStrategy = attrs.get("strategy"); if (overrideStrategy != null) { if ("highest".equalsIgnoreCase(overrideStrategy)) useStrategy = Strategy.HIGHEST; else if ("lowest".equalsIgnoreCase(overrideStrategy)) useStrategy = Strategy.LOWEST; else if ("exact".equalsIgnoreCase(overrideStrategy)) useStrategy = Strategy.EXACT; } } return useStrategy; } /** * @param bsn * @param range * @param attrs * @param result * @return */ protected Container toContainer(String bsn, String range, Map attrs, File result) { if (result == null) { System.out.println("Huh?"); } if (result.getName().endsWith("lib")) return new Container(this, bsn, range, Container.TYPE.LIBRARY, result, null, attrs); else return new Container(this, bsn, range, Container.TYPE.REPO, result, null, attrs); } /** * Look for the bundle in the workspace. The premise is that the bsn must * start with the project name. * * @param bsn * The bsn * @param attrs * Any attributes * @return * @throws Exception */ private Container getBundleFromProject(String bsn, Map attrs) throws Exception { String pname = bsn; while (true) { Project p = getWorkspace().getProject(pname); if (p != null && p.isValid()) { Container c = p.getDeliverable(bsn, attrs); return c; } int n = pname.lastIndexOf('.'); if (n <= 0) return null; pname = pname.substring(0, n); } } /** * Deploy the file (which must be a bundle) into the repository. * * @param name * The repository name * @param file * bundle */ public void deploy(String name, File file) throws Exception { List plugins = getPlugins(RepositoryPlugin.class); ; RepositoryPlugin rp = null; for (RepositoryPlugin plugin : plugins) { if (!plugin.canWrite()) { continue; } if (name == null) { rp = plugin; break; } else if (name.equals(plugin.getName())) { rp = plugin; break; } } if (rp != null) { Jar jar = new Jar(file); try { rp.put(jar); return; } catch (Exception e) { error("Deploying " + file + " on " + rp.getName(), e); } finally { jar.close(); } return; } trace("No repo found " + file); throw new IllegalArgumentException("No repository found for " + file); } /** * Deploy the file (which must be a bundle) into the repository. * * @param file * bundle */ public void deploy(File file) throws Exception { String name = getProperty(Constants.DEPLOYREPO); deploy(name, file); } /** * Deploy the current project to a repository * * @throws Exception */ public void deploy() throws Exception { Map> deploy = parseHeader(getProperty(DEPLOY)); if (deploy.isEmpty()) { warning("Deploying but %s is not set to any repo", DEPLOY); return; } File[] outputs = getBuildFiles(); for (File output : outputs) { Jar jar = new Jar(output); try { for (Deploy d : getPlugins(Deploy.class)) { trace("Deploying %s to: %s", jar, d); try { if (d.deploy(this, jar)) trace("deployed %s successfully to %s", output, d); } catch (Exception e) { error("Error while deploying %s, %s", this, e); e.printStackTrace(); } } } finally { jar.close(); } } } /** * Macro access to the repository * * ${repo;[;[;]]} */ public String _repo(String args[]) throws Exception { if (args.length < 2) throw new IllegalArgumentException( "Too few arguments for repo, syntax=: ${repo ';' [ ; [; ('HIGHEST'|'LOWEST')]}"); String bsns = args[1]; String version = null; Strategy strategy = Strategy.HIGHEST; if (args.length > 2) { version = args[2]; if (args.length == 4) { if (args[3].equalsIgnoreCase("HIGHEST")) strategy = Strategy.HIGHEST; else if (args[3].equalsIgnoreCase("LOWEST")) strategy = Strategy.LOWEST; else if (args[3].equalsIgnoreCase("EXACT")) strategy = Strategy.EXACT; else error("${repo;;;<'highest'|'lowest'|'exact'>} macro requires a strategy of 'highest' or 'lowest', and is " + args[3]); } } Collection parts = split(bsns); List paths = new ArrayList(); for (String bsn : parts) { Container container = getBundle(bsn, version, strategy, null); add(paths, container); } return join(paths); } private void add(List paths, Container container) throws Exception { if (container.getType() == Container.TYPE.LIBRARY) { List members = container.getMembers(); for (Container sub : members) { add(paths, sub); } } else { if (container.getError() == null) paths.add(container.getFile().getAbsolutePath()); else { paths.add("<<${repo} = " + container.getBundleSymbolicName() + "-" + container.getVersion() + " : " + container.getError() + ">>"); if (isPedantic()) { warning("Could not expand repo path request: %s ", container); } } } } public File getTarget() throws Exception { prepare(); return target; } /** * This is the external method that will pre-build any dependencies if it is * out of date. * * @param underTest * @return * @throws Exception */ public File[] build(boolean underTest) throws Exception { if (getProperty(NOBUNDLES) != null) return null; if (getProperty("-nope") != null) { warning("Please replace -nope with %s", NOBUNDLES); return null; } if (isStale()) { trace("Building " + this); files = buildLocal(underTest); } return files; } /** * Return the files */ public File[] getFiles() { return files; } /** * Check if this project needs building */ public boolean isStale() throws Exception { if (files == null) return true; long localTime = getBuildTime(); if (lastModified() > localTime) return true; for (Project dependency : getDependson()) { if (dependency.isStale()) return true; if (dependency.getBuildTime() > localTime) return true; if (dependency.lastModified() > localTime) return true; } return false; } /** * This method must only be called when it is sure that the project has been * build before in the same session. * * It is a bit yucky, but ant creates different class spaces which makes it * hard to detect we already build it. * * @return */ public File[] getBuildFiles() throws Exception { return getBuildFiles(true); } public File[] getBuildFiles(boolean buildIfAbsent) throws Exception { File f = new File(getTarget(), BUILDFILES); if (f.isFile()) { FileReader fin = new FileReader(f); BufferedReader rdr = new BufferedReader(fin); try { List files = newList(); for (String s = rdr.readLine(); s != null; s = rdr.readLine()) { s = s.trim(); File ff = new File(s); if (!ff.isFile()) { error("buildfile lists file but the file does not exist %s", ff); } else files.add(ff); } return files.toArray(new File[files.size()]); } finally { fin.close(); } } if (buildIfAbsent) return buildLocal(false); else return null; } /** * Build without doing any dependency checking. Make sure any dependent * projects are built first. * * @param underTest * @return * @throws Exception */ public File[] buildLocal(boolean underTest) throws Exception { if (getProperty(NOBUNDLES) != null) return null; long buildtime = System.currentTimeMillis(); File bfs = new File(getTarget(), BUILDFILES); bfs.delete(); files = null; ProjectBuilder builder = getBuilder(null); if (underTest) builder.setProperty(Constants.UNDERTEST, "true"); Jar jars[] = builder.builds(); File[] files = new File[jars.length]; for (int i = 0; i < jars.length; i++) { Jar jar = jars[i]; files[i] = saveBuild(jar); } getInfo(builder); builder.close(); if (isOk()) { this.files = files; // Write out the filenames in the buildfiles file // so we can get them later evenin another process FileWriter fw = new FileWriter(bfs); try { for (File f : files) { fw.append(f.getAbsolutePath()); fw.append("\n"); } } finally { fw.close(); } getWorkspace().changedFile(bfs); this.buildtime = buildtime; return files; } else return null; } public File saveBuild(Jar jar) throws Exception { try { String bsn = jar.getName(); File f = getOutputFile(bsn); String msg = ""; if (!f.exists() || f.lastModified() < jar.lastModified()) { reportNewer(f.lastModified(), jar); f.delete(); if (!f.getParentFile().isDirectory()) f.getParentFile().mkdirs(); jar.write(f); getWorkspace().changedFile(f); } else { msg = "(not modified since " + new Date(f.lastModified()) + ")"; } trace(jar.getName() + " (" + f.getName() + ") " + jar.getResources().size() + " " + msg); return f; } finally { jar.close(); } } public File getOutputFile(String bsn) throws Exception { return new File(getTarget(), bsn + ".jar"); } private void reportNewer(long lastModified, Jar jar) { if (isTrue(getProperty(Constants.REPORTNEWER))) { StringBuilder sb = new StringBuilder(); String del = "Newer than " + new Date(lastModified); for (Map.Entry entry : jar.getResources().entrySet()) { if (entry.getValue().lastModified() > lastModified) { sb.append(del); del = ", \n "; sb.append(entry.getKey()); } } if (sb.length() > 0) warning(sb.toString()); } } /** * Refresh if we are based on stale data. This also implies our workspace. */ public boolean refresh() { boolean changed = false; if (isCnf()) { changed = workspace.refresh(); } return super.refresh() || changed; } public boolean isCnf() { return getBase().getName().equals(Workspace.CNFDIR); } public void propertiesChanged() { super.propertiesChanged(); preparedPaths = false; files = null; } public String getName() { return getBase().getName(); } public Map getActions() { Map all = newMap(); Map actions = newMap(); fillActions(all); getWorkspace().fillActions(all); for (Map.Entry action : all.entrySet()) { String key = getReplacer().process(action.getKey()); if (key != null && key.trim().length() != 0) actions.put(key, action.getValue()); } return actions; } public void fillActions(Map all) { List plugins = getPlugins(NamedAction.class); for (NamedAction a : plugins) all.put(a.getName(), a); Map> actions = parseHeader(getProperty("-actions", DEFAULT_ACTIONS)); for (Map.Entry> entry : actions.entrySet()) { String key = Processor.removeDuplicateMarker(entry.getKey()); Action action; if (entry.getValue().get("script") != null) { // TODO check for the type action = new ScriptAction(entry.getValue().get("type"), entry.getValue().get( "script")); } else { action = new ReflectAction(key); } String label = entry.getValue().get("label"); all.put(label.toLowerCase(), action); } } public void release() throws Exception { release(false); } /** * Release. * * @param name * The repository name * @throws Exception */ public void release(String name) throws Exception { release(name, false); } public void clean() throws Exception { File target = getTarget(); if (target.isDirectory() && target.getParentFile() != null) { IO.delete(target); target.mkdirs(); } if (getOutput().isDirectory()) IO.delete(getOutput()); getOutput().mkdirs(); } public File[] build() throws Exception { return build(false); } public void run() throws Exception { ProjectLauncher pl = getProjectLauncher(); pl.setTrace(isTrace()); pl.launch(); } public void test() throws Exception { clear(); ProjectTester tester = getProjectTester(); tester.setContinuous(isTrue(getProperty(Constants.TESTCONTINUOUS))); tester.prepare(); if (!isOk()) { return; } int errors = tester.test(); if (errors == 0) { System.out.println("No Errors"); } else { if (errors > 0) { System.out.println(errors + " Error(s)"); } else System.out.println("Error " + errors); } } /** * This methods attempts to turn any jar into a valid jar. If this is a * bundle with manifest, a manifest is added based on defaults. If it is a * bundle, but not r4, we try to add the r4 headers. * * @param descriptor * @param in * @return * @throws Exception */ public Jar getValidJar(File f) throws Exception { Jar jar = new Jar(f); return getValidJar(jar, f.getAbsolutePath()); } public Jar getValidJar(URL url) throws Exception { InputStream in = url.openStream(); try { Jar jar = new Jar(url.getFile().replace('/', '.'), in, System.currentTimeMillis()); return getValidJar(jar, url.toString()); } finally { in.close(); } } public Jar getValidJar(Jar jar, String id) throws Exception { Manifest manifest = jar.getManifest(); if (manifest == null) { trace("Wrapping with all defaults"); Builder b = new Builder(this); b.addClasspath(jar); b.setProperty("Bnd-Message", "Wrapped from " + id + "because lacked manifest"); b.setProperty(Constants.EXPORT_PACKAGE, "*"); b.setProperty(Constants.IMPORT_PACKAGE, "*;resolution:=optional"); jar = b.build(); } else if (manifest.getMainAttributes().getValue(Constants.BUNDLE_MANIFESTVERSION) == null) { trace("Not a release 4 bundle, wrapping with manifest as source"); Builder b = new Builder(this); b.addClasspath(jar); b.setProperty(Constants.PRIVATE_PACKAGE, "*"); b.mergeManifest(manifest); String imprts = manifest.getMainAttributes().getValue(Constants.IMPORT_PACKAGE); if (imprts == null) imprts = ""; else imprts += ","; imprts += "*;resolution=optional"; b.setProperty(Constants.IMPORT_PACKAGE, imprts); b.setProperty("Bnd-Message", "Wrapped from " + id + "because had incomplete manifest"); jar = b.build(); } return jar; } public String _project(String args[]) { return getBase().getAbsolutePath(); } public void bump(String mask) throws IOException { Sed sed = new Sed(getReplacer(), getPropertiesFile()); sed.replace("(Bundle-Version\\s*(:|=)\\s*)(([0-9]+(\\.[0-9]+(\\.[0-9]+)?)?))", "$1${version;" + mask + ";$3}"); sed.doIt(); forceRefresh(); } public void bump() throws IOException { bump(getProperty(BUMPPOLICY, "=+0")); } public void action(String command) throws Throwable { Map actions = getActions(); Action a = actions.get(command); if (a == null) a = new ReflectAction(command); before(this, command); try { a.execute(this, command); } catch (Throwable t) { after(this, command, t); throw t; } } /** * Run all before command plugins * */ void before(Project p, String a) { List testPlugins = getPlugins(CommandPlugin.class); for (CommandPlugin testPlugin : testPlugins) { testPlugin.before(this, a); } } /** * Run all after command plugins */ void after(Project p, String a, Throwable t) { List testPlugins = getPlugins(CommandPlugin.class); for (int i = testPlugins.size() - 1; i >= 0; i--) { testPlugins.get(i).after(this, a, t); } } public String _findfile(String args[]) { File f = getFile(args[1]); List files = new ArrayList(); tree(files, f, "", Instruction.getPattern(args[2])); return join(files); } void tree(List list, File current, String path, Instruction instr) { if (path.length() > 0) path = path + "/"; String subs[] = current.list(); if (subs != null) { for (String sub : subs) { File f = new File(current, sub); if (f.isFile()) { if (instr.matches(sub) && !instr.isNegated()) list.add(path + sub); } else tree(list, f, path + sub, instr); } } } public void refreshAll() { workspace.refresh(); refresh(); } @SuppressWarnings("unchecked") public void script(String type, String script) throws Exception { // TODO check tyiping List scripters = getPlugins(Scripter.class); if (scripters.isEmpty()) { error("Can not execute script because there are no scripters registered: %s", script); return; } @SuppressWarnings("rawtypes") Map x = (Map) getProperties(); scripters.get(0).eval((Map) x, new StringReader(script)); } public String _repos(String args[]) throws Exception { List repos = getPlugins(RepositoryPlugin.class); List names = new ArrayList(); for (RepositoryPlugin rp : repos) names.add(rp.getName()); return join(names, ", "); } public String _help(String args[]) throws Exception { if (args.length == 1) return "Specify the option or header you want information for"; Syntax syntax = Syntax.HELP.get(args[1]); if (syntax == null) return "No help for " + args[1]; String what = null; if (args.length > 2) what = args[2]; if (what == null || what.equals("lead")) return syntax.getLead(); if (what == null || what.equals("example")) return syntax.getExample(); if (what == null || what.equals("pattern")) return syntax.getPattern(); if (what == null || what.equals("values")) return syntax.getValues(); return "Invalid type specified for help: lead, example, pattern, values"; } /** * Returns containers for the deliverables of this project. The deliverables * is the project builder for this project if no -sub is specified. * Otherwise it contains all the sub bnd files. * * @return A collection of containers * * @throws Exception */ public Collection getDeliverables() throws Exception { List result = new ArrayList(); Collection builders = getSubBuilders(); for (Builder builder : builders) { Container c = new Container(this, builder.getBsn(), builder.getVersion(), Container.TYPE.PROJECT, getOutputFile(builder.getBsn()), null, null); result.add(c); } return result; } /** * Return the builder associated with the give bnd file or null. The bnd.bnd * file can contain -sub option. This option allows specifying files in the * same directory that should drive the generation of multiple deliverables. * This method figures out if the bndFile is actually one of the bnd files * of a deliverable. * * @param bndFile * A file pointing to a bnd file. * @return null or the builder for a sub file. * @throws Exception */ public Builder getSubBuilder(File bndFile) throws Exception { bndFile = bndFile.getCanonicalFile(); // Verify that we are inside the project. File base = getBase().getCanonicalFile(); if (!bndFile.getAbsolutePath().startsWith(base.getAbsolutePath())) return null; Collection builders = getSubBuilders(); for (Builder sub : builders) { File propertiesFile = sub.getPropertiesFile(); if (propertiesFile != null) { if (propertiesFile.getCanonicalFile().equals(bndFile)) { // Found it! return sub; } } } return null; } /** * Answer the container associated with a given bsn. * * @param bndFile * A file pointing to a bnd file. * @return null or the builder for a sub file. * @throws Exception */ public Container getDeliverable(String bsn, Map attrs) throws Exception { Collection builders = getSubBuilders(); for (Builder sub : builders) { if (sub.getBsn().equals(bsn)) return new Container(this, getOutputFile(bsn)); } return null; } /** * Get a list of the sub builders. A bnd.bnd file can contain the -sub * option. This will generate multiple deliverables. This method returns the * builders for each sub file. If no -sub option is present, the list will * contain a builder for the bnd.bnd file. * * @return A list of builders. * @throws Exception */ public Collection getSubBuilders() throws Exception { return getBuilder(null).getSubBuilders(); } /** * Calculate the classpath. We include our own runtime.jar which includes * the test framework and we include the first of the test frameworks * specified. * * @throws Exception */ Collection toFile(Collection containers) throws Exception { ArrayList files = new ArrayList(); for (Container container : containers) { container.contributeFiles(files, this); } return files; } public Collection getRunVM() { Map> hdr = parseHeader(getProperty(RUNVM)); return hdr.keySet(); } public Map getRunProperties() { return OSGiHeader.parseProperties(getProperty(RUNPROPERTIES)); } /** * Get a launcher. * * @return * @throws Exception */ public ProjectLauncher getProjectLauncher() throws Exception { return getHandler(ProjectLauncher.class, getRunpath(), LAUNCHER_PLUGIN, "biz.aQute.launcher"); } public ProjectTester getProjectTester() throws Exception { return getHandler(ProjectTester.class, getTestpath(), TESTER_PLUGIN, "biz.aQute.junit"); } private T getHandler(Class target, Collection containers, String header, String defaultHandler) throws Exception { Class handlerClass = target; // Make sure we find at least one handler, but hope to find an earlier // one List withDefault = Create.list(); withDefault.addAll(containers); withDefault.addAll(getBundles(Strategy.HIGHEST, defaultHandler, null)); for (Container c : withDefault) { Manifest manifest = c.getManifest(); if (manifest != null) { String launcher = manifest.getMainAttributes().getValue(header); if (launcher != null) { Class clz = getClass(launcher, c.getFile()); if (clz != null) { if (!target.isAssignableFrom(clz)) { error("Found a %s class in %s but it is not compatible with: %s", clz, c, target); } else { handlerClass = clz.asSubclass(target); Constructor constructor = handlerClass .getConstructor(Project.class); return constructor.newInstance(this); } } } } } throw new IllegalArgumentException("Default handler for " + header + " not found in " + defaultHandler); } public synchronized boolean lock(String reason) throws InterruptedException { if (!lock.tryLock(5, TimeUnit.SECONDS)) { error("Could not acquire lock for %s, was locked by %s for %s", reason, lockingThread, lockingReason); System.out.printf("Could not acquire lock for %s, was locked by %s for %s\n", reason, lockingThread, lockingReason); System.out.flush(); return false; } this.lockingReason = reason; this.lockingThread = Thread.currentThread(); return true; } public void unlock() { lockingReason = null; lock.unlock(); } public long getBuildTime() throws Exception { if (buildtime == 0) { files = getBuildFiles(); if (files != null && files.length >= 1) buildtime = files[0].lastModified(); } return buildtime; } /** * Make this project delay the calculation of the run dependencies. * * The run dependencies calculation can be done in prepare or until the * dependencies are actually needed. */ public void setDelayRunDependencies(boolean x) { delayRunDependencies = x; } } bnd-1.50.0/biz.aQute.bndlib/src/aQute/bnd/build/ProjectTester.java0000644000175000017500000000304211656076535024514 0ustar drazzibdrazzibpackage aQute.bnd.build; import java.io.*; import java.util.*; public abstract class ProjectTester { final Project project; final Collection testbundles; final ProjectLauncher launcher; final List tests = new ArrayList(); File reportDir; boolean continuous = true; public ProjectTester(Project project) throws Exception { this.project = project; launcher = project.getProjectLauncher(); testbundles = project.getTestpath(); for (Container c : testbundles) { launcher.addClasspath(c); } reportDir = new File(project.getTarget(), project.getProperty("test-reports", "test-reports")); } public ProjectLauncher getProjectLauncher() { return launcher; } public void addTest(String test) { tests.add(test); } public Collection getTests() { return tests; } public Collection getReports() { List reports = new ArrayList(); for (File report : reportDir.listFiles()) { if (report.isFile() ) reports.add(report); } return reports; } public File getReportDir() { return reportDir; } public void setReportDir(File reportDir) { this.reportDir = reportDir; } public Project getProject() { return project; } public boolean getContinuous() { return continuous; } public void setContinuous(boolean b) { this.continuous = b; } public boolean prepare() throws Exception { reportDir.mkdirs(); for ( File file : reportDir.listFiles() ) { file.delete(); } return true; } public abstract int test() throws Exception; } bnd-1.50.0/biz.aQute.bndlib/src/aQute/bnd/build/packageinfo0000644000175000017500000000001711656076535023245 0ustar drazzibdrazzibversion 1.43.1 bnd-1.50.0/biz.aQute.bndlib/src/aQute/bnd/component/0000755000175000017500000000000011656076535021760 5ustar drazzibdrazzibbnd-1.50.0/biz.aQute.bndlib/src/aQute/bnd/component/AnnotationReader.java0000644000175000017500000002417511656076535026071 0ustar drazzibdrazzibpackage aQute.bnd.component; import java.lang.reflect.*; import java.util.*; import java.util.regex.*; import org.osgi.service.component.annotations.*; import aQute.lib.collections.*; import aQute.lib.osgi.*; import aQute.libg.version.*; public class AnnotationReader extends ClassDataCollector { final static String[] EMPTY = new String[0]; final static Pattern PROPERTY_PATTERN = Pattern .compile("([^=]+(:(Boolean|Byte|Char|Short|Integer|Long|Float|Double|String))?)\\s*=(.*)"); public static final Version V1_1 = new Version("1.1.0"); // "1.1.0" public static final Version V1_2 = new Version("1.2.0"); // "1.1.0" static Pattern BINDDESCRIPTOR = Pattern .compile("\\(((L([^;]+);)(Ljava/util/Map;)?|Lorg/osgi/framework/ServiceReference;)\\)V"); static Pattern BINDMETHOD = Pattern .compile("(set|bind|add)?(.*)"); static Pattern ACTIVATEDESCRIPTOR = Pattern .compile("\\(((Lorg/osgi/service/component/ComponentContext;)|(Lorg/osgi/framework/BundleContext;)|(Ljava/util/Map;))*\\)V"); static Pattern REFERENCEBINDDESCRIPTOR = Pattern .compile("\\(Lorg/osgi/framework/ServiceReference;\\)V"); ComponentDef component = new ComponentDef(); Clazz clazz; String interfaces[]; String methodDescriptor; String method; String className; int methodAccess; Analyzer analyzer; MultiMap methods = new MultiMap(); String extendsClass; AnnotationReader(Analyzer analyzer, Clazz clazz) { this.analyzer = analyzer; this.clazz = clazz; } public static ComponentDef getDefinition(Clazz c, Analyzer analyzer) throws Exception { AnnotationReader r = new AnnotationReader(analyzer, c); return r.getDef(c, analyzer); } /** * fixup any unbind methods To declare no unbind method, the value "-" must * be used. If not specified, the name of the unbind method is derived from * the name of the annotated bind method. If the annotated method name * begins with set, that is replaced with unset to derive the unbind method * name. If the annotated method name begins with add, that is replaced with * remove to derive the unbind method name. Otherwise, un is prefixed to the * annotated method name to derive the unbind method name. * * @return * @throws Exception */ private ComponentDef getDef(Clazz c, Analyzer analyzer) throws Exception { c.parseClassFileWithCollector(this); if (component.implementation == null) return null; while (extendsClass != null) { if (extendsClass.startsWith("java/")) break; Clazz ec = analyzer.findClass(extendsClass); if (ec == null) { analyzer.error("Missing super class for DS annotations: " + Clazz.pathToFqn(extendsClass) + " from " + c.getFQN()); } else { c.parseClassFileWithCollector(this); } } if (component.implementation != null) { for (ReferenceDef rdef : component.references.values()) { rdef.unbind = referredMethod(analyzer, rdef, rdef.unbind, "add(.*)", "remove$1", "(.*)", "un$1"); rdef.modified = referredMethod(analyzer, rdef, rdef.modified, "(add|set)(.*)", "modified$2", "(.*)", "modified$1"); } return component; } else return null; } /** * * @param analyzer * @param rdef */ protected String referredMethod(Analyzer analyzer, ReferenceDef rdef, String value, String... matches) { if (value == null) { String bind = rdef.bind; for (int i = 0; i < matches.length; i += 2) { Matcher m = Pattern.compile(matches[i]).matcher(bind); if (m.matches()) { value = m.replaceFirst(matches[i+1]); break; } } } else if (value.equals("-")) return null; if (methods.containsKey(value)) { for (String descriptor : methods.get(value)) { Matcher matcher = BINDDESCRIPTOR.matcher(descriptor); if (matcher.matches()) { String type = matcher.group(2); if (rdef.interfce.equals(Clazz.objectDescriptorToFQN(type)) || type.equals("Ljava/util/Map;") || type.equals("Lorg/osgi/framework/ServiceReference;")) { return value; } } } analyzer.error( "A related method to %s from the reference %s has no proper prototype for class %s. Expected void %s(%s s [,Map m] | ServiceReference r)", rdef.bind, value, component.implementation, value, rdef.interfce); } return null; } public void annotation(Annotation annotation) { try { java.lang.annotation.Annotation a = annotation.getAnnotation(); if (a instanceof Component) doComponent((Component) a, annotation); else if (a instanceof Activate) doActivate(); else if (a instanceof Deactivate) doDeactivate(); else if (a instanceof Modified) doModified(); else if (a instanceof Reference) doReference((Reference) a, annotation); } catch (Exception e) { e.printStackTrace(); analyzer.error("During generation of a component on class %s, exception %s", clazz, e); } } /** * */ protected void doDeactivate() { if (!ACTIVATEDESCRIPTOR.matcher(methodDescriptor).matches()) analyzer.error( "Deactivate method for %s does not have an acceptable prototype, only Map, ComponentContext, or BundleContext is allowed. Found: %s", clazz, methodDescriptor); else { component.deactivate = method; } } /** * */ protected void doModified() { if (!ACTIVATEDESCRIPTOR.matcher(methodDescriptor).matches()) analyzer.error( "Modified method for %s does not have an acceptable prototype, only Map, ComponentContext, or BundleContext is allowed. Found: %s", clazz, methodDescriptor); else { component.modified = method; } } /** * @param annotation * @throws Exception */ protected void doReference(Reference reference, Annotation raw) throws Exception { ReferenceDef def = new ReferenceDef(); def.name = reference.name(); if (def.name == null) { Matcher m = BINDMETHOD.matcher(method); if (m.matches()) { def.name = m.group(2); } else { def.name = method; } } def.unbind = reference.unbind(); def.bind = method; def.interfce = raw.get("service"); if (def.interfce != null) { def.interfce = Clazz.objectDescriptorToFQN(def.interfce); } else { // We have to find the type of the current method to // link it to the referenced service. Matcher m = BINDDESCRIPTOR.matcher(methodDescriptor); if (m.matches()) { def.interfce = Clazz.internalToFqn(m.group(3)); } else throw new IllegalArgumentException( "Cannot detect the type of a Component Reference from the descriptor: " + methodDescriptor); } // Check if we have a target, this must be a filter def.target = reference.target(); if (def.target != null) { Verifier.verifyFilter(def.target, 0); } if (component.references.containsKey(def.name)) analyzer.error( "In component %s, multiple references with the same name: %s. Previous def: %s, this def: %s", component.implementation, component.references.get(def.name), def.interfce, ""); else component.references.put(def.name, def); def.cardinality = reference.cardinality(); def.policy = reference.policy(); } /** * */ protected void doActivate() { if (!ACTIVATEDESCRIPTOR.matcher(methodDescriptor).matches()) analyzer.error( "Activate method for %s does not have an acceptable prototype, only Map, ComponentContext, or BundleContext is allowed. Found: %s", clazz, methodDescriptor); else { component.activate = method; } } /** * @param annotation * @throws Exception */ protected void doComponent(Component comp, Annotation annotation) throws Exception { // Check if we are doing a super class if (component.implementation != null) return; component.version = V1_1; component.implementation = clazz.getFQN(); component.name = comp.name(); component.factory = comp.factory(); component.configurationPolicy = comp.configurationPolicy(); if (annotation.get("enabled") != null) component.enabled = comp.enabled(); if (annotation.get("factory") != null) component.factory = comp.factory(); if (annotation.get("immediate") != null) component.immediate = comp.immediate(); if (annotation.get("servicefactory") != null) component.servicefactory = comp.servicefactory(); String properties[] = comp.properties(); if (properties != null) for (String entry : properties) component.properties.add(entry); doProperties(comp.property()); Object [] x = annotation.get("service"); if (x == null) { // Use the found interfaces, but convert from internal to // fqn. if (interfaces != null) { List result = new ArrayList(); for (int i = 0; i < interfaces.length; i++) { if (!interfaces[i].equals("scala/ScalaObject")) result.add(Clazz.internalToFqn(interfaces[i])); } component.service = result.toArray(EMPTY); } } else { // We have explicit interfaces set component.service= new String[x.length]; for (int i = 0; i < x.length; i++) { component.service[i] = Clazz.objectDescriptorToFQN(x[i].toString()); } } } /** * Parse the properties */ private void doProperties(String[] properties) { if (properties != null) { for (String p : properties) { Matcher m = PROPERTY_PATTERN.matcher(p); if (m.matches()) { String key = m.group(1); String value = m.group(4); component.property.add(key, value); } else throw new IllegalArgumentException("Malformed property '" + p + "' on component: " + className); } } } /** * Are called during class parsing */ @Override public void classBegin(int access, String name) { className = name; } @Override public void implementsInterfaces(String[] interfaces) { this.interfaces = interfaces; } @Override public void method(int access, String name, String descriptor) { if (Modifier.isPrivate(access) || Modifier.isAbstract(access) || Modifier.isStatic(access)) return; this.method = name; this.methodDescriptor = descriptor; this.methodAccess = access; methods.add(name, descriptor); } @Override public void extendsClass(String name) { this.extendsClass = name; } } bnd-1.50.0/biz.aQute.bndlib/src/aQute/bnd/component/DSAnnotations.java0000644000175000017500000000315711656076535025355 0ustar drazzibdrazzibpackage aQute.bnd.component; import java.util.*; import aQute.bnd.service.*; import aQute.lib.osgi.*; import aQute.libg.header.*; /** * Analyze the class space for any classes that have an OSGi annotation for DS. * */ public class DSAnnotations implements AnalyzerPlugin { public boolean analyzeJar(Analyzer analyzer) throws Exception { Map> header = OSGiHeader.parseHeader(analyzer .getProperty("-dsannotations")); if ( header.size()==0) return false; Set instructions = Instruction.replaceWithInstruction(header).keySet(); Set list = new HashSet(analyzer.getClassspace().values()); String sc = analyzer.getProperty(Constants.SERVICE_COMPONENT); List names = new ArrayList(); if ( sc != null && sc.trim().length() > 0) names.add(sc); for (Iterator i = list.iterator(); i.hasNext();) { for (Instruction instruction : instructions) { Clazz c = i.next(); System.out.println("fqn " + c.getFQN() + " " + instruction); if (instruction.matches(c.getFQN())) { if (instruction.isNegated()) i.remove(); else { ComponentDef definition = AnnotationReader.getDefinition(c, analyzer); if (definition != null) { definition.prepare(analyzer); String name = "OSGI-INF/" + definition.name + ".xml"; names.add(name); analyzer.getJar().putResource(name, new TagResource(definition.getTag())); } } } } } sc = Processor.append(names.toArray(new String[names.size()])); analyzer.setProperty(Constants.SERVICE_COMPONENT, sc); return false; } } bnd-1.50.0/biz.aQute.bndlib/src/aQute/bnd/component/ComponentDef.java0000644000175000017500000000711411656076535025207 0ustar drazzibdrazzibpackage aQute.bnd.component; import java.util.*; import org.osgi.service.component.annotations.*; import aQute.lib.collections.*; import aQute.lib.osgi.*; import aQute.lib.tag.*; import aQute.libg.version.*; class ComponentDef { final static String NAMESPACE_STEM = "http://www.osgi.org/xmlns/scr"; Version version = new Version("1.1.0"); String name; String factory; Boolean immediate; Boolean servicefactory; ConfigurationPolicy configurationPolicy; String implementation; String service[]; String activate; String deactivate; String modified; Boolean enabled; final List properties = new ArrayList(); final MultiMap property = new MultiMap(); final Map references = new TreeMap(); void prepare(Analyzer analyzer) { for (ReferenceDef ref : references.values()) { ref.prepare(analyzer); if (ref.version.compareTo(version) > 0) version = ref.version; } if (implementation == null) analyzer.error("No Implementation defined for component " + name); else analyzer.referTo(implementation); name = implementation; if (service != null && service.length > 0) { for (String interfaceName : service) analyzer.referTo(interfaceName); } else if (servicefactory != null && servicefactory) analyzer.warning("The servicefactory:=true directive is set but no service is provided, ignoring it"); } Tag getTag() { Tag component = new Tag("scr:component"); component.addAttribute("xmlns:scr", NAMESPACE_STEM + "/" + version); component.addAttribute("name", name); if (servicefactory != null) component.addAttribute("servicefactory", servicefactory); if (configurationPolicy != null) component.addAttribute("configuration-policy", configurationPolicy.toString() .toLowerCase()); if (enabled != null) component.addAttribute("enabled", enabled); if (immediate != null) component.addAttribute("immediate", immediate); if (factory != null) component.addAttribute("factory", factory); if (activate != null) component.addAttribute("activate", activate); if (deactivate != null) component.addAttribute("deactivate", deactivate); if (modified != null) component.addAttribute("modified", modified); Tag impl = new Tag(component, "implementation"); impl.addAttribute("class", implementation); if (service != null && service.length != 0) { Tag s = new Tag(component, "service"); if (servicefactory != null && servicefactory) s.addAttribute("servicefactory", true); for (String ss : service) { Tag provide = new Tag(s, "provide"); provide.addAttribute("interface", ss); } } for (ReferenceDef ref : references.values()) { Tag refTag = ref.getTag(); component.addContent(refTag); } for (Map.Entry> kvs : property.entrySet()) { Tag property = new Tag(component, "property"); String name = kvs.getKey(); String type = null; int n = name.indexOf(':'); if (n > 0) { type = name.substring(n + 1); name = name.substring(0, n); } property.addAttribute("name", name); if (type != null) { property.addAttribute("type", type); } StringBuffer sb = new StringBuffer(); String del = ""; for (String v : kvs.getValue()) { sb.append(del); sb.append(v); del = "\n"; } property.addContent(sb.toString()); } for (String entry : properties) { Tag properties = new Tag(component, "properties"); properties.addAttribute("entry", entry); } return component; } }bnd-1.50.0/biz.aQute.bndlib/src/aQute/bnd/component/ReferenceDef.java0000644000175000017500000000336711656076535025151 0ustar drazzibdrazzibpackage aQute.bnd.component; import org.osgi.service.component.annotations.*; import aQute.lib.osgi.*; import aQute.lib.tag.*; import aQute.libg.version.*; class ReferenceDef { Version version; String name; String interfce; ReferenceCardinality cardinality; ReferencePolicy policy; String target; String bind; String unbind; String modified; public void prepare(Analyzer analyzer) { if (name == null) analyzer.error("No name for a reference"); if (version == null) version = AnnotationReader.V1_1; } public Tag getTag() { Tag ref = new Tag("reference"); ref.addAttribute("name", name); if (cardinality != null) ref.addAttribute("cardinality", p(cardinality)); if (policy != null) ref.addAttribute("policy", p(policy)); if (interfce != null) ref.addAttribute("interface", interfce); if (target != null) ref.addAttribute("target", target); if (bind != null) ref.addAttribute("bind", bind); if (unbind != null) ref.addAttribute("unbind", unbind); if (modified != null) { ref.addAttribute("modified", modified); version = max(version, AnnotationReader.V1_2); } return ref; } private String p(ReferencePolicy policy) { switch(policy) { case DYNAMIC: return "dynamic"; case STATIC: return "static"; } return policy.toString(); } private String p(ReferenceCardinality crd) { switch (crd) { case AT_LEAST_ONE: return "1..n"; case MANDATORY: return "1..1"; case MULTIPLE: return "0..n"; case OPTIONAL: return "0..1"; } return crd.toString(); } private > T max(T a, T b) { int n = a.compareTo(b); if (n >= 0) return a; else return b; } public String toString() { return name; } } bnd-1.50.0/biz.aQute.bndlib/src/aQute/bnd/service/0000755000175000017500000000000011656076535021416 5ustar drazzibdrazzibbnd-1.50.0/biz.aQute.bndlib/src/aQute/bnd/service/RepositoryPlugin.java0000644000175000017500000000434211656076535025622 0ustar drazzibdrazzibpackage aQute.bnd.service; import java.io.*; import java.util.*; import aQute.lib.osgi.*; import aQute.libg.version.*; public interface RepositoryPlugin { public enum Strategy { LOWEST, HIGHEST, EXACT } /** * Return a URL to a matching version of the given bundle. * * @param bsn * Bundle-SymbolicName of the searched bundle * @param range * Version range for this bundle,"latest" if you only want the * latest, or null when you want all. * @return A list of URLs sorted on version, lowest version is at index 0. * null is returned when no files with the given bsn ould be found. * @throws Exception * when anything goes wrong */ @Deprecated File[] get(String bsn, String range) throws Exception; /** * Return a URL to a matching version of the given bundle. * * @param bsn * Bundle-SymbolicName of the searched bundle * @param range * Version range for this bundle,"latest" if you only want the * latest, or null when you want all. * @param strategy * Get the highest or the lowest * @return A list of URLs sorted on version, lowest version is at index 0. * null is returned when no files with the given bsn ould be found. * @throws Exception * when anything goes wrong */ File get(String bsn, String range, Strategy strategy, Map properties) throws Exception; /** * Answer if this repository can be used to store files. * * @return true if writable */ boolean canWrite(); /** * Put a JAR file in the repository. * * @param jar * @throws Exception */ File put(Jar jar) throws Exception; /** * Return a list of bsns that are present in the repository. * * @param regex * if not null, match against the bsn and if matches, return * otherwise skip * @return A list of bsns that match the regex parameter or all if regex is * null * @throws Exception */ List list(String regex) throws Exception; /** * Return a list of versions. * * @throws Exception */ List versions(String bsn) throws Exception; /** * @return The name of the repository */ String getName(); } bnd-1.50.0/biz.aQute.bndlib/src/aQute/bnd/service/OBRIndexProvider.java0000644000175000017500000000041111656076535025402 0ustar drazzibdrazzibpackage aQute.bnd.service; import java.io.IOException; import java.net.URL; import java.util.Collection; import java.util.Set; public interface OBRIndexProvider { Collection getOBRIndexes() throws IOException; Set getSupportedModes(); } bnd-1.50.0/biz.aQute.bndlib/src/aQute/bnd/service/OBRResolutionMode.java0000644000175000017500000000011611656076535025572 0ustar drazzibdrazzibpackage aQute.bnd.service; public enum OBRResolutionMode { build, runtime } bnd-1.50.0/biz.aQute.bndlib/src/aQute/bnd/service/Scripter.java0000644000175000017500000000024111656076535024051 0ustar drazzibdrazzibpackage aQute.bnd.service; import java.io.*; import java.util.*; public interface Scripter { void eval(Map x, StringReader stringReader); } bnd-1.50.0/biz.aQute.bndlib/src/aQute/bnd/service/MakePlugin.java0000644000175000017500000000121511656076535024314 0ustar drazzibdrazzibpackage aQute.bnd.service; import java.util.*; import aQute.lib.osgi.*; public interface MakePlugin { /** * This plugin is called when Include-Resource detects a reference to a resource * that it can not find in the file system. * * @param builder The current builder * @param source The source string (i.e. the place where bnd looked) * @param arguments Any arguments on the clause in Include-Resource * @return A resource or null if no resource could be made * @throws Exception */ Resource make(Builder builder, String source, Map arguments) throws Exception; } bnd-1.50.0/biz.aQute.bndlib/src/aQute/bnd/service/RemoteRepositoryPlugin.java0000644000175000017500000000122411656076535026772 0ustar drazzibdrazzibpackage aQute.bnd.service; import java.io.File; import java.util.Map; public interface RemoteRepositoryPlugin extends RepositoryPlugin { /** * Retrieve a resource handle from the repository. For all implementations of this interface, calling {@code getFile(bsn, range, strategy, props)} * should always return the same result as {@code getResource(bsn, range, strategy, props).request()}. * @param bsn * @param range * @param strategy * @param properties * @return * @throws Exception */ ResourceHandle getHandle(String bsn, String range, Strategy strategy, Map properties) throws Exception; File getCacheDirectory(); } bnd-1.50.0/biz.aQute.bndlib/src/aQute/bnd/service/Plugin.java0000644000175000017500000000157411656076535023526 0ustar drazzibdrazzibpackage aQute.bnd.service; import java.util.*; import aQute.libg.reporter.*; /** * An optional interface for plugins. If a plugin implements this interface then * it can receive the reminaing attributes and directives given in its clause as * well as the reporter to use. * */ public interface Plugin { /** * Give the plugin the remaining properties. * * When a plugin is declared, the clause can contain extra properties. * All the properties and directives are given to the plugin to use. * * @param map attributes and directives for this plugin's clause */ void setProperties(Map map); /** * Set the current reporter. This is called at init time. This plugin * should report all errors and warnings to this reporter. * * @param processor */ void setReporter(Reporter processor); } bnd-1.50.0/biz.aQute.bndlib/src/aQute/bnd/service/SignerPlugin.java0000644000175000017500000000066411656076535024675 0ustar drazzibdrazzibpackage aQute.bnd.service; import aQute.lib.osgi.*; public interface SignerPlugin { /** * Sign the current jar. The alias is the given certificate * keystore. * * @param builder The current builder that contains the jar to sign * @param alias The keystore certificate alias * @throws Exception When anything goes wrong */ void sign(Builder builder, String alias) throws Exception; } bnd-1.50.0/biz.aQute.bndlib/src/aQute/bnd/service/AnalyzerPlugin.java0000644000175000017500000000112011656076535025217 0ustar drazzibdrazzibpackage aQute.bnd.service; import aQute.lib.osgi.*; public interface AnalyzerPlugin { /** * This plugin is called after analysis. The plugin is free to modify the * jar and/or change the classpath information (see referred, contained). * This plugin is called after analysis of the JAR but before manifest * generation. * * @param analyzer * @return true if the classpace has been modified so that the bundle * classpath must be reanalyzed * @throws Exception */ boolean analyzeJar(Analyzer analyzer) throws Exception; } bnd-1.50.0/biz.aQute.bndlib/src/aQute/bnd/service/EclipseJUnitTester.java0000644000175000017500000000017211656076535026006 0ustar drazzibdrazzibpackage aQute.bnd.service; public interface EclipseJUnitTester { void setPort(int port); void setHost( String host); } bnd-1.50.0/biz.aQute.bndlib/src/aQute/bnd/service/Registry.java0000755000175000017500000000026511656076535024077 0ustar drazzibdrazzibpackage aQute.bnd.service; import java.util.*; /** * A registry for objects. */ public interface Registry { List getPlugins(Class c); T getPlugin(Class c); } bnd-1.50.0/biz.aQute.bndlib/src/aQute/bnd/service/DependencyContributor.java0000644000175000017500000000027411656076535026575 0ustar drazzibdrazzibpackage aQute.bnd.service; import java.util.*; import aQute.bnd.build.*; public interface DependencyContributor { void addDependencies(Project project, Set dependencies); } bnd-1.50.0/biz.aQute.bndlib/src/aQute/bnd/service/LauncherPlugin.java0000644000175000017500000000030711656076535025201 0ustar drazzibdrazzibpackage aQute.bnd.service; import aQute.bnd.build.*; public interface LauncherPlugin { ProjectLauncher getLauncher(Project project) throws Exception; ProjectTester getTester(Project project); } bnd-1.50.0/biz.aQute.bndlib/src/aQute/bnd/service/Compiler.java0000644000175000017500000000037011656076535024033 0ustar drazzibdrazzibpackage aQute.bnd.service; import java.io.*; import java.util.*; import aQute.bnd.build.*; public interface Compiler { boolean compile(Project project, Collection sources, Collection buildpath, File bin) throws Exception; } bnd-1.50.0/biz.aQute.bndlib/src/aQute/bnd/service/Refreshable.java0000644000175000017500000000017311656076535024504 0ustar drazzibdrazzibpackage aQute.bnd.service; import java.io.*; public interface Refreshable { boolean refresh(); File getRoot(); } bnd-1.50.0/biz.aQute.bndlib/src/aQute/bnd/service/BndListener.java0000644000175000017500000000073711656076535024501 0ustar drazzibdrazzibpackage aQute.bnd.service; import java.io.*; import java.util.concurrent.atomic.*; import aQute.libg.reporter.*; public class BndListener { final AtomicInteger inside = new AtomicInteger(); public void changed(File file) { } public void begin() { inside.incrementAndGet();} public void end() { inside.decrementAndGet(); } public boolean isInside() { return inside.get()!=0; } public void signal(Reporter reporter) { } } bnd-1.50.0/biz.aQute.bndlib/src/aQute/bnd/service/action/0000755000175000017500000000000011656076535022673 5ustar drazzibdrazzibbnd-1.50.0/biz.aQute.bndlib/src/aQute/bnd/service/action/Action.java0000644000175000017500000000023611656076535024754 0ustar drazzibdrazzibpackage aQute.bnd.service.action; import aQute.bnd.build.*; public interface Action { void execute( Project project, String action) throws Exception; } bnd-1.50.0/biz.aQute.bndlib/src/aQute/bnd/service/action/NamedAction.java0000644000175000017500000000015211656076535025716 0ustar drazzibdrazzibpackage aQute.bnd.service.action; public interface NamedAction extends Action { String getName(); } bnd-1.50.0/biz.aQute.bndlib/src/aQute/bnd/service/action/packageinfo0000644000175000017500000000001711656076535025063 0ustar drazzibdrazzibversion 1.43.1 bnd-1.50.0/biz.aQute.bndlib/src/aQute/bnd/service/ResourceHandle.java0000644000175000017500000000037611656076535025172 0ustar drazzibdrazzibpackage aQute.bnd.service; import java.io.File; import java.io.IOException; public interface ResourceHandle { public enum Location { local, remote_cached, remote }; String getName(); Location getLocation(); File request() throws IOException; } bnd-1.50.0/biz.aQute.bndlib/src/aQute/bnd/service/Deploy.java0000644000175000017500000000032711656076535023517 0ustar drazzibdrazzibpackage aQute.bnd.service; import aQute.bnd.build.*; import aQute.lib.osgi.*; /** * Deploy this artifact to maven. * */ public interface Deploy { boolean deploy(Project project, Jar jar) throws Exception; } bnd-1.50.0/biz.aQute.bndlib/src/aQute/bnd/service/CommandPlugin.java0000644000175000017500000000137011656076535025017 0ustar drazzibdrazzibpackage aQute.bnd.service; import aQute.bnd.build.*; /** * A plugin that makes it possible to * @author aqute * */ public interface CommandPlugin { /** * Is run before a command is executed. These plugins are called * in the order of declaration. * * @param project The project for which the command runs * * @param command the command name */ void before(Project project, String command); /** * Is run after a command is executed. These plugins are * called in the reverse order of declaration. * * @param project The project for which the command runs * * @param command the command name */ void after(Project project, String command, Throwable outcome); } bnd-1.50.0/biz.aQute.bndlib/src/aQute/bnd/service/packageinfo0000644000175000017500000000001711656076535023606 0ustar drazzibdrazzibversion 1.44.0 bnd-1.50.0/biz.aQute.bndlib/src/aQute/bnd/service/url/0000755000175000017500000000000011656076535022220 5ustar drazzibdrazzibbnd-1.50.0/biz.aQute.bndlib/src/aQute/bnd/service/url/URLConnector.java0000644000175000017500000000030211656076535025373 0ustar drazzibdrazzibpackage aQute.bnd.service.url; import java.io.IOException; import java.io.InputStream; import java.net.URL; public interface URLConnector { InputStream connect(URL url) throws IOException; } bnd-1.50.0/biz.aQute.bndlib/src/aQute/bnd/service/RegistryPlugin.java0000644000175000017500000000022111656076535025243 0ustar drazzibdrazzibpackage aQute.bnd.service; /** * A plugin that wants a registry */ public interface RegistryPlugin { void setRegistry(Registry registry); } bnd-1.50.0/biz.aQute.bndlib/src/aQute/bnd/service/RepositoryListenerPlugin.java0000644000175000017500000000046411656076535027331 0ustar drazzibdrazzibpackage aQute.bnd.service; import java.io.File; import aQute.lib.osgi.Jar; public interface RepositoryListenerPlugin { /** * Called when a bundle is added to a repository. * @param repository * @param jar * @param file */ void bundleAdded(RepositoryPlugin repository, Jar jar, File file); } bnd-1.50.0/biz.aQute.bndlib/src/aQute/bnd/compatibility/0000755000175000017500000000000011656076535022627 5ustar drazzibdrazzibbnd-1.50.0/biz.aQute.bndlib/src/aQute/bnd/compatibility/ParseSignatureBuilder.java0000644000175000017500000000516111656076535027740 0ustar drazzibdrazzibpackage aQute.bnd.compatibility; import java.io.*; import aQute.lib.osgi.*; public class ParseSignatureBuilder { final Scope root; public ParseSignatureBuilder(Scope root) { this.root = root; } public void add( Jar jar ) throws Exception { for ( Resource r : jar.getResources().values()) { InputStream in = r.openInputStream(); try { parse(in); } finally { in.close(); } } } public Scope getRoot() { return root; } public void parse(InputStream in) throws IOException { Clazz clazz = new Clazz("", null); clazz.parseClassFile(in, new ClassDataCollector() { Scope s; Scope enclosing; Scope declaring; public void classBegin(int access, String name) { s = root.getScope(Scope.classIdentity(name)); s.access = Access.modifier(access); s.kind = Kind.CLASS; } public void extendsClass(String name) { // s.setBase(new GenericType(name)); } public void implementsInterfaces(String names[]) { s.setParameterTypes(convert(names)); } GenericType[] convert(String names[]) { GenericType tss[] = new GenericType[names.length]; for (int i = 0; i < names.length; i++) { // tss[i] = new GenericType(names[i]); } return tss; } public void method(Clazz.MethodDef defined) { String descriptor; Kind kind; if (defined.isConstructor()) { descriptor = ":" + defined.descriptor; kind = Kind.CONSTRUCTOR; } else { descriptor = defined.name + ":" + defined.descriptor; kind = Kind.METHOD; } Scope m = s.getScope(descriptor); m.access = Access.modifier(defined.access); m.kind = kind; m.declaring = s; s.add(m); } public void field(Clazz.FieldDef defined) { String descriptor = defined.name + ":" + defined.descriptor; Kind kind = Kind.FIELD; Scope m = s.getScope(descriptor); m.access = Access.modifier(defined.access); m.kind = kind; m.declaring = s; s.add(m); } public void classEnd() { if (enclosing != null) s.setEnclosing( enclosing ); if (declaring != null) s.setDeclaring( declaring ); } public void enclosingMethod(String cName, String mName, String mDescriptor) { enclosing = root.getScope(Scope.classIdentity(cName)); if (mName != null) { enclosing = enclosing.getScope(Scope.methodIdentity(mName, mDescriptor)); } } public void innerClass(String innerClass, String outerClass, String innerName, int innerClassAccessFlags) { if (outerClass != null && innerClass != null && innerClass.equals(s.name)) declaring = root.getScope(Scope.classIdentity(outerClass)); } }); } } bnd-1.50.0/biz.aQute.bndlib/src/aQute/bnd/compatibility/GenericType.java0000644000175000017500000000124011656076535025705 0ustar drazzibdrazzibpackage aQute.bnd.compatibility; public class GenericType { public GenericType(Class class1) { // TODO Auto-generated constructor stub } final static GenericType EMPTY[] = new GenericType[0]; Scope reference; GenericType[] a; GenericType[] b; int array; Scope scope; static public class GenericWildcard extends GenericType{ public GenericWildcard(Class class1) { super(class1); // TODO Auto-generated constructor stub } } static public class GenericArray extends GenericType { public GenericArray(Class class1) { super(class1); // TODO Auto-generated constructor stub } } } bnd-1.50.0/biz.aQute.bndlib/src/aQute/bnd/compatibility/Signatures.java0000644000175000017500000003457511656076535025634 0ustar drazzibdrazzib/* * Copyright (c) OSGi Alliance (2009, 2010). All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package aQute.bnd.compatibility; import java.lang.reflect.*; import java.util.*; /** * This class is compiled against 1.5 or later to provide access to the generic * signatures. It can convert a Class, Field, Method or constructor to a generic * signature and it can normalize a signature. Both are methods. Normalized * signatures can be string compared and match even if the type variable names * differ. * * @version $Id: ec4a5450ad339ea13acb8e684c6db9c154a33662 $ */ public class Signatures { /** * Check if the environment has generics, i.e. later than * Java 5 VM. * * @return true if generics are supported * @throws Exception */ public boolean hasGenerics() throws Exception { try { call( Signatures.class, "getGenericSuperClass"); return true; } catch( NoSuchMethodException mnfe ) { return false; } } /** * Helper class to track an index in a string. */ class Rover { final String s; int i; public Rover(String s) { this.s = s; i = 0; } char peek() { return s.charAt(i); } char take() { return s.charAt(i++); } char take(char c) { char x = s.charAt(i++); if (c != x) throw new IllegalStateException("get() expected " + c + " but got + " + x); return x; } public String upTo(String except) { int start = i; while (except.indexOf(peek()) < 0) take(); return s.substring(start, i); } public boolean isEOF() { return i >= s.length(); } } /** * Calculate the generic signature of a Class,Method,Field, or Constructor. * @param f * @return * @throws Exception */ public String getSignature(Object c) throws Exception { if( c instanceof Class) return getSignature((Class)c); if( c instanceof Constructor) return getSignature((Constructor)c); if( c instanceof Method) return getSignature((Method)c); if( c instanceof Field) return getSignature((Field)c); throw new IllegalArgumentException(c.toString()); } /** * Calculate the generic signature of a Class. A Class consists of: * *
	 * 	  class        ::= declaration? reference reference*
	 * 
* * * @param f * @return * @throws Exception */ public String getSignature(Class< ? > c) throws Exception { StringBuffer sb = new StringBuffer(); declaration(sb, c); reference(sb, call(c, "getGenericSuperclass")); for (Object type : (Object[]) call(c,"getGenericInterfaces")) { reference(sb, type); } return sb.toString(); } /** * Calculate the generic signature of a Method. A Method consists of: * *
	 *    method ::= declaration? '(' reference* ')' reference
	 * 
* * @param c * @return * @throws Exception */ public String getSignature(Method m) throws Exception { StringBuffer sb = new StringBuffer(); declaration(sb, m); sb.append('('); for (Object type : (Object[]) call(m,"getGenericParameterTypes")) { reference(sb, type); } sb.append(')'); reference(sb, call(m,"getGenericReturnType")); return sb.toString(); } /** * Calculate the generic signature of a Constructor. A Constructor consists * of: * *
	 *    constructor ::= declaration? '(' reference* ')V'
	 * 
* * @param c * @return * @throws Exception */ public String getSignature(Constructor< ? > c) throws Exception { StringBuffer sb = new StringBuffer(); declaration(sb, c); sb.append('('); for (Object type : (Object[]) call(c,"getGenericParameterTypes")) { reference(sb, type); } sb.append(')'); reference(sb, void.class); return sb.toString(); } /** * Calculate the generic signature of a Field. A Field consists of: * *
	 *    constructor ::= reference
	 * 
* * @param c * @return * @throws Exception */ public String getSignature(Field f) throws Exception { StringBuffer sb = new StringBuffer(); Object t = call(f,"getGenericType"); reference(sb, t); return sb.toString(); } /** * Classes, Methods, or Constructors can have a declaration that provides * nested a scope for type variables. A Method/Constructor inherits * the type variables from its class and a class inherits its type variables * from its outer class. The declaration consists of the following * syntax: *
	 *    declarations ::= '<' declaration ( ',' declaration )* '>'
	 *    declaration  ::= identifier ':' declare
	 *    declare      ::= types | variable 
	 *    types        ::= ( 'L' class ';' )? ( ':' 'L' interface ';' )*
	 *    variable     ::= 'T' id ';'
	 * 
* * @param sb * @param gd * @throws Exception */ private void declaration(StringBuffer sb, Object gd) throws Exception { Object[] typeParameters = (Object[]) call(gd,"getTypeParameters"); if (typeParameters.length > 0) { sb.append('<'); for (Object tv : typeParameters) { sb.append( call(tv,"getName")); Object[] bounds = (Object[]) call(tv,"getBounds"); if (bounds.length > 0 && isInterface(bounds[0])) { sb.append(':'); } for (int i = 0; i < bounds.length; i++) { sb.append(':'); reference(sb, bounds[i]); } } sb.append('>'); } } /** * Verify that the type is an interface. * * @param type the type to check. * @return true if this is a class that is an interface or a Parameterized * Type that is an interface * @throws Exception */ private boolean isInterface(Object type) throws Exception { if (type instanceof Class) return (((Class< ? >) type).isInterface()); if ( isInstance(type.getClass(), "java.lang.reflect.ParameterizedType")) return isInterface(call(type,"getRawType")); return false; } /** * This is the heart of the signature builder. A reference is used * in a lot of places. It referes to another type. *
	 *   reference     ::= array | class | primitive | variable
	 *   array         ::= '[' reference
	 *   class         ::=  'L' body ( '.' body )* ';'
	 *   body          ::=  id ( '<' ( wildcard | reference )* '>' )?
	 *   variable      ::=  'T' id ';'
	 *   primitive     ::= PRIMITIVE
	 * 
* * @param sb * @param t * @throws Exception */ private void reference(StringBuffer sb, Object t) throws Exception { if ( isInstance(t.getClass(),"java.lang.reflect.ParameterizedType")) { sb.append('L'); parameterizedType(sb, t); sb.append(';'); return; } else if ( isInstance(t.getClass(), "java.lang.reflect.GenericArrayType")) { sb.append('['); reference(sb, call(t,"getGenericComponentType")); } else if ( isInstance(t.getClass(), "java.lang.reflect.WildcardType")) { Object[] lowerBounds = (Object[]) call(t, "getLowerBounds"); Object[] upperBounds = (Object[]) call(t, "getUpperBounds"); if (upperBounds.length == 1 && upperBounds[0] == Object.class) upperBounds = new Object[0]; if (upperBounds.length != 0) { // extend for (Object upper : upperBounds) { sb.append('+'); reference(sb, upper); } } else if (lowerBounds.length != 0) { // super, can only be one by the language for (Object lower : lowerBounds) { sb.append('-'); reference(sb, lower); } } else sb.append('*'); } else if ( isInstance(t.getClass(),"java.lang.reflect.TypeVariable")) { sb.append('T'); sb.append( call(t,"getName")); sb.append(';'); } else if (t instanceof Class< ? >) { Class< ? > c = (Class< ? >) t; if (c.isPrimitive()) { sb.append(primitive(c)); } else { sb.append('L'); String name = c.getName().replace('.', '/'); sb.append(name); sb.append(';'); } } } /** * Creates the signature for a Parameterized Type. * * A Parameterized Type has a raw class and a set of type variables. * * @param sb * @param pt * @throws Exception */ private void parameterizedType(StringBuffer sb, Object pt) throws Exception { Object owner = call(pt,"getOwnerType"); String name = ((Class< ? >) call(pt,"getRawType")).getName() .replace('.', '/'); if (owner != null) { if ( isInstance(owner.getClass(), "java.lang.reflect.ParameterizedType")) parameterizedType(sb, owner); else sb.append(((Class< ? >) owner).getName().replace('.', '/')); sb.append('.'); int n = name.lastIndexOf('$'); name = name.substring(n + 1); } sb.append(name); sb.append('<'); for (Object parameterType : (Object[]) call(pt,"getActualTypeArguments")) { reference(sb, parameterType); } sb.append('>'); } /** * Handle primitives, these need to be translated to a single char. * * @param type the primitive class * @return the single char associated with the primitive */ private char primitive(Class< ? > type) { if (type == byte.class) return 'B'; else if (type == char.class) return 'C'; else if (type == double.class) return 'D'; else if (type == float.class) return 'F'; else if (type == int.class) return 'I'; else if (type == long.class) return 'J'; else if (type == short.class) return 'S'; else if (type == boolean.class) return 'Z'; else if (type == void.class) return 'V'; else throw new IllegalArgumentException( "Unknown primitive type " + type); } /** * Normalize a signature to make sure the name of the variables are always * the same. We change the names of the type variables to _n, where n is an * integer. n is incremented for every new name and already used names are * replaced with the _n name. * * @return a normalized signature */ public String normalize(String signature) { StringBuffer sb = new StringBuffer(); Map map = new HashMap(); Rover rover = new Rover(signature); declare(sb, map, rover); if (rover.peek() == '(') { // method or constructor sb.append(rover.take('(')); while (rover.peek() != ')') { reference(sb, map, rover, true); } sb.append(rover.take(')')); reference(sb, map, rover, true); // return type } else { // field or class reference(sb, map, rover, true); // field type or super class while (!rover.isEOF()) { reference(sb, map, rover, true); // interfaces } } return sb.toString(); } /** * The heart of the routine. Handle a reference to a type. Can be * an array, a class, a type variable, or a primitive. * * @param sb * @param map * @param rover * @param primitivesAllowed */ private void reference(StringBuffer sb, Map map, Rover rover, boolean primitivesAllowed) { char type = rover.take(); sb.append(type); if (type == '[') { reference(sb, map, rover, true); } else if (type == 'L') { String fqnb = rover.upTo("<;."); sb.append(fqnb); body(sb, map, rover); while (rover.peek() == '.') { sb.append(rover.take('.')); sb.append(rover.upTo("<;.")); body(sb, map, rover); } sb.append(rover.take(';')); } else if (type == 'T') { String name = rover.upTo(";"); name = assign(map, name); sb.append(name); sb.append(rover.take(';')); } else { if (!primitivesAllowed) throw new IllegalStateException( "Primitives are not allowed without an array"); } } /** * Because classes can be nested the body handles the part that can * be nested, the reference handles the enclosing L ... ; * * @param sb * @param map * @param rover */ private void body(StringBuffer sb, Map map, Rover rover) { if (rover.peek() == '<') { sb.append(rover.take('<')); while (rover.peek() != '>') { switch (rover.peek()) { case 'L' : case '[' : reference(sb, map, rover, false); break; case 'T' : String name; sb.append(rover.take('T')); // 'T' name = rover.upTo(";"); sb.append(assign(map, name)); sb.append(rover.take(';')); break; case '+' : // extends case '-' : // super sb.append(rover.take()); reference(sb, map, rover, false); break; case '*' : // wildcard sb.append(rover.take()); break; } } sb.append(rover.take('>')); } } /** * Handle the declaration part. * * @param sb * @param map * @param rover */ private void declare(StringBuffer sb, Map map, Rover rover) { char c = rover.peek(); if (c == '<') { sb.append(rover.take('<')); while (rover.peek() != '>') { String name = rover.upTo(":"); name = assign(map, name); sb.append(name); typeVar: while (rover.peek() == ':') { sb.append(rover.take(':')); switch (rover.peek()) { case ':' : // empty class cases continue typeVar; default : reference(sb, map, rover, false); break; } } } sb.append(rover.take('>')); } } /** * Handles the assignment of type variables to index names so that * we have a normalized name for each type var. * * @param map the map with variables. * @param name The name of the variable * @return the index name, like _1 */ private String assign(Map map, String name) { if (map.containsKey(name)) return map.get(name); else { int n = map.size(); map.put(name, "_" + n); return "_" + n; } } private boolean isInstance(Class type, String string) { if ( type == null) return false; if ( type.getName().equals(string)) return true; if ( isInstance( type.getSuperclass(), string)) return true; for ( Class intf : type.getInterfaces()) { if ( isInstance(intf,string)) return true; } return false; } private Object call(Object gd, String string) throws Exception { Method m = gd.getClass().getMethod(string); return m.invoke(gd); } } bnd-1.50.0/biz.aQute.bndlib/src/aQute/bnd/compatibility/Scope.java0000644000175000017500000000673611656076535024557 0ustar drazzibdrazzibpackage aQute.bnd.compatibility; import java.io.*; import java.util.*; public class Scope { final Map children = new LinkedHashMap(); // class: slashed name // field: name ":" typed // constructor: ":(" typed* ")" typed // method: name ":(" typed* ")" typed final String name; Access access; Kind kind; Scope enclosing; Scope declaring; GenericParameter typeVars[]; Map name2bounds; // class: super // field: type // constructor: void // method: return GenericType base; // class: interfaces // constructor: args // method: args GenericType[] parameters; // constructor: exceptions // method: exceptions GenericType[] exceptions; // class: super interfaces* // field: type // constructor: void arguments* // method: return arguments* public Scope(Access access, Kind kind, String name) { this.access = access; this.kind = kind; this.name = name; } Scope getScope(String name) { Scope s = children.get(name); if (s != null) return s; s = new Scope(Access.UNKNOWN, Kind.UNKNOWN, name); children.put(name, s); s.declaring = this; return s; } public void setParameterTypes(GenericType[] convert) { this.parameters = convert; } public void setExceptionTypes(GenericType[] convert) { this.exceptions = convert; } public void setBase(GenericType typeSignature) { base = typeSignature; } public String toString() { StringBuilder sb = new StringBuilder(); if ( typeVars != null && typeVars.length !=0) { sb.append("<"); for ( GenericParameter v : typeVars) { sb.append(v); } sb.append(">"); } sb.append(access.toString()); sb.append(" "); sb.append(kind.toString()); sb.append( " "); sb.append( name ); return sb.toString(); } public void report(Appendable a, int indent) throws IOException { for (int i = 0; i < indent; i++) a.append(" "); a.append(toString()); a.append("\n"); for (Scope s : children.values()) s.report(a, indent + 1); } public void add(Scope m) { children.put(m.name, m); } public void setDeclaring(Scope declaring) { this.declaring = declaring; } public void setAccess(Access access) { this.access = access; } public void setEnclosing(Scope enclosing) { this.enclosing = enclosing; if (this.enclosing != null) { this.enclosing.add(this); } } public boolean isTop() { return enclosing == null; } public void setKind(Kind kind) { this.kind = kind; } static public String classIdentity(String name) { return name.replace('.', '/'); } static public String methodIdentity(String name, String descriptor) { return name + ":" + descriptor; } static public String constructorIdentity(String descriptor) { return ":" + descriptor; } static public String fieldIdentity(String name, String descriptor) { return name + ":" + descriptor; } public void cleanRoot() { Iterator> i = children.entrySet().iterator(); while (i.hasNext()) { Map.Entry entry = i.next(); if (!entry.getValue().isTop()) i.remove(); } } public void prune(EnumSet level) { Iterator> i = children.entrySet().iterator(); while (i.hasNext()) { Map.Entry entry = i.next(); if (!level.contains(entry.getValue().access)) i.remove(); else entry.getValue().prune(level); } } public void setGenericParameter(GenericParameter[] typeVars) { this.typeVars = typeVars; } } bnd-1.50.0/biz.aQute.bndlib/src/aQute/bnd/compatibility/Kind.java0000644000175000017500000000033511656076535024360 0ustar drazzibdrazzibpackage aQute.bnd.compatibility; /** * The kind of thing we scope * */ public enum Kind { ROOT, CLASS, FIELD, CONSTRUCTOR, METHOD, UNKNOWN; public String toString() { return super.toString().toLowerCase(); } } bnd-1.50.0/biz.aQute.bndlib/src/aQute/bnd/compatibility/GenericParameter.java0000644000175000017500000000110511656076535026704 0ustar drazzibdrazzibpackage aQute.bnd.compatibility; public class GenericParameter { String name; GenericType bounds[]; public GenericParameter(String name, GenericType[] bounds) { this.name = name; this.bounds = bounds; if (bounds == null || bounds.length == 0) bounds = new GenericType[] { new GenericType( Object.class) }; } public String toString() { StringBuilder sb = new StringBuilder(); sb.append(name); if ( bounds != null && bounds.length > 0) { for ( GenericType gtype : bounds ) { sb.append( ":"); sb.append(gtype); } } return sb.toString(); } } bnd-1.50.0/biz.aQute.bndlib/src/aQute/bnd/compatibility/SignatureGenerator.java0000644000175000017500000000625511656076535027312 0ustar drazzibdrazzibpackage aQute.bnd.compatibility; public class SignatureGenerator { // enum ACCESS { //// PUBLIC("+"), PROTECTED("|"), PACKAGE_PRIVATE(""), PRIVATE("-"); //// final String repr; //// //// ACCESS(String s) { //// repr = s; //// } //// //// public String toString() { //// return repr; //// } // } // // public static void main(String args[]) throws Exception { // final PrintStream out = System.out; // // Clazz c = new Clazz("x", new FileResource(new File( // "src/aQute/bnd/compatibility/SignatureGenerator.class"))); // c.parseClassFileWithCollector(new ClassDataCollector() { // public void classBegin(int access, String name) { // out.print(name); // out.println(access(access)); // } // // private ACCESS access(int access) { // if (Modifier.isPublic(access)) // return ACCESS.PUBLIC; // // throw new IllegalArgumentException(); // } // // public void extendsClass(String name) { // } // // public void implementsInterfaces(String name[]) { // } // // public void addReference(String token) { // } // // public void annotation(Annotation annotation) { // } // // public void parameter(int p) { // } // // public void method(Clazz.MethodDef defined) { // if (defined.isConstructor()) // constructor(defined.access, defined.descriptor); // else // method(defined.access, defined.name, defined.descriptor); // } // // public void field(Clazz.FieldDef defined) { // field(defined.access, defined.name, defined.descriptor); // } // // public void reference(Clazz.MethodDef referenced) { // } // // public void reference(Clazz.FieldDef referenced) { // } // // public void classEnd() { // } // // @Deprecated// Will really be removed! // public void field(int access, String name, String descriptor) { // } // // @Deprecated// Will really be removed! // public void constructor(int access, String descriptor) { // } // // @Deprecated// Will really be removed! // public void method(int access, String name, String descriptor) { // } // // /** // * The EnclosingMethod attribute // * // * @param cName // * The name of the enclosing class, never null. Name is // * with slashes. // * @param mName // * The name of the enclosing method in the class with // * cName or null // * @param mDescriptor // * The descriptor of this type // */ // public void enclosingMethod(String cName, String mName, String mDescriptor) { // // } // // /** // * The InnerClass attribute // * // * @param innerClass // * The name of the inner class (with slashes). Can be // * null. // * @param outerClass // * The name of the outer class (with slashes) Can be // * null. // * @param innerName // * The name inside the outer class, can be null. // * @param modifiers // * The access flags // */ // public void innerClass(String innerClass, String outerClass, String innerName, // int innerClassAccessFlags) { // } // // public void signature(String signature) { // } // // public void constant(Object object) { // } // // }); // } } bnd-1.50.0/biz.aQute.bndlib/src/aQute/bnd/compatibility/RuntimeSignatureBuilder.java0000644000175000017500000001421311656076535030307 0ustar drazzibdrazzibpackage aQute.bnd.compatibility; import java.lang.reflect.*; public class RuntimeSignatureBuilder { final Scope root; public RuntimeSignatureBuilder(Scope root) { this.root = root; } static public String identity(Class c) { return Scope.classIdentity(c.getName()); } static public String identity(Method m) { return Scope.methodIdentity(m.getName(), getDescriptor(m.getReturnType(), m .getParameterTypes())); } static public String identity(Constructor m) { return Scope.constructorIdentity(getDescriptor(void.class, m.getParameterTypes())); } static public String identity(Field m) { return Scope.fieldIdentity(m.getName(), getDescriptor(m.getType(), null)); } static public String getDescriptor(Class base, Class[] parameters) { StringBuilder sb = new StringBuilder(); if (parameters != null) { sb.append("("); for (Class parameter : parameters) { sb.append(getDescriptor(parameter)); } sb.append(")"); } sb.append(getDescriptor(base)); return sb.toString(); } public Scope add(Class c) { Scope local = add(root, getEnclosingScope(c), c.getModifiers(), c.getTypeParameters(), Kind.CLASS, identity(c), c.getGenericSuperclass(), c.getGenericInterfaces(), null); for (Field f : c.getDeclaredFields()) { add(local, // declaring scope local, // enclosing f.getModifiers(), // access modifiers null, // fields have no type vars Kind.FIELD, // field identity(f), // the name of the field f.getGenericType(), // the type of the field null, // fields have no parameters null // fields have no exceptions ); } for (Constructor constr : c.getConstructors()) { add(local, // class scope local, // enclosing constr.getModifiers(), // access modifiers constr.getTypeParameters(), // Type vars Kind.CONSTRUCTOR, // constructor identity(constr), // (type*) void.class, // Always void constr.getGenericParameterTypes(), // parameters types constr.getGenericExceptionTypes() // exception types ); } for (Method m : c.getDeclaredMethods()) { if (m.getDeclaringClass() != Object.class) { add(local, // class scope local, // enclosing m.getModifiers(), // access modifiers m.getTypeParameters(), Kind.METHOD, // method identity(m), // (type*)return m.getGenericReturnType(), // return type m.getGenericParameterTypes(), // parameter types m.getGenericExceptionTypes() // exception types ); } } return local; } private Scope getEnclosingScope(Class c) { Method m = c.getEnclosingMethod(); if (m != null) { Scope s = getGlobalScope(m.getDeclaringClass()); return s.getScope(identity(m)); } // TODO // Constructor cnstr = c.getEnclosingConstructor(); // if (m != null) { // Scope s = getGlobalScope(cnstr.getDeclaringClass()); // return s.getScope(identity(cnstr)); // // } Class enclosingClass = c.getEnclosingClass(); if (enclosingClass != null) { return getGlobalScope(enclosingClass); } return null; } private Scope getGlobalScope(Class c) { if (c == null) return null; String id = identity(c); return root.getScope(id); } private Scope add(Scope declaring, Scope enclosing, int modifiers, TypeVariable[] typeVariables, Kind kind, String id, Type mainType, Type[] parameterTypes, Type exceptionTypes[]) { Scope scope = declaring.getScope(id); assert scope.access == Access.UNKNOWN; scope.setAccess(Access.modifier(modifiers)); scope.setKind(kind); scope.setGenericParameter(convert(typeVariables)); scope.setBase(convert(scope,mainType)); scope.setParameterTypes(convert(parameterTypes)); scope.setExceptionTypes(convert(exceptionTypes)); scope.setDeclaring(declaring); scope.setEnclosing(enclosing); return scope; } private GenericType convert(Scope source, Type t) { if (t instanceof ParameterizedType) { // C ParameterizedType pt = (ParameterizedType) t; /*Scope reference =*/ root.getScope(identity((Class)pt.getRawType())); Type args[] = pt.getActualTypeArguments(); GenericType[] arguments = new GenericType[args.length]; int n = 0; for (Type arg : args) arguments[n++] = convert(source,arg); // return new GenericType(reference,null,arguments); } else if (t instanceof TypeVariable) { // TypeVariable tv = (TypeVariable) t; // return new GenericType(source,tv.getName(), null); } else if (t instanceof WildcardType) { // WildcardType wc = (WildcardType) t; // wc. } else if (t instanceof GenericArrayType) { } if (t instanceof Class) { // raw = ((Class) t).getName() + ";"; } else throw new IllegalArgumentException(t.toString()); return null; } private GenericParameter[] convert(TypeVariable vars[]) { if (vars == null) return null; GenericParameter out[] = new GenericParameter[vars.length]; for (int i = 0; i < vars.length; i++) { GenericType gss[] = convert(vars[i].getBounds()); out[i] = new GenericParameter(vars[i].getName(), gss); } return out; } private GenericType[] convert(Type[] parameterTypes) { if (parameterTypes == null || parameterTypes.length == 0) return GenericType.EMPTY; GenericType tss[] = new GenericType[parameterTypes.length]; for (int i = 0; i < parameterTypes.length; i++) { //tss[i] = new GenericType(parameterTypes[i]); } return tss; } private static String getDescriptor(Class c) { StringBuilder sb = new StringBuilder(); if (c.isPrimitive()) { if (c == boolean.class) sb.append("Z"); else if (c == byte.class) sb.append("Z"); else if (c == char.class) sb.append("C"); else if (c == short.class) sb.append("S"); else if (c == int.class) sb.append("I"); else if (c == long.class) sb.append("J"); else if (c == float.class) sb.append("F"); else if (c == double.class) sb.append("D"); else if (c == void.class) sb.append("V"); else throw new IllegalArgumentException("unknown primitive type: " + c); } else if (c.isArray()) { sb.append("["); sb.append(getDescriptor(c)); } else { sb.append("L"); sb.append(c.getName().replace('.', '/')); sb.append(";"); } return sb.toString(); } } bnd-1.50.0/biz.aQute.bndlib/src/aQute/bnd/compatibility/Access.java0000644000175000017500000000070211656076535024672 0ustar drazzibdrazzibpackage aQute.bnd.compatibility; import java.lang.reflect.*; /** * Access modifier */ public enum Access { PUBLIC, PROTECTED, PACKAGE, PRIVATE, UNKNOWN; public static Access modifier(int mod) { if (Modifier.isPublic(mod)) return PUBLIC; if (Modifier.isProtected(mod)) return PROTECTED; if (Modifier.isPrivate(mod)) return PRIVATE; return PACKAGE; } public String toString() { return super.toString().toLowerCase(); } } bnd-1.50.0/biz.aQute.bndlib/src/aQute/bnd/maven/0000755000175000017500000000000011656076535021064 5ustar drazzibdrazzibbnd-1.50.0/biz.aQute.bndlib/src/aQute/bnd/maven/BsnToMavenPath.java0000644000175000017500000000015411656076535024560 0ustar drazzibdrazzibpackage aQute.bnd.maven; public interface BsnToMavenPath { String[] getGroupAndArtifact(String bsn); } bnd-1.50.0/biz.aQute.bndlib/src/aQute/bnd/maven/MavenCommand.java0000644000175000017500000004124511656076535024302 0ustar drazzibdrazzibpackage aQute.bnd.maven; import java.io.*; import java.net.*; import java.util.*; import java.util.concurrent.*; import java.util.jar.*; import java.util.regex.*; import aQute.bnd.maven.support.*; import aQute.bnd.maven.support.Pom.*; import aQute.bnd.settings.*; import aQute.lib.collections.*; import aQute.lib.io.*; import aQute.lib.osgi.*; import aQute.libg.command.*; import aQute.libg.header.*; public class MavenCommand extends Processor { final Settings settings = new Settings(); File temp; public MavenCommand() { } public MavenCommand(Processor p) { super(p); } /** * maven deploy [-url repo] [-passphrase passphrase] [-homedir homedir] * [-keyname keyname] bundle ... * * @param args * @param i * @throws Exception */ public void run(String args[], int i) throws Exception { temp = new File("maven-bundle"); if (i >= args.length) { help(); return; } while (i < args.length && args[i].startsWith("-")) { String option = args[i]; trace("option " + option); if (option.equals("-temp")) temp = getFile(args[++i]); else { help(); error("Invalid option " + option); } i++; } String cmd = args[i++]; trace("temp dir " + temp); IO.delete(temp); temp.mkdirs(); if (!temp.isDirectory()) throw new IOException("Cannot create temp directory"); if (cmd.equals("settings")) settings(); else if (cmd.equals("help")) help(); else if (cmd.equals("bundle")) bundle(args, i); else if (cmd.equals("view")) view(args, i); else error("No such command %s, type help", cmd); } private void help() { System.err.println("Usage:\n"); System.err .println(" maven \n" // + " [-temp ] use as temp directory\n" // + " settings show maven settings\n" // + " bundle turn a bundle into a maven bundle\n" // + " [-properties ] provide properties, properties starting with javadoc are options for javadoc, like javadoc-tag=...\n" + " [-javadoc ] where to find the javadoc (zip/dir), otherwise generated\n" // + " [-source ] where to find the source (zip/dir), otherwise from OSGI-OPT/src\n" // + " [-scm ] required scm in pom, otherwise from Bundle-SCM\n" // + " [-url ] required project url in pom\n" // + " [-bsn bsn] overrides bsn\n" // + " [-version ] overrides version\n" // + " [-developer ] developer email\n" // + " [-nodelete] do not delete temp files\n" // + " [-passphrase ] signer password\n"// + " "); } /** * Show the maven settings * * @throws FileNotFoundException * @throws Exception */ private void settings() throws FileNotFoundException, Exception { File userHome = new File(System.getProperty("user.home")); File m2 = new File(userHome, ".m2"); if (!m2.isDirectory()) { error("There is no m2 directory at %s", userHome); return; } File settings = new File(m2, "settings.xml"); if (!settings.isFile()) { error("There is no settings file at '%s'", settings.getAbsolutePath()); return; } FileReader rdr = new FileReader(settings); LineCollection lc = new LineCollection(new BufferedReader(rdr)); while (lc.hasNext()) { System.out.println(lc.next()); } } /** * Create a maven bundle. * * @param args * @param i * @throws Exception */ private void bundle(String args[], int i) throws Exception { List developers = new ArrayList(); Properties properties = new Properties(); String scm = null; String passphrase = null; String javadoc = null; String source = null; String output = "bundle.jar"; String url = null; String artifact = null; String group = null; String version = null; boolean nodelete = false; while (i < args.length && args[i].startsWith("-")) { String option = args[i++]; trace("bundle option %s", option); if (option.equals("-scm")) scm = args[i++]; else if (option.equals("-group")) group = args[i++]; else if (option.equals("-artifact")) artifact = args[i++]; else if (option.equals("-version")) version = args[i++]; else if (option.equals("-developer")) developers.add(args[i++]); else if (option.equals("-passphrase")) { passphrase = args[i++]; } else if (option.equals("-url")) { url = args[i++]; } else if (option.equals("-javadoc")) javadoc = args[i++]; else if (option.equals("-source")) source = args[i++]; else if (option.equals("-output")) output = args[i++]; else if (option.equals("-nodelete")) nodelete=true; else if (option.startsWith("-properties")) { InputStream in = new FileInputStream(args[i++]); try { properties.load(in); } catch (Exception e) { in.close(); } } } if (developers.isEmpty()) { String email = settings.globalGet(Settings.EMAIL, null); if (email == null) error("No developer email set, you can set global default email with: bnd global email Peter.Kriens@aQute.biz"); else developers.add(email); } if (i == args.length) { error("too few arguments, no bundle specified"); return; } if (i != args.length - 1) { error("too many arguments, only one bundle allowed"); return; } String input = args[i++]; Jar binaryJar = getJarFromFileOrURL(input); trace("got %s", binaryJar); if (binaryJar == null) { error("JAR does not exist: %s", input); return; } File original = getFile(temp, "original"); original.mkdirs(); binaryJar.expand(original); binaryJar.calcChecksums(null); Manifest manifest = binaryJar.getManifest(); trace("got manifest"); PomFromManifest pom = new PomFromManifest(manifest); if (scm != null) pom.setSCM(scm); if (url != null) pom.setURL(url); if (artifact != null) pom.setArtifact(artifact); if (artifact != null) pom.setGroup(group); if (version != null) pom.setVersion(version); trace(url); for (String d : developers) pom.addDeveloper(d); Set exports = OSGiHeader.parseHeader( manifest.getMainAttributes().getValue(Constants.EXPORT_PACKAGE)).keySet(); Jar sourceJar; if (source == null) { trace("Splitting source code"); sourceJar = new Jar("source"); for (Map.Entry entry : binaryJar.getResources().entrySet()) { if (entry.getKey().startsWith("OSGI-OPT/src")) { sourceJar.putResource(entry.getKey().substring("OSGI-OPT/src/".length()), entry.getValue()); } } copyInfo(binaryJar, sourceJar, "source"); } else { sourceJar = getJarFromFileOrURL(source); } sourceJar.calcChecksums(null); Jar javadocJar; if (javadoc == null) { trace("creating javadoc because -javadoc not used"); javadocJar = javadoc(getFile(original, "OSGI-OPT/src"), exports, manifest, properties); if (javadocJar == null) { error("Cannot find source code in OSGI-OPT/src to generate Javadoc"); return; } copyInfo(binaryJar, javadocJar, "javadoc"); } else { trace("Loading javadoc externally %s", javadoc); javadocJar = getJarFromFileOrURL(javadoc); } javadocJar.calcChecksums(null); addClose(binaryJar); addClose(sourceJar); addClose(javadocJar); trace("creating bundle dir"); File bundle = new File(temp, "bundle"); bundle.mkdirs(); String prefix = pom.getArtifactId() + "-" + pom.getVersion(); File binaryFile = new File(bundle, prefix + ".jar"); File sourceFile = new File(bundle, prefix + "-sources.jar"); File javadocFile = new File(bundle, prefix + "-javadoc.jar"); File pomFile = new File(bundle, "pom.xml").getAbsoluteFile(); trace("creating output files %s, %s,%s, and %s", binaryFile, sourceFile, javadocFile, pomFile); IO.copy(pom.openInputStream(), pomFile); trace("copied pom"); trace("writing binary %s", binaryFile); binaryJar.write(binaryFile); trace("writing source %s", sourceFile); sourceJar.write(sourceFile); trace("writing javadoc %s", javadocFile); javadocJar.write(javadocFile); sign(binaryFile, passphrase); sign(sourceFile, passphrase); sign(javadocFile, passphrase); sign(pomFile, passphrase); trace("create bundle"); Jar bundleJar = new Jar(bundle); addClose(bundleJar); File outputFile = getFile(output); bundleJar.write(outputFile); trace("created bundle %s", outputFile); binaryJar.close(); sourceJar.close(); javadocJar.close(); bundleJar.close(); if (!nodelete) IO.delete(temp); } private void copyInfo(Jar source, Jar dest, String type) throws Exception { source.ensureManifest(); dest.ensureManifest(); copyInfoResource( source, dest, "LICENSE"); copyInfoResource( source, dest, "LICENSE.html"); copyInfoResource( source, dest, "about.html"); Manifest sm = source.getManifest(); Manifest dm = dest.getManifest(); copyInfoHeader( sm, dm, "Bundle-Description",""); copyInfoHeader( sm, dm, "Bundle-Vendor",""); copyInfoHeader( sm, dm, "Bundle-Copyright",""); copyInfoHeader( sm, dm, "Bundle-DocURL",""); copyInfoHeader( sm, dm, "Bundle-License",""); copyInfoHeader( sm, dm, "Bundle-Name", " " + type); copyInfoHeader( sm, dm, "Bundle-SymbolicName", "." + type); copyInfoHeader( sm, dm, "Bundle-Version", ""); } private void copyInfoHeader(Manifest sm, Manifest dm, String key, String value) { String v = sm.getMainAttributes().getValue(key); if ( v == null) { trace("no source for " + key); return; } if ( dm.getMainAttributes().getValue(key) != null) { trace("already have " + key ); return; } dm.getMainAttributes().putValue(key, v + value); } private void copyInfoResource(Jar source, Jar dest, String type) { if ( source.getResources().containsKey(type) && !dest.getResources().containsKey(type)) dest.putResource(type, source.getResource(type)); } /** * @return * @throws IOException * @throws MalformedURLException */ protected Jar getJarFromFileOrURL(String spec) throws IOException, MalformedURLException { Jar jar; File jarFile = getFile(spec); if (jarFile.exists()) { jar = new Jar(jarFile); } else { URL url = new URL(spec); InputStream in = url.openStream(); try { jar = new Jar(url.getFile(), in); } finally { in.close(); } } addClose(jar); return jar; } private void sign(File file, String passphrase) throws Exception { trace("signing %s", file); File asc = new File(file.getParentFile(), file.getName() + ".asc"); asc.delete(); Command command = new Command(); command.setTrace(); command.add(getProperty("gpgp", "gpg")); if (passphrase != null) command.add("--passphrase", passphrase); command.add("-ab", "--sign"); // not the -b!! command.add(file.getAbsolutePath()); System.out.println(command); StringBuffer stdout = new StringBuffer(); StringBuffer stderr = new StringBuffer(); int result = command.execute(stdout, stderr); if (result != 0) { error("gpg signing %s failed because %s", file, "" + stdout + stderr); } } private Jar javadoc(File source, Set exports, Manifest m, Properties p) throws Exception { File tmp = new File(temp, "javadoc"); tmp.mkdirs(); Command command = new Command(); command.add(getProperty("javadoc", "javadoc")); command.add("-quiet"); command.add("-protected"); // command.add("-classpath"); // command.add(binary.getAbsolutePath()); command.add("-d"); command.add(tmp.getAbsolutePath()); command.add("-charset"); command.add("UTF-8"); command.add("-sourcepath"); command.add(source.getAbsolutePath()); Attributes attr = m.getMainAttributes(); Properties pp = new Properties(p); set(pp, "-doctitle", description(attr)); set(pp, "-header", description(attr)); set(pp, "-windowtitle", name(attr)); set(pp, "-bottom", copyright(attr)); set(pp, "-footer", license(attr)); command.add("-tag"); command.add("Immutable:t:Immutable"); command.add("-tag"); command.add("ThreadSafe:t:ThreadSafe"); command.add("-tag"); command.add("NotThreadSafe:t:NotThreadSafe"); command.add("-tag"); command.add("GuardedBy:mf:Guarded By:"); command.add("-tag"); command.add("security:m:Required Permissions"); command.add("-tag"); command.add("noimplement:t:Consumers of this API must not implement this interface"); for (Enumeration e = pp.propertyNames(); e.hasMoreElements();) { String key = (String) e.nextElement(); String value = pp.getProperty(key); if (key.startsWith("javadoc")) { key = key.substring("javadoc".length()); removeDuplicateMarker(key); command.add(key); command.add(value); } } for (String packageName : exports) { command.add(packageName); } StringBuffer out = new StringBuffer(); StringBuffer err = new StringBuffer(); System.out.println(command); int result = command.execute(out, err); if (result != 0) { warning("Error during execution of javadoc command: %s\n******************\n%s", out, err); } Jar jar = new Jar(tmp); addClose(jar); return jar; } /** * Generate a license string * * @param attr * @return */ private String license(Attributes attr) { Map> map = Processor.parseHeader( attr.getValue(Constants.BUNDLE_LICENSE), null); if (map.isEmpty()) return null; StringBuilder sb = new StringBuilder(); String sep = "Licensed under "; for (Map.Entry> entry : map.entrySet()) { sb.append(sep); String key = entry.getKey(); String link = entry.getValue().get("link"); String description = entry.getValue().get("description"); if (description == null) description = key; if (link != null) { sb.append(""); } sb.append(description); if (link != null) { sb.append(""); } sep = ",
"; } return sb.toString(); } /** * Generate the copyright statement. * * @param attr * @return */ private String copyright(Attributes attr) { return attr.getValue(Constants.BUNDLE_COPYRIGHT); } private String name(Attributes attr) { String name = attr.getValue(Constants.BUNDLE_NAME); if (name == null) name = attr.getValue(Constants.BUNDLE_SYMBOLICNAME); return name; } private String description(Attributes attr) { String descr = attr.getValue(Constants.BUNDLE_DESCRIPTION); if (descr == null) descr = attr.getValue(Constants.BUNDLE_NAME); if (descr == null) descr = attr.getValue(Constants.BUNDLE_SYMBOLICNAME); return descr; } private void set(Properties pp, String option, String defaultValue) { String key = "javadoc" + option; String existingValue = pp.getProperty(key); if (existingValue != null) return; pp.setProperty(key, defaultValue); } /** * View - Show the dependency details of an artifact */ static Executor executor = Executors.newCachedThreadPool(); static Pattern GROUP_ARTIFACT_VERSION = Pattern.compile("([^+]+)\\+([^+]+)\\+([^+]+)"); void view( String args[], int i) throws Exception { Maven maven = new Maven(executor); OutputStream out = System.out; List urls = new ArrayList(); while ( i < args.length && args[i].startsWith("-")) { if( "-r".equals(args[i])) { URI uri = new URI(args[++i]); urls.add( uri ); System.out.println("URI for repo " + uri); } else if ( "-o".equals(args[i])) { out = new FileOutputStream(args[++i]); } else throw new IllegalArgumentException("Unknown option: " + args[i]); i++; } URI[] urls2 = urls.toArray(new URI[urls.size()]); PrintWriter pw = new PrintWriter(out); while ( i < args.length) { String ref = args[i++]; pw.println("Ref " + ref); Matcher matcher = GROUP_ARTIFACT_VERSION.matcher(ref); if (matcher.matches()) { String group = matcher.group(1); String artifact = matcher.group(2); String version = matcher.group(3); CachedPom pom = maven.getPom(group, artifact, version, urls2); Builder a = new Builder(); a.setProperty("Private-Package", "*"); Set dependencies = pom.getDependencies(Scope.compile, urls2); for ( Pom dep : dependencies ) { System.out.printf( "%20s %-20s %10s\n", dep.getGroupId(), dep.getArtifactId(), dep.getVersion()); a.addClasspath(dep.getArtifact()); } pw.println(a.getClasspath()); a.build(); TreeSet sorted = new TreeSet( a.getImports().keySet()); for ( String p :sorted) { pw.printf("%-40s\n",p); } // for ( Map.Entry> entry : a.getUses().entrySet()) { // String from = entry.getKey(); // for ( String uses : entry.getValue()) { // System.out.printf("%40s %s\n", from, uses); // from = ""; // } // } a.close(); } else System.err.println("Wrong, must look like group+artifact+version, is " + ref); } } } bnd-1.50.0/biz.aQute.bndlib/src/aQute/bnd/maven/MavenDeployCmd.java0000644000175000017500000001475011656076535024605 0ustar drazzibdrazzibpackage aQute.bnd.maven; import java.io.*; import java.util.*; import java.util.jar.*; import aQute.bnd.build.*; import aQute.lib.osgi.*; import aQute.libg.command.*; import aQute.libg.reporter.*; public class MavenDeployCmd extends Processor { String repository = "nexus"; String url = "http://oss.sonatype.org/service/local/staging/deploy/maven2"; String homedir; String keyname; String passphrase; Reporter reporter; /** * maven deploy [-url repo] [-passphrase passphrase] [-homedir homedir] * [-keyname keyname] bundle ... * * @param args * @param i * @throws Exception */ void run(String args[], int i) throws Exception { if (i >= args.length) { System.err .println("Usage:\n"); System.err.println(" deploy [-url repo] [-passphrase passphrase] [-homedir homedir] [-keyname keyname] bundle ..."); System.err.println(" settings"); return; } @SuppressWarnings("unused") String cmd = args[i++]; while (i < args.length && args[i].startsWith("-")) { String option = args[i]; if (option.equals("-url")) repository = args[++i]; else if (option.equals("-passphrase")) passphrase = args[++i]; else if (option.equals("-url")) homedir = args[++i]; else if (option.equals("-keyname")) keyname = args[++i]; else error("Invalid command "); } } public void setProperties(Map map) { repository = map.get("repository"); url = map.get("url"); passphrase = map.get("passphrase"); homedir = map.get("homedir"); keyname = map.get("keyname"); if (url == null) throw new IllegalArgumentException("MavenDeploy plugin must get a repository URL"); if (repository == null) throw new IllegalArgumentException("MavenDeploy plugin must get a repository name"); } public void setReporter(Reporter processor) { this.reporter = processor; } /** */ public boolean deploy(Project project, Jar original) throws Exception { Map> deploy = project.parseHeader(project .getProperty(Constants.DEPLOY)); Map maven = deploy.get(repository); if (maven == null) return false; // we're not playing for this bundle project.progress("deploying %s to Maven repo: %s", original, repository); File target = project.getTarget(); File tmp = Processor.getFile(target, repository); tmp.mkdirs(); Manifest manifest = original.getManifest(); if (manifest == null) project.error("Jar has no manifest: %s", original); else { project.progress("Writing pom.xml"); PomResource pom = new PomResource(manifest); pom.setProperties(maven); File pomFile = write(tmp, pom, "pom.xml"); Jar main = new Jar("main"); Jar src = new Jar("src"); try { split(original, main, src); Map> exports = project.parseHeader(manifest .getMainAttributes().getValue(Constants.EXPORT_PACKAGE)); File jdoc = new File(tmp, "jdoc"); jdoc.mkdirs(); project.progress("Generating Javadoc for: " + exports.keySet()); Jar javadoc = javadoc(jdoc, project, exports.keySet()); project.progress("Writing javadoc jar"); File javadocFile = write(tmp, new JarResource(javadoc), "javadoc.jar"); project.progress("Writing main file"); File mainFile = write(tmp, new JarResource(main), "main.jar"); project.progress("Writing sources file"); File srcFile = write(tmp, new JarResource(main), "src.jar"); project.progress("Deploying main file"); maven_gpg_sign_and_deploy(project, mainFile, null, pomFile); project.progress("Deploying main sources file"); maven_gpg_sign_and_deploy(project, srcFile, "sources", null); project.progress("Deploying main javadoc file"); maven_gpg_sign_and_deploy(project, javadocFile, "javadoc", null); } finally { main.close(); src.close(); } } return true; } private void split(Jar original, Jar main, Jar src) { for (Map.Entry e : original.getResources().entrySet()) { String path = e.getKey(); if (path.startsWith("OSGI-OPT/src/")) { src.putResource(path.substring("OSGI-OPT/src/".length()), e.getValue()); } else { main.putResource(path, e.getValue()); } } } // gpg:sign-and-deploy-file \ // -Durl=http://oss.sonatype.org/service/local/staging/deploy/maven2 // \ // -DrepositoryId=sonatype-nexus-staging \ // -DupdateReleaseInfo=true \ // -DpomFile=pom.xml \ // -Dfile=/Ws/bnd/biz.aQute.bndlib/tmp/biz.aQute.bndlib.jar \ // -Dpassphrase=a1k3v3t5x3 private void maven_gpg_sign_and_deploy(Project b, File file, String classifier, File pomFile) throws Exception { Command command = new Command(); command.setTrace(); command.add(b.getProperty("mvn", "mvn")); command.add("gpg:sign-and-deploy-file", "-DreleaseInfo=true", "-DpomFile=pom.xml"); command.add("-Dfile=" + file.getAbsolutePath()); command.add("-DrepositoryId=" + repository); command.add("-Durl=" + url); optional(command, "passphrase", passphrase); optional(command, "keyname", keyname); optional(command, "homedir", homedir); optional(command, "classifier", classifier); optional(command, "pomFile", pomFile == null ? null : pomFile.getAbsolutePath()); StringBuffer stdout = new StringBuffer(); StringBuffer stderr = new StringBuffer(); int result = command.execute(stdout, stderr); if (result != 0) { b.error("Maven deploy to %s failed to sign and transfer %s because %s", repository, file, "" + stdout + stderr); } } private void optional(Command command, String key, String value) { if (value == null) return; command.add("-D=" + value); } private Jar javadoc(File tmp, Project b, Set exports) throws Exception { Command command = new Command(); command.add(b.getProperty("javadoc", "javadoc")); command.add("-d"); command.add(tmp.getAbsolutePath()); command.add("-sourcepath"); command.add(Processor.join(b.getSourcePath(), File.pathSeparator)); for (String packageName : exports) { command.add(packageName); } StringBuffer out = new StringBuffer(); StringBuffer err = new StringBuffer(); Command c = new Command(); c.setTrace(); int result = c.execute(out, err); if (result == 0) { Jar jar = new Jar(tmp); b.addClose(jar); return jar; } b.error("Error during execution of javadoc command: %s / %s", out, err); return null; } private File write(File base, Resource r, String fileName) throws Exception { File f = Processor.getFile(base, fileName); OutputStream out = new FileOutputStream(f); try { r.write(out); } finally { out.close(); } return f; } } bnd-1.50.0/biz.aQute.bndlib/src/aQute/bnd/maven/support/0000755000175000017500000000000011656076535022600 5ustar drazzibdrazzibbnd-1.50.0/biz.aQute.bndlib/src/aQute/bnd/maven/support/MavenEntry.java0000644000175000017500000002011711656076535025534 0ustar drazzibdrazzibpackage aQute.bnd.maven.support; import java.io.*; import java.net.*; import java.security.*; import java.util.*; import java.util.concurrent.*; import aQute.lib.hex.*; import aQute.lib.io.*; import aQute.libg.filelock.*; /** * An entry (a group/artifact) in the maven cache in the .m2/repository * directory. It provides methods to get the pom and the artifact. * */ public class MavenEntry implements Closeable { final Maven maven; final File root; final File dir; final String path; final DirectoryLock lock; final Map poms = new HashMap(); final File pomFile; final File artifactFile; final String pomPath; final File propertiesFile; Properties properties; private boolean propertiesChanged; FutureTask artifact; private String artifactPath; /** * Constructor. * * @param maven * @param path */ MavenEntry(Maven maven, String path) { this.root = maven.repository; this.maven = maven; this.path = path; this.pomPath = path + ".pom"; this.artifactPath = path + ".jar"; this.dir = IO.getFile(maven.repository, path).getParentFile(); this.dir.mkdirs(); this.pomFile = new File(maven.repository, pomPath); this.artifactFile = new File(maven.repository, artifactPath); this.propertiesFile = new File(dir, "bnd.properties"); this.lock = new DirectoryLock(dir, 5 * 60000); // 5 mins } /** * This is the method to get the POM for a cached entry. * * @param urls * The allowed URLs * @return a CachedPom for this maven entry * * @throws Exception * If something goes haywire */ public CachedPom getPom(URI[] urls) throws Exception { // First check if we have the pom cached in memory synchronized (this) { // Try to find it in the in-memory cache for (URI url : urls) { CachedPom pom = poms.get(url); if (pom != null) return pom; } } // Ok, we need to see if it exists on disk // lock.lock(); try { if (isValid()) { // Check if one of our repos had the correct file. for (URI url : urls) { String valid = getProperty(url.toASCIIString()); if (valid != null) return createPom(url); } // we have the info, but have to verify that it // exists in one of our repos but we do not have // to download it as our cache is already ok. for (URI url : urls) { if (verify(url, pomPath)) { return createPom(url); } } // It does not exist in out repo // so we have to fail even though we do have // the file. } else { dir.mkdirs(); // We really do not have the file // so we have to find out who has it. for (final URI url : urls) { if (download(url, pomPath)) { if (verify(url, pomPath)) { artifact = new FutureTask(new Callable() { public File call() throws Exception { if (download(url, artifactPath)) { verify(url, artifactPath); } return artifactFile; } }); maven.executor.execute(artifact); return createPom(url); } } } } return null; } finally { saveProperties(); // lock.release(); } } /** * Download a resource from the given repo. * * @param url * The base url for the repo * @param path * The path part * @return * @throws MalformedURLException */ private boolean download(URI repo, String path) throws MalformedURLException { try { URL url = toURL(repo, path); System.out.println("Downloading " + repo + " path " + path + " url " + url); File file = new File(root, path); IO.copy(url.openStream(), file); System.out.println("Downloaded " + url); return true; } catch (Exception e) { System.err.println("debug: " + e); return false; } } /** * Converts a repo + path to a URL.. * * @param base * The base repo * @param path * The path in the directory + url * @return a URL that points to the file in the repo * * @throws MalformedURLException */ URL toURL(URI base, String path) throws MalformedURLException { StringBuilder r = new StringBuilder(); r.append(base.toString()); if (r.charAt(r.length() - 1) != '/') r.append('/'); r.append(path); return new URL(r.toString()); } /** * Check if this is a valid cache directory, might probably need some more * stuff. * * @return true if valid */ private boolean isValid() { return pomFile.isFile() && pomFile.length() > 100 && artifactFile.isFile() && artifactFile.length() > 100; } /** * We maintain a set of bnd properties in the cache directory. * * @param key * The key for the property * @param value * The value for the property */ private void setProperty(String key, String value) { Properties properties = getProperties(); properties.setProperty(key, value); propertiesChanged = true; } /** * Answer the properties, loading if needed. */ protected Properties getProperties() { if (properties == null) { properties = new Properties(); File props = new File(dir, "bnd.properties"); if (props.exists()) { try { FileInputStream in = new FileInputStream(props); properties.load(in); } catch (Exception e) { // we ignore for now, will handle it on safe } } } return properties; } /** * Answer a property. * * @param key * The key * @return The value */ private String getProperty(String key) { Properties properties = getProperties(); return properties.getProperty(key); } private void saveProperties() throws IOException { if (propertiesChanged) { FileOutputStream fout = new FileOutputStream(propertiesFile); try { properties.store(fout, ""); } finally { properties = null; propertiesChanged = false; fout.close(); } } } /** * Help function to create the POM and record its source. * * @param url * the repo from which it was constructed * @return the new pom * @throws Exception */ private CachedPom createPom(URI url) throws Exception { CachedPom pom = new CachedPom(this, url); pom.parse(); poms.put(url, pom); setProperty(url.toASCIIString(), "true"); return pom; } /** * Verify that the repo has a checksum file for the given path and that this * checksum matchs. * * @param repo * The repo * @param path * The file id * @return true if there is a digest and it matches one of the algorithms * @throws Exception */ boolean verify(URI repo, String path) throws Exception { for (String algorithm : Maven.ALGORITHMS) { if (verify(repo, path, algorithm)) return true; } return false; } /** * Verify the path against its digest for the given algorithm. * * @param repo * @param path * @param algorithm * @return * @throws Exception */ private boolean verify(URI repo, String path, String algorithm) throws Exception { String digestPath = path + "." + algorithm; File actualFile = new File(root, path); if (download(repo, digestPath)) { File digestFile = new File(root, digestPath); final MessageDigest md = MessageDigest.getInstance(algorithm); IO.copy(actualFile, new OutputStream() { @Override public void write(int c) throws IOException { md.update((byte) c); } @Override public void write(byte[] buffer, int offset, int length) { md.update(buffer, offset, length); } }); byte[] digest = md.digest(); String source = IO.collect(digestFile).toUpperCase(); String hex = Hex.toHexString(digest).toUpperCase(); if (source.startsWith(hex)) { System.out.println("Verified ok " + actualFile + " digest " + algorithm); return true; } } System.out.println("Failed to verify " + actualFile + " for digest " + algorithm); return false; } public File getArtifact() throws Exception { if (artifact == null ) return artifactFile; return artifact.get(); } public File getPomFile() { return pomFile; } public void close() throws IOException { } public void remove() { if (dir.getParentFile() != null) { IO.delete(dir); } } } bnd-1.50.0/biz.aQute.bndlib/src/aQute/bnd/maven/support/Pom.java0000644000175000017500000002167211656076535024206 0ustar drazzibdrazzibpackage aQute.bnd.maven.support; import java.io.*; import java.net.*; import java.util.*; import javax.xml.parsers.*; import javax.xml.xpath.*; import org.w3c.dom.*; public abstract class Pom { static DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); static XPathFactory xpf = XPathFactory.newInstance(); static { dbf.setNamespaceAware(false); } public enum Scope { compile, runtime, system, import_, provided, test, ; private boolean includes(Scope other) { if (other == this) return true; switch (this) { case compile: return other == provided || other == test; default: return false; } } }; final Maven maven; final URI home; String groupId; String artifactId; String version; List dependencies = new ArrayList(); Exception exception; File pomFile; String description=""; String name; public String getDescription() { return description; } public class Dependency { Scope scope; String type; boolean optional; String groupId; String artifactId; String version; Set exclusions = new HashSet(); public Scope getScope() { return scope; } public String getType() { return type; } public boolean isOptional() { return optional; } public String getGroupId() { return replace(groupId); } public String getArtifactId() { return replace(artifactId); } public String getVersion() { return replace(version); } public Set getExclusions() { return exclusions; } public Pom getPom() throws Exception { return maven.getPom(groupId, artifactId, version); } @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append("Dependency ["); if (groupId != null) builder.append("groupId=").append(groupId).append(", "); if (artifactId != null) builder.append("artifactId=").append(artifactId).append(", "); if (version != null) builder.append("version=").append(version).append(", "); if (type != null) builder.append("type=").append(type).append(", "); if (scope != null) builder.append("scope=").append(scope).append(", "); builder.append("optional=").append(optional).append(", "); if (exclusions != null) builder.append("exclusions=").append(exclusions); builder.append("]"); return builder.toString(); } } public Pom(Maven maven, File pomFile, URI home) throws Exception { this.maven = maven; this.home = home; this.pomFile = pomFile; } void parse() throws Exception { DocumentBuilder db = dbf.newDocumentBuilder(); System.out.println("Parsing " + pomFile.getAbsolutePath()); Document doc = db.parse(pomFile); XPath xp = xpf.newXPath(); parse(doc, xp); } protected void parse(Document doc, XPath xp) throws XPathExpressionException, Exception { this.artifactId = replace(xp.evaluate("project/artifactId", doc).trim(), this.artifactId); this.groupId = replace(xp.evaluate("project/groupId", doc).trim(), this.groupId); this.version = replace(xp.evaluate("project/version", doc).trim(), this.version); String nextDescription = xp.evaluate("project/description", doc).trim(); if ( this.description.length() != 0 && nextDescription.length() != 0) this.description += "\n"; this.description += replace(nextDescription); this.name = replace(xp.evaluate("project/name", doc).trim(), this.name); NodeList list = (NodeList) xp.evaluate("project/dependencies/dependency", doc, XPathConstants.NODESET); for (int i = 0; i < list.getLength(); i++) { Node node = list.item(i); Dependency dep = new Dependency(); String scope = xp.evaluate("scope", node).trim(); if (scope.length() == 0) dep.scope = Scope.compile; else dep.scope = Scope.valueOf(scope); dep.type = xp.evaluate("type", node).trim(); String opt = xp.evaluate("optional", node).trim(); dep.optional = opt != null && opt.equalsIgnoreCase("true"); dep.groupId = replace(xp.evaluate("groupId", node)); dep.artifactId = replace(xp.evaluate("artifactId", node).trim()); dep.version = replace(xp.evaluate("version", node).trim()); dependencies.add(dep); NodeList exclusions = (NodeList) xp .evaluate("exclusions", node, XPathConstants.NODESET); for (int e = 0; e < exclusions.getLength(); e++) { Node exc = exclusions.item(e); String exclGroupId = xp.evaluate("groupId", exc).trim(); String exclArtifactId = xp.evaluate("artifactId", exc).trim(); dep.exclusions.add(exclGroupId + "+" + exclArtifactId); } } } private String replace(String key, String dflt) { if ( key == null || key.length() == 0) return dflt; return replace(key); } public String getArtifactId() throws Exception { return replace(artifactId); } public String getGroupId() throws Exception { return replace(groupId); } public String getVersion() throws Exception { if ( version == null) return ""; return replace(version); } public List getDependencies() throws Exception { return dependencies; } class Rover { public Rover(Rover rover, Dependency d) { this.previous = rover; this.dependency = d; } final Rover previous; final Dependency dependency; public boolean excludes(String name) { return dependency.exclusions.contains(name) && previous != null && previous.excludes(name); } } public Set getDependencies(Scope scope, URI... urls) throws Exception { Set result = new LinkedHashSet(); List queue = new ArrayList(); for (Dependency d : dependencies) { queue.add(new Rover(null, d)); } while (!queue.isEmpty()) { Rover rover = queue.remove(0); Dependency dep = rover.dependency; String groupId = replace(dep.groupId); String artifactId = replace(dep.artifactId); String version = replace(dep.version); String name = groupId + "+" + artifactId; if (rover.excludes(name) || dep.optional) continue; if (dep.scope == scope && !dep.optional) { try { Pom sub = maven.getPom(groupId, artifactId, version, urls); if (sub != null) { if (!result.contains(sub)) { result.add(sub); for (Dependency subd : sub.dependencies) { queue.add(new Rover(rover, subd)); } } } else if (rover.previous != null) System.out.println("Cannot find " + dep + " from " + rover.previous.dependency); else System.out.println("Cannot find " + dep + " from top"); } catch (Exception e) { if (rover.previous != null) System.out.println("Cannot find " + dep + " from " + rover.previous.dependency); else System.out.println("Cannot find " + dep + " from top"); // boolean include = false; // if (dep.scope == Scope.compile) { // include = true; // } else if (dep.scope == Scope.test) { // include = rover.previous == null && (action == Action.compile || action == Action.test); // } else if (dep.scope == Scope.runtime) { // include = action == Action.run; // } // if (include) { // Pom sub = maven.getPom(groupId, artifactId, version, urls); // if (!result.contains(sub)) { // result.add(sub); // for (Dependency subd : sub.dependencies) { // queue.add(new Rover(rover, subd)); // } } } } return result; } protected String replace(String in) { System.out.println("replace: " + in); if (in == null) return "null"; in = in.trim(); if ("${pom.version}".equals(in) || "${version}".equals(in) || "${project.version}".equals(in)) return version; if ("${basedir}".equals(in)) return pomFile.getParentFile().getAbsolutePath(); if ("${pom.name}".equals(in) || "${project.name}".equals(in)) return name; if ("${pom.artifactId}".equals(in) || "${project.artifactId}".equals(in)) return artifactId; if ("${pom.groupId}".equals(in) || "${project.groupId}".equals(in)) return groupId; return in; } public String toString() { return groupId + "+" + artifactId + "-" + version; } public File getLibrary(Scope action, URI... repositories) throws Exception { MavenEntry entry = maven.getEntry(this); File file = new File(entry.dir, action + ".lib"); if (file.isFile() && file.lastModified() >= getPomFile().lastModified()) return file; file.delete(); Writer writer = new FileWriter(file); doEntry(writer, this); try { for (Pom dep : getDependencies(action, repositories)) { doEntry(writer, dep); } } finally { writer.close(); } return file; } /** * @param writer * @param dep * @throws IOException * @throws Exception */ private void doEntry(Writer writer, Pom dep) throws IOException, Exception { writer.append(dep.getGroupId()); writer.append("+"); writer.append(dep.getArtifactId()); writer.append(";version=\""); writer.append(dep.getVersion()); writer.append("\"\n"); } public File getPomFile() { return pomFile; } public String getName() { return name; } public abstract java.io.File getArtifact() throws Exception; } bnd-1.50.0/biz.aQute.bndlib/src/aQute/bnd/maven/support/ProjectPom.java0000644000175000017500000001306311656076535025530 0ustar drazzibdrazzibpackage aQute.bnd.maven.support; import java.io.*; import java.net.*; import java.util.*; import java.util.regex.*; import javax.xml.xpath.*; import org.w3c.dom.*; import aQute.lib.io.*; public class ProjectPom extends Pom { final List repositories = new ArrayList(); final Properties properties = new Properties(); String packaging; String url; ProjectPom(Maven maven, File pomFile) throws Exception { super(maven, pomFile, pomFile.toURI()); } @Override protected void parse(Document doc, XPath xp) throws Exception { packaging = xp.evaluate("project/packaging", doc); url = xp.evaluate("project/url", doc); Node parent = (Node) xp.evaluate("project/parent", doc, XPathConstants.NODE); if (parent != null && parent.hasChildNodes()) { File parentFile = IO.getFile(getPomFile().getParentFile(), "../pom.xml"); String parentGroupId = xp.evaluate("groupId", parent).trim(); String parentArtifactId = xp.evaluate("artifactId", parent).trim(); String parentVersion = xp.evaluate("version", parent).trim(); String parentPath = xp.evaluate("relativePath", parent).trim(); if (parentPath != null && parentPath.length()!=0) { parentFile = IO.getFile(getPomFile().getParentFile(), parentPath); } if (parentFile.isFile()) { ProjectPom parentPom = new ProjectPom(maven, parentFile); parentPom.parse(); dependencies.addAll(parentPom.dependencies); for ( Enumeration e = parentPom.properties.propertyNames(); e.hasMoreElements(); ) { String key = (String) e.nextElement(); if ( ! properties.contains(key)) properties.put(key, parentPom.properties.get(key)); } repositories.addAll(parentPom.repositories); setNames(parentPom); } else { // This seems to be a bit bizarre, extending an external pom? CachedPom parentPom = maven.getPom(parentGroupId, parentArtifactId, parentVersion); dependencies.addAll(parentPom.dependencies); setNames(parentPom); } } NodeList propNodes = (NodeList) xp.evaluate("project/properties/*", doc, XPathConstants.NODESET); for (int i = 0; i < propNodes.getLength(); i++) { Node node = propNodes.item(i); String key = node.getNodeName(); String value = node.getTextContent(); if ( key == null || key.length()==0) throw new IllegalArgumentException("Pom has an empty or null key"); if ( value == null || value.length()==0) throw new IllegalArgumentException("Pom has an empty or null value for property " + key); properties.setProperty(key, value.trim()); } NodeList repos = (NodeList) xp.evaluate("project/repositories/repository/url", doc, XPathConstants.NODESET); for (int i = 0; i < repos.getLength(); i++) { Node node = repos.item(i); String URIString = node.getTextContent().trim(); URI uri = new URI(URIString); if ( uri.getScheme() ==null ) uri = IO.getFile(pomFile.getParentFile(),URIString).toURI(); repositories.add(uri); } super.parse(doc, xp); } // private void print(Node node, String indent) { // System.out.print(indent); // System.out.println(node.getNodeName()); // Node rover = node.getFirstChild(); // while ( rover != null) { // print( rover, indent+" "); // rover = rover.getNextSibling(); // } // } /** * @param parentArtifactId * @param parentGroupId * @param parentVersion * @throws Exception */ private void setNames(Pom pom) throws Exception { if (artifactId == null || artifactId.length()==0) artifactId = pom.getArtifactId(); if (groupId == null || groupId.length()==0) groupId = pom.getGroupId(); if (version == null || version.length()==0) version = pom.getVersion(); if ( description == null ) description = pom.getDescription(); else description = pom.getDescription() + "\n" + description; } class Rover { public Rover(Rover rover, Dependency d) { this.previous = rover; this.dependency = d; } final Rover previous; final Dependency dependency; public boolean excludes(String name) { return dependency.exclusions.contains(name) && previous != null && previous.excludes(name); } } public Set getDependencies(Scope action) throws Exception { return getDependencies(action, repositories.toArray(new URI[0])); } // Match any macros final static Pattern MACRO = Pattern.compile("(\\$\\{\\s*([^}\\s]+)\\s*\\})"); protected String replace(String in) { System.out.println("Replce: " + in); if ( in == null) { System.out.println("null??"); } Matcher matcher = MACRO.matcher(in); int last = 0; StringBuilder sb = new StringBuilder(); while (matcher.find()) { int n = matcher.start(); sb.append( in, last, n); String replacement = get(matcher.group(2)); if ( replacement == null ) sb.append( matcher.group(1)); else sb.append( replacement ); last = matcher.end(); } if ( last == 0) return in; sb.append( in, last, in.length()); return sb.toString(); } private String get(String key) { if (key.equals("pom.artifactId")) return artifactId; if (key.equals("pom.groupId")) return groupId; if (key.equals("pom.version")) return version; if (key.equals("pom.name")) return name; String prop = properties.getProperty(key); if ( prop != null ) return prop; return System.getProperty(key); } public Properties getProperties() { return properties; } public String getPackaging() { return packaging; } public String getUrl() { return url; } public String getProperty(String key) { String s = properties.getProperty(key); return replace(s); } @Override public File getArtifact() throws Exception { return null; } } bnd-1.50.0/biz.aQute.bndlib/src/aQute/bnd/maven/support/Repo.java0000644000175000017500000000007111656076535024346 0ustar drazzibdrazzibpackage aQute.bnd.maven.support; public class Repo { } bnd-1.50.0/biz.aQute.bndlib/src/aQute/bnd/maven/support/Maven.java0000644000175000017500000000502111656076535024507 0ustar drazzibdrazzibpackage aQute.bnd.maven.support; import java.io.*; import java.net.*; import java.util.*; import java.util.concurrent.*; import java.util.regex.*; /* http://repository.springsource.com/maven/bundles/external/org/apache/coyote/com.springsource.org.apache.coyote/6.0.24/com.springsource.org.apache.coyote-6.0.24.pom http://repository.springsource.com/maven/bundles/external/org/apache/coyote/com.springsource.org.apache.coyote/6.0.24/com.springsource.org.apache.coyote-6.0.24.pom */ public class Maven { final File userHome = new File(System.getProperty("user.home")); final Map entries = new ConcurrentHashMap(); final static String[] ALGORITHMS = { "md5", "sha1" }; boolean usecache = false; final Executor executor; File m2 = new File(userHome, ".m2"); File repository = new File(m2, "repository"); public Maven(Executor executor) { if ( executor == null) this.executor = Executors.newCachedThreadPool(); else this.executor = executor; } //http://repo1.maven.org/maven2/junit/junit/maven-metadata.xml static Pattern MAVEN_RANGE = Pattern.compile("(\\[|\\()(.+)(,(.+))(\\]|\\))"); public CachedPom getPom(String groupId, String artifactId, String version, URI... extra) throws Exception { MavenEntry entry = getEntry(groupId, artifactId, version); return entry.getPom(extra); } /** * @param groupId * @param artifactId * @param version * @param extra * @return * @throws Exception */ public MavenEntry getEntry(String groupId, String artifactId, String version) throws Exception { String path = path(groupId, artifactId, version); MavenEntry entry; synchronized (entries) { entry = entries.get(path); if (entry != null) return entry; entry = new MavenEntry(this, path); entries.put(path, entry); } return entry; } private String path(String groupId, String artifactId, String version) { return groupId.replace('.', '/') + '/' + artifactId + '/' + version + "/" + artifactId + "-" + version; } public void schedule(Runnable runnable) { if (executor == null) runnable.run(); else executor.execute(runnable); } public ProjectPom createProjectModel(File file) throws Exception { ProjectPom pom = new ProjectPom(this, file); pom.parse(); return pom; } public MavenEntry getEntry(Pom pom) throws Exception { return getEntry(pom.getGroupId(), pom.getArtifactId(), pom.getVersion()); } public void setM2(File dir) { this.m2 = dir; this.repository = new File(dir,"repository"); } } bnd-1.50.0/biz.aQute.bndlib/src/aQute/bnd/maven/support/MavenRemoteRepository.java0000644000175000017500000000564111656076535027773 0ustar drazzibdrazzibpackage aQute.bnd.maven.support; import java.io.*; import java.net.*; import java.util.*; import aQute.bnd.service.*; import aQute.lib.io.*; import aQute.lib.osgi.*; import aQute.libg.reporter.*; import aQute.libg.version.*; public class MavenRemoteRepository implements RepositoryPlugin, RegistryPlugin, Plugin { Reporter reporter; URI[] repositories; Registry registry; Maven maven; public File[] get(String bsn, String range) throws Exception { File f = get(bsn, range, Strategy.HIGHEST, null); if (f == null) return null; return new File[] { f }; } public File get(String bsn, String version, Strategy strategy, Map properties) throws Exception { String groupId = null; if (properties != null) groupId = properties.get("groupId"); if (groupId == null) { int n = bsn.indexOf('+'); if ( n < 0) return null; groupId = bsn.substring(0,n); bsn = bsn.substring(n+1); } String artifactId = bsn; if (version == null) { if (reporter != null) reporter.error("Maven dependency version not set for %s - %s", groupId, artifactId); return null; } CachedPom pom = getMaven().getPom(groupId, artifactId, version, repositories); String value = properties == null ? null : properties.get("scope"); if (value == null) return pom.getArtifact(); Pom.Scope action = null; try { action = Pom.Scope.valueOf(value); return pom.getLibrary(action, repositories); } catch (Exception e) { return pom.getArtifact(); } } public Maven getMaven() { if ( maven != null) return maven; maven = registry.getPlugin(Maven.class); return maven; } public boolean canWrite() { return false; } public File put(Jar jar) throws Exception { throw new UnsupportedOperationException("cannot do put"); } public List list(String regex) throws Exception { throw new UnsupportedOperationException("cannot do list"); } public List versions(String bsn) throws Exception { throw new UnsupportedOperationException("cannot do versions"); } public String getName() { return "maven"; } public void setRepositories(URI... urls) { repositories = urls; } public void setProperties(Map map) { String repoString = map.get("repositories"); if (repoString != null) { String[] repos = repoString.split("\\s*,\\s*"); repositories = new URI[repos.length]; int n = 0; for (String repo : repos) { try { URI uri = new URI(repo); if ( !uri.isAbsolute()) uri = IO.getFile( new File(""),repo).toURI(); repositories[n++] = uri; } catch (Exception e) { if (reporter != null) reporter.error("Invalid repository %s for maven plugin, %s", repo, e); } } } } public void setReporter(Reporter reporter) { this.reporter = reporter; } public void setRegistry(Registry registry) { this.registry = registry; } public void setMaven(Maven maven) { this.maven = maven; } } bnd-1.50.0/biz.aQute.bndlib/src/aQute/bnd/maven/support/CachedPom.java0000644000175000017500000000056411656076535025273 0ustar drazzibdrazzibpackage aQute.bnd.maven.support; import java.io.*; import java.net.*; public class CachedPom extends Pom { final MavenEntry maven; CachedPom(MavenEntry mavenEntry, URI repo) throws Exception { super(mavenEntry.maven, mavenEntry.getPomFile(), repo); this.maven = mavenEntry; } public File getArtifact() throws Exception { return maven.getArtifact(); } } bnd-1.50.0/biz.aQute.bndlib/src/aQute/bnd/maven/MavenDeploy.java0000644000175000017500000001306311656076535024155 0ustar drazzibdrazzibpackage aQute.bnd.maven; import java.io.*; import java.util.*; import java.util.jar.*; import aQute.bnd.build.*; import aQute.bnd.service.*; import aQute.lib.osgi.*; import aQute.libg.command.*; import aQute.libg.reporter.*; public class MavenDeploy implements Deploy, Plugin { String repository; String url; String homedir; String keyname; String passphrase; Reporter reporter; public void setProperties(Map map) { repository = map.get("repository"); url = map.get("url"); passphrase = map.get("passphrase"); homedir = map.get("homedir"); keyname = map.get("keyname"); if (url == null) throw new IllegalArgumentException("MavenDeploy plugin must get a repository URL"); if (repository == null) throw new IllegalArgumentException("MavenDeploy plugin must get a repository name"); } public void setReporter(Reporter processor) { this.reporter = processor; } /** */ public boolean deploy(Project project, Jar original) throws Exception { Map> deploy = project.parseHeader(project .getProperty(Constants.DEPLOY)); Map maven = deploy.get(repository); if (maven == null) return false; // we're not playing for this bundle project.progress("deploying %s to Maven repo: %s", original, repository); File target = project.getTarget(); File tmp = Processor.getFile(target, repository); tmp.mkdirs(); Manifest manifest = original.getManifest(); if (manifest == null) project.error("Jar has no manifest: %s", original); else { project.progress("Writing pom.xml"); PomResource pom = new PomResource(manifest); pom.setProperties(maven); File pomFile = write(tmp, pom, "pom.xml"); Jar main = new Jar("main"); Jar src = new Jar("src"); try { split(original, main, src); Map> exports = project.parseHeader(manifest .getMainAttributes().getValue(Constants.EXPORT_PACKAGE)); File jdoc = new File(tmp, "jdoc"); jdoc.mkdirs(); project.progress("Generating Javadoc for: " + exports.keySet()); Jar javadoc = javadoc(jdoc, project, exports.keySet()); project.progress("Writing javadoc jar"); File javadocFile = write(tmp, new JarResource(javadoc), "javadoc.jar"); project.progress("Writing main file"); File mainFile = write(tmp, new JarResource(main), "main.jar"); project.progress("Writing sources file"); File srcFile = write(tmp, new JarResource(main), "src.jar"); project.progress("Deploying main file"); maven_gpg_sign_and_deploy(project, mainFile, null, pomFile); project.progress("Deploying main sources file"); maven_gpg_sign_and_deploy(project, srcFile, "sources", null); project.progress("Deploying main javadoc file"); maven_gpg_sign_and_deploy(project, javadocFile, "javadoc", null); } finally { main.close(); src.close(); } } return true; } private void split(Jar original, Jar main, Jar src) { for (Map.Entry e : original.getResources().entrySet()) { String path = e.getKey(); if (path.startsWith("OSGI-OPT/src/")) { src.putResource(path.substring("OSGI-OPT/src/".length()), e.getValue()); } else { main.putResource(path, e.getValue()); } } } // gpg:sign-and-deploy-file \ // -Durl=http://oss.sonatype.org/service/local/staging/deploy/maven2 // \ // -DrepositoryId=sonatype-nexus-staging \ // -DupdateReleaseInfo=true \ // -DpomFile=pom.xml \ // -Dfile=/Ws/bnd/biz.aQute.bndlib/tmp/biz.aQute.bndlib.jar \ // -Dpassphrase=a1k3v3t5x3 private void maven_gpg_sign_and_deploy(Project b, File file, String classifier, File pomFile) throws Exception { Command command = new Command(); command.setTrace(); command.add(b.getProperty("mvn", "mvn")); command.add("gpg:sign-and-deploy-file", "-DreleaseInfo=true", "-DpomFile=pom.xml"); command.add("-Dfile=" + file.getAbsolutePath()); command.add("-DrepositoryId=" + repository); command.add("-Durl=" + url); optional(command, "passphrase", passphrase); optional(command, "keyname", keyname); optional(command, "homedir", homedir); optional(command, "classifier", classifier); optional(command, "pomFile", pomFile == null ? null : pomFile.getAbsolutePath()); StringBuffer stdout = new StringBuffer(); StringBuffer stderr = new StringBuffer(); int result = command.execute(stdout, stderr); if (result != 0) { b.error("Maven deploy to %s failed to sign and transfer %s because %s", repository, file, "" + stdout + stderr); } } private void optional(Command command, String key, String value) { if (value == null) return; command.add("-D=" + value); } private Jar javadoc(File tmp, Project b, Set exports) throws Exception { Command command = new Command(); command.add(b.getProperty("javadoc", "javadoc")); command.add("-d"); command.add(tmp.getAbsolutePath()); command.add("-sourcepath"); command.add( Processor.join(b.getSourcePath(),File.pathSeparator)); for (String packageName : exports) { command.add(packageName); } StringBuffer out = new StringBuffer(); StringBuffer err = new StringBuffer(); Command c = new Command(); c.setTrace(); int result = c.execute(out, err); if (result == 0) { Jar jar = new Jar(tmp); b.addClose(jar); return jar; } b.error("Error during execution of javadoc command: %s / %s", out, err); return null; } private File write(File base, Resource r, String fileName) throws Exception { File f = Processor.getFile(base, fileName); OutputStream out = new FileOutputStream(f); try { r.write(out); } finally { out.close(); } return f; } } bnd-1.50.0/biz.aQute.bndlib/src/aQute/bnd/maven/MavenDependencyGraph.java0000644000175000017500000000710111656076535025755 0ustar drazzibdrazzibpackage aQute.bnd.maven; import java.net.*; import java.util.*; import javax.xml.parsers.*; import javax.xml.xpath.*; import org.w3c.dom.*; public class MavenDependencyGraph { final static DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); final static XPathFactory xpathFactory = XPathFactory.newInstance(); final List dependencies = new ArrayList(); final List repositories = new ArrayList(); final XPath xpath = xpathFactory.newXPath(); final Map cache = new HashMap(); Artifact root; enum Scope { COMPILE, RUNTIME, TEST, PROVIDED, SYSTEM, IMPORT, }; public class Artifact { String groupId; String artifactId; String version; Scope scope = Scope.COMPILE; boolean optional; String type; URL url; List dependencies = new ArrayList(); public Artifact(URL url) throws Exception { if (url != null) { this.url = url; DocumentBuilder db = docFactory.newDocumentBuilder(); Document doc = db.parse(url.toString()); Node node = (Node) xpath.evaluate("/project", doc, XPathConstants.NODE); groupId = xpath.evaluate("groupId", node); artifactId = xpath.evaluate("artifactId", node); version = xpath.evaluate("version", node); type = xpath.evaluate("type", node); optional = (Boolean) xpath.evaluate("optinal", node, XPathConstants.BOOLEAN); String scope = xpath.evaluate("scope", node); if (scope != null && scope.length() > 0) { this.scope = Scope.valueOf(scope.toUpperCase()); } NodeList evaluate = (NodeList) xpath.evaluate("//dependencies/dependency", doc, XPathConstants.NODESET); for (int i = 0; i < evaluate.getLength(); i++) { Node childNode = evaluate.item(i); Artifact artifact = getArtifact(xpath.evaluate("groupId", childNode), xpath .evaluate("artifactId", childNode), xpath.evaluate("version", childNode)); add(artifact); } } } public void add(Artifact artifact) { dependencies.add(artifact); } public String toString() { return groupId + "." + artifactId + "-" + version + "[" + scope + "," + optional + "]"; } public String getPath() throws URISyntaxException { return groupId.replace('.', '/') + "/" + artifactId + "/" + version + "/" + artifactId + "-" + version; } } public void addRepository(URL repository) { repositories.add(repository); } /** * @param xp * @param node * @param d * @throws XPathExpressionException */ public Artifact getArtifact(String groupId, String artifactId, String version) { for (URL repository : repositories) { String path = getPath(repository.toString(), groupId, artifactId, version); try { URL url = new URL(path + ".pom"); if (cache.containsKey(url)) { return cache.get(url); } else { return new Artifact(url); } } catch (Exception e) { System.err.println("Failed to get " + artifactId + " from " + repository); } } return null; } private String getPath(String path, String groupId, String artifactId, String version) { StringBuilder sb = new StringBuilder(); sb.append(path); if (!path.endsWith("/")) sb.append("/"); sb.append(groupId.replace('.', '/')); sb.append('/'); sb.append(artifactId); sb.append('/'); sb.append(version); sb.append('/'); sb.append(artifactId); sb.append('-'); sb.append(version); return null; } public void addArtifact( Artifact artifact ) throws Exception { if ( root == null) root = new Artifact(null); root.add(artifact); } } bnd-1.50.0/biz.aQute.bndlib/src/aQute/bnd/maven/PomResource.java0000644000175000017500000001142411656076535024174 0ustar drazzibdrazzibpackage aQute.bnd.maven; import java.io.*; import java.util.*; import java.util.jar.*; import java.util.regex.*; import aQute.lib.osgi.*; import aQute.lib.tag.*; public class PomResource extends WriteResource { final Manifest manifest; private Map scm; final static Pattern NAME_URL = Pattern.compile("(.*)(http://.*)"); public PomResource(Manifest manifest) { this.manifest = manifest; } @Override public long lastModified() { return 0; } @Override public void write(OutputStream out) throws IOException { PrintWriter ps = new PrintWriter(out); String name = manifest.getMainAttributes().getValue(Analyzer.BUNDLE_NAME); String description = manifest.getMainAttributes().getValue(Constants.BUNDLE_DESCRIPTION); String docUrl = manifest.getMainAttributes().getValue(Constants.BUNDLE_DOCURL); String version = manifest.getMainAttributes().getValue(Constants.BUNDLE_VERSION); String bundleVendor = manifest.getMainAttributes().getValue(Constants.BUNDLE_VENDOR); String bsn = manifest.getMainAttributes().getValue(Constants.BUNDLE_SYMBOLICNAME); String licenses = manifest.getMainAttributes().getValue(Constants.BUNDLE_LICENSE); if (bsn == null) { throw new RuntimeException("Cannot create POM unless bsn is set"); } bsn = bsn.trim(); int n = bsn.lastIndexOf('.'); if (n <= 0) throw new RuntimeException( "Can not create POM unless Bundle-SymbolicName contains a . to separate group and artifact id"); if (version == null) version = "0"; String groupId = bsn.substring(0, n); String artifactId = bsn.substring(n + 1); n = artifactId.indexOf(';'); if (n > 0) artifactId = artifactId.substring(0, n).trim(); Tag project = new Tag("project"); project.addAttribute("xmlns", "http://maven.apache.org/POM/4.0.0"); project.addAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance"); project.addAttribute("xmlns:xsi", ""); project.addAttribute("xsi:schemaLocation", "http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"); project.addContent(new Tag("modelVersion").addContent("4.0.0")); project.addContent(new Tag("groupId").addContent(groupId)); project.addContent(new Tag("artifactId").addContent(artifactId)); project.addContent(new Tag("version").addContent(version)); if (description != null) { new Tag(project, "description").addContent(description); } if (name != null) { new Tag(project, "name").addContent(name); } if (docUrl != null) { new Tag(project, "url").addContent(docUrl); } if (scm != null) { Tag scm = new Tag(project, "scm"); for (Map.Entry e : this.scm.entrySet()) { new Tag(scm, e.getKey()).addContent(e.getValue()); } } if (bundleVendor != null) { Matcher m = NAME_URL.matcher(bundleVendor); String namePart = bundleVendor; String urlPart = null; if (m.matches()) { namePart = m.group(1); urlPart = m.group(2); } Tag organization = new Tag(project, "organization"); new Tag(organization, "name").addContent(namePart.trim()); if (urlPart != null) { new Tag(organization, "url").addContent(urlPart.trim()); } } if (licenses != null) { Tag ls = new Tag(project, "licenses"); Map> map = Processor.parseHeader(licenses, null); for (Iterator>> e = map.entrySet().iterator(); e .hasNext();) { // Bundle-License: // http://www.opensource.org/licenses/apache2.0.php; \ // description="${Bundle-Copyright}"; \ // link=LICENSE // //   //    This material is licensed under the Apache // Software License, Version 2.0 //    http://www.apache.org/licenses/LICENSE-2.0 //    repo //     Map.Entry> entry = e.next(); Tag l = new Tag(ls, "license"); Map values = entry.getValue(); String url = entry.getKey(); if (values.containsKey("description")) tagFromMap(l, values, "description", "name", url); else tagFromMap(l, values, "name", "name", url); tagFromMap(l, values, "url", "url", url); tagFromMap(l, values, "distribution", "distribution", "repo"); } } project.print(0, ps); ps.flush(); } /** * Utility function to print a tag from a map * * @param ps * @param values * @param string * @param tag * @param object */ private Tag tagFromMap(Tag parent, Map values, String string, String tag, String object) { String value = (String) values.get(string); if (value == null) value = object; if (value == null) return parent; new Tag(parent, tag).addContent(value.trim()); return parent; } public void setProperties(Map scm) { this.scm = scm; } } bnd-1.50.0/biz.aQute.bndlib/src/aQute/bnd/maven/MavenRepository.java0000644000175000017500000001145011656076535025076 0ustar drazzibdrazzibpackage aQute.bnd.maven; import java.io.*; import java.util.*; import java.util.regex.*; import aQute.bnd.service.*; import aQute.lib.osgi.*; import aQute.libg.reporter.*; import aQute.libg.version.*; public class MavenRepository implements RepositoryPlugin, Plugin, BsnToMavenPath { public static String NAME = "name"; File root; Reporter reporter; String name; public String toString() { return "maven:" + root; } public boolean canWrite() { return false; } public File[] get(String bsn, String version) throws Exception { VersionRange range = new VersionRange("0"); if (version != null) range = new VersionRange(version); List plugins = ((Processor) reporter).getPlugins(BsnToMavenPath.class); if ( plugins.isEmpty()) plugins.add(this); for (BsnToMavenPath cvr : plugins) { String[] paths = cvr.getGroupAndArtifact(bsn); if (paths != null) { File[] files = find(paths[0], paths[1], range); if (files != null) return files; } } reporter.trace("Cannot find in maven: %s-%s", bsn, version); return null; } File[] find(String groupId, String artifactId, VersionRange range) { String path = groupId.replace(".", "/"); File vsdir = Processor.getFile(root, path); if (!vsdir.isDirectory()) return null; vsdir = Processor.getFile(vsdir, artifactId); List result = new ArrayList(); if (vsdir.isDirectory()) { String versions[] = vsdir.list(); for (String v : versions) { String vv = Analyzer.cleanupVersion(v); if (Verifier.isVersion(vv)) { Version vvv = new Version(vv); if (range.includes(vvv)) { File file = Processor.getFile(vsdir, v + "/" + artifactId + "-" + v + ".jar"); if (file.isFile()) result.add(file); else reporter.warning("Expected maven entry was not a valid file %s ", file); } } else { reporter .warning( "Expected a version directory in maven: dir=%s raw-version=%s cleaned-up-version=%s", vsdir, vv, v); } } } else return null; return result.toArray(new File[result.size()]); } public List list(String regex) { List bsns = new ArrayList(); Pattern match = Pattern.compile(".*"); if (regex != null) match = Pattern.compile(regex); find(bsns, match, root, ""); return bsns; } void find(List bsns, Pattern pattern, File base, String name) { if (base.isDirectory()) { String list[] = base.list(); boolean found = false; for (String entry : list) { char c = entry.charAt(0); if (c >= '0' && c <= '9') { if (pattern.matcher(name).matches()) found = true; } else { String nextName = entry; if (name.length() != 0) nextName = name + "." + entry; File next = Processor.getFile(base, entry); find(bsns, pattern, next, nextName); } } if (found) bsns.add(name); } } public File put(Jar jar) throws Exception { throw new IllegalStateException("Maven does not support the put command"); } public List versions(String bsn) throws Exception { File files[] = get( bsn, null); List versions = new ArrayList(); for ( File f : files ) { Version v = new Version( f.getParentFile().getName()); versions.add(v); } return versions; } public void setProperties(Map map) { File home = new File(""); String root = map.get("root"); if (root == null) { home = new File( System.getProperty("user.home") ); this.root = Processor.getFile(home , ".m2/repository").getAbsoluteFile(); } else this.root = Processor.getFile(home, root).getAbsoluteFile(); if (!this.root.isDirectory()) { reporter.error("Maven repository did not get a proper URL to the repository %s", root); } name = (String) map.get(NAME); } public void setReporter(Reporter processor) { this.reporter = processor; } public String[] getGroupAndArtifact(String bsn) { String groupId; String artifactId; int n = bsn.indexOf('.'); while ( n > 0 ) { artifactId = bsn.substring(n+1); groupId = bsn.substring(0,n); File gdir = new File(root, groupId.replace('.',File.separatorChar)).getAbsoluteFile(); File adir = new File( gdir, artifactId).getAbsoluteFile(); if ( adir.isDirectory() ) return new String[] {groupId, artifactId}; n = bsn.indexOf('.',n+1); } return null; } public String getName() { if (name == null) { return toString(); } return name; } public File get(String bsn, String range, Strategy strategy, Map properties) throws Exception { File[] files = get(bsn, range); if (files.length >= 0) { switch (strategy) { case LOWEST: return files[0]; case HIGHEST: return files[files.length - 1]; } } return null; } public void setRoot( File f ) { root = f; } } bnd-1.50.0/biz.aQute.bndlib/src/aQute/bnd/maven/PomFromManifest.java0000644000175000017500000001561211656076535025002 0ustar drazzibdrazzibpackage aQute.bnd.maven; import java.io.*; import java.util.*; import java.util.jar.*; import java.util.regex.*; import aQute.lib.osgi.*; import aQute.lib.tag.*; import aQute.libg.version.*; public class PomFromManifest extends WriteResource { final Manifest manifest; private List scm = new ArrayList(); private List developers = new ArrayList(); final static Pattern NAME_URL = Pattern.compile("(.*)(http://.*)"); String xbsn; String xversion; String xgroupId; String xartifactId; private String projectURL; public String getBsn() { if (xbsn == null) xbsn = manifest.getMainAttributes().getValue(Constants.BUNDLE_SYMBOLICNAME); if (xbsn == null) throw new RuntimeException("Cannot create POM unless bsn is set"); xbsn = xbsn.trim(); int n = xbsn.lastIndexOf('.'); if (n < 0) { n = xbsn.length(); xbsn = xbsn + "." + xbsn; } if (xgroupId == null) xgroupId = xbsn.substring(0, n); if (xartifactId == null) { xartifactId = xbsn.substring(n + 1); n = xartifactId.indexOf(';'); if (n > 0) xartifactId = xartifactId.substring(0, n).trim(); } return xbsn; } public String getGroupId() { getBsn(); return xgroupId; } public String getArtifactId() { getBsn(); return xartifactId; } public Version getVersion() { if (xversion != null) return new Version(xversion); String version = manifest.getMainAttributes().getValue(Constants.BUNDLE_VERSION); Version v = new Version(version); return new Version(v.getMajor(), v.getMinor(), v.getMicro()); } public PomFromManifest(Manifest manifest) { this.manifest = manifest; } @Override public long lastModified() { return 0; } @Override public void write(OutputStream out) throws IOException { PrintWriter ps = new PrintWriter(out); String name = manifest.getMainAttributes().getValue(Analyzer.BUNDLE_NAME); String description = manifest.getMainAttributes().getValue(Constants.BUNDLE_DESCRIPTION); String docUrl = manifest.getMainAttributes().getValue(Constants.BUNDLE_DOCURL); String bundleVendor = manifest.getMainAttributes().getValue(Constants.BUNDLE_VENDOR); String licenses = manifest.getMainAttributes().getValue(Constants.BUNDLE_LICENSE); Tag project = new Tag("project"); project.addAttribute("xmlns", "http://maven.apache.org/POM/4.0.0"); project.addAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance"); project.addAttribute("xsi:schemaLocation", "http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"); project.addContent(new Tag("modelVersion").addContent("4.0.0")); project.addContent(new Tag("groupId").addContent(getGroupId())); project.addContent(new Tag("artifactId").addContent(getArtifactId())); project.addContent(new Tag("version").addContent(getVersion().toString())); if (description != null) { new Tag(project, "description").addContent(description); } if (name != null) { new Tag(project, "name").addContent(name); } if (projectURL != null) new Tag(project, "url").addContent(projectURL); else if (docUrl != null) { new Tag(project, "url").addContent(docUrl); } else new Tag(project, "url").addContent("http://no-url"); String scmheader = manifest.getMainAttributes().getValue("Bundle-SCM"); if (scmheader != null) scm.add(scmheader); Tag scmtag = new Tag(project, "scm"); if (scm != null && !scm.isEmpty()) { for (String cm : this.scm) { new Tag(scmtag, "url").addContent(cm); new Tag(scmtag, "connection").addContent(cm); new Tag(scmtag, "developerConnection").addContent(cm); } } else { new Tag(scmtag, "url").addContent("private"); new Tag(scmtag, "connection").addContent("private"); new Tag(scmtag, "developerConnection").addContent("private"); } if (bundleVendor != null) { Matcher m = NAME_URL.matcher(bundleVendor); String namePart = bundleVendor; String urlPart = this.projectURL; if (m.matches()) { namePart = m.group(1); urlPart = m.group(2); } Tag organization = new Tag(project, "organization"); new Tag(organization, "name").addContent(namePart.trim()); if (urlPart != null) { new Tag(organization, "url").addContent(urlPart.trim()); } } if (!developers.isEmpty()) { Tag d = new Tag(project, "developers"); for (String email : developers) { String id = email; String xname = email; String organization = null; Matcher m = Pattern.compile("([^@]+)@([\\d\\w\\-_\\.]+)\\.([\\d\\w\\-_\\.]+)") .matcher(email); if (m.matches()) { xname = m.group(1); organization = m.group(2); } Tag developer = new Tag(d, "developer"); new Tag(developer, "id").addContent(id); new Tag(developer, "name").addContent(xname); new Tag(developer, "email").addContent(email); if (organization != null) new Tag(developer, "organization").addContent(organization); } } if (licenses != null) { Tag ls = new Tag(project, "licenses"); Map> map = Processor.parseHeader(licenses, null); for (Iterator>> e = map.entrySet().iterator(); e .hasNext();) { // Bundle-License: // http://www.opensource.org/licenses/apache2.0.php; \ // description="${Bundle-Copyright}"; \ // link=LICENSE // //   //    This material is licensed under the Apache // Software License, Version 2.0 //    http://www.apache.org/licenses/LICENSE-2.0 //    repo //     Map.Entry> entry = e.next(); Tag l = new Tag(ls, "license"); Map values = entry.getValue(); String url = entry.getKey(); if (values.containsKey("description")) tagFromMap(l, values, "description", "name", url); else tagFromMap(l, values, "name", "name", url); tagFromMap(l, values, "url", "url", url); tagFromMap(l, values, "distribution", "distribution", "repo"); } } project.print(0, ps); ps.flush(); } /** * Utility function to print a tag from a map * * @param ps * @param values * @param string * @param tag * @param object */ private Tag tagFromMap(Tag parent, Map values, String string, String tag, String object) { String value = (String) values.get(string); if (value == null) value = object; if (value == null) return parent; new Tag(parent, tag).addContent(value.trim()); return parent; } public void setSCM(String scm) { this.scm.add(scm); } public void setURL(String url) { this.projectURL = url; } public void setBsn(String bsn) { this.xbsn = bsn; } public void addDeveloper(String email) { this.developers.add(email); } public void setVersion(String version) { this.xversion = version; } public void setArtifact(String artifact) { this.xartifactId = artifact; } public void setGroup(String group) { this.xgroupId = group; } } bnd-1.50.0/biz.aQute.bndlib/src/aQute/bnd/maven/PomParser.java0000644000175000017500000001016211656076535023637 0ustar drazzibdrazzibpackage aQute.bnd.maven; import java.io.*; import java.util.*; import javax.xml.parsers.*; import javax.xml.xpath.*; import org.w3c.dom.*; import aQute.lib.io.*; import aQute.lib.osgi.*; /** * Provides a way to parse a maven pom as properties. * * This provides most of the maven elements as properties. It also * provides pom.scope.[compile|test|runtime|provided|system] properties * that can be appended to the build and run path. That is, they are * in the correct format for this. */ public class PomParser extends Processor { static DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); static XPathFactory xpathf = XPathFactory.newInstance(); static Set multiple = new HashSet(); static Set skip = new HashSet(); static { dbf.setNamespaceAware(false); // Set all elements that need enumeration of their elements // these will not use the name of the subelement but instead // they use an index from 0..n multiple.add("mailingLists"); multiple.add("pluginRepositories"); multiple.add("repositories"); multiple.add("resources"); multiple.add("executions"); multiple.add("goals"); multiple.add("includes"); multiple.add("excludes"); // These properties are not very useful and // pollute the property space. skip.add("plugins"); skip.add("dependencies"); skip.add("reporting"); skip.add("extensions"); } public Properties getProperties(File pom) throws Exception { DocumentBuilder db = dbf.newDocumentBuilder(); XPath xpath = xpathf.newXPath(); pom = pom.getAbsoluteFile(); Document doc = db.parse(pom); Properties p = new Properties(); // Check if there is a parent pom String relativePath = xpath.evaluate("project/parent/relativePath", doc); if (relativePath != null && relativePath.length()!=0) { File parentPom = IO.getFile(pom.getParentFile(), relativePath); if (parentPom.isFile()) { Properties parentProps = getProperties(parentPom); p.putAll(parentProps); } else { error("Parent pom for %s is not an existing file (could be directory): %s", pom, parentPom); } } Element e = doc.getDocumentElement(); traverse("pom", e, p); String scopes[] = { "provided", "runtime", "test", "system" }; NodeList set = (NodeList) xpath.evaluate("//dependency[not(scope) or scope='compile']", doc, XPathConstants.NODESET); if (set.getLength() != 0) p.put("pom.scope.compile", toBsn(set)); for (String scope : scopes) { set = (NodeList) xpath.evaluate("//dependency[scope='" + scope + "']", doc, XPathConstants.NODESET); if (set.getLength() != 0) p.put("pom.scope." + scope, toBsn(set)); } return p; } private Object toBsn(NodeList set) throws XPathExpressionException { XPath xpath = xpathf.newXPath(); StringBuilder sb = new StringBuilder(); String del = ""; for (int i = 0; i < set.getLength(); i++) { Node child = set.item(i); String version = xpath.evaluate("version", child); sb.append(del); sb.append(xpath.evaluate("groupId", child)); sb.append("."); sb.append(xpath.evaluate("artifactId", child)); if (version != null && version.trim().length()!=0) { sb.append(";version="); sb.append( Analyzer.cleanupVersion(version)); } del = ", "; } return sb.toString(); } /** * The maven POM is quite straightforward, it is basically a structured property file. * @param name * @param parent * @param p */ static void traverse(String name, Node parent, Properties p) { if ( skip.contains(parent.getNodeName())) return; NodeList children = parent.getChildNodes(); if (multiple.contains(parent.getNodeName())) { int n = 0; for (int i = 0; i < children.getLength(); i++) { Node child = children.item(i); if (!(child instanceof Text)) { traverse(name + "." + n++, child, p); } } } else { for (int i = 0; i < children.getLength(); i++) { Node child = children.item(i); if (child instanceof Text) { String value = child.getNodeValue().trim(); if (value.length()!=0) { p.put(name, value); } } else { traverse(name + "." + child.getNodeName(), child, p); } } } } } bnd-1.50.0/biz.aQute.bndlib/src/aQute/bnd/maven/MavenGroup.java0000644000175000017500000000111711656076535024012 0ustar drazzibdrazzibpackage aQute.bnd.maven; import java.util.*; import aQute.bnd.service.*; import aQute.libg.reporter.*; public class MavenGroup implements BsnToMavenPath, Plugin { String groupId = ""; public String[] getGroupAndArtifact(String bsn) { String[] result = new String[2]; result[0] = groupId; result[1] = bsn; return result; } public void setProperties(Map map) { if (map.containsKey("groupId")) { groupId = map.get("groupId"); } } public void setReporter(Reporter processor) { } } bnd-1.50.0/biz.aQute.bndlib/src/aQute/bnd/concurrent/0000755000175000017500000000000011656076535022140 5ustar drazzibdrazzibbnd-1.50.0/biz.aQute.bndlib/src/aQute/bnd/concurrent/MultiBuilder.java0000644000175000017500000000463011656076535025407 0ustar drazzibdrazzibpackage aQute.bnd.concurrent; import java.io.*; import java.util.*; import java.util.concurrent.*; import aQute.bnd.build.*; import aQute.lib.osgi.*; import aQute.libg.forker.*; /** * This class implements a concurrent builder. It manages the build process in * an environment where many threads can initiate builds. Users should call * changed(Project,boolean) * */ public class MultiBuilder { Workspace workspace; volatile FutureTask future; final Set filesChanged = Collections .synchronizedSet(new HashSet()); /** * Constructor * * @param workspace * the workspace this MultiBuilder works for. * */ public MultiBuilder(Workspace workspace) { this.workspace = workspace; } /** * Return the build result of a project. * * @param p * the project * @return the files build by the project * * @throws Exception */ public File[] build(Project p) throws Exception { if (p.isStale()) { schedule(true); } return p.build(); } /** * Indicate that the project has changed. This will start a build. * * @param p * the project that is changed * @throws Exception */ public void changed(Project p) throws Exception { p.setChanged(); schedule(false); } /** * Schedule a new build if no build is running otherwise return. * * @throws Exception */ public void schedule(boolean sync) throws Exception { synchronized (this) { if (future != null) { future.cancel(true); future.get(); future = null; } future = new FutureTask(new Callable() { public Throwable call() { Forker forker = new Forker(Processor.getExecutor()); try { Thread.sleep(100); workspace.bracket(true); try { for (final Project p : workspace.getAllProjects()) { forker.doWhen(p.getDependson(), p, new Runnable() { public void run() { try { p.build(); } catch (Exception e) { e.printStackTrace(); } } }); } forker.start(0); } catch (InterruptedException e) { forker.cancel(10000); } finally { workspace.bracket(false); } } catch (Exception e) { return e; } return null; } }); Processor.getExecutor().execute(future); if ( sync ) future.get(); } } } bnd-1.50.0/biz.aQute.bndlib/src/aQute/bnd/test/0000755000175000017500000000000011656076535020735 5ustar drazzibdrazzibbnd-1.50.0/biz.aQute.bndlib/src/aQute/bnd/test/SimpleContext.java0000644000175000017500000000113411656076535024375 0ustar drazzibdrazzibpackage aQute.bnd.test; import java.util.*; import javax.xml.namespace.*; public class SimpleContext implements NamespaceContext { final String prefix; final String ns; SimpleContext(String prefix, String ns) { this.prefix = prefix; this.ns = ns; } public String getNamespaceURI(String prefix) { if ( prefix.equals(prefix)) return ns; else return null; } public String getPrefix(String namespaceURI) { if (namespaceURI.equals(ns)) return prefix; return prefix; } public Iterator getPrefixes(String namespaceURI) { return Arrays.asList(prefix).iterator(); } } bnd-1.50.0/biz.aQute.bndlib/src/aQute/bnd/test/XmlTester.java0000644000175000017500000000311011656076535023522 0ustar drazzibdrazzibpackage aQute.bnd.test; import java.io.*; import java.util.*; import javax.xml.namespace.*; import javax.xml.parsers.*; import javax.xml.xpath.*; import junit.framework.*; import org.w3c.dom.*; public class XmlTester { final static DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); final static XPathFactory xpathf = XPathFactory.newInstance(); final static DocumentBuilder db; static { try { dbf.setNamespaceAware(true); db = dbf.newDocumentBuilder(); } catch (ParserConfigurationException e) { throw new RuntimeException(e); } } final Document document; final XPath xpath = xpathf.newXPath(); public XmlTester(InputStream in, final String... namespace) throws Exception { xpath.setNamespaceContext(new NamespaceContext() { public Iterator getPrefixes(String namespaceURI) { return Arrays.asList("md", "scr").iterator(); } public String getPrefix(String namespaceURI) { for (int i = 0; i < namespace.length; i += 2) { if (namespaceURI.equals(namespace[i + 1])) return namespace[i]; } return null; } public String getNamespaceURI(String prefix) { for (int i = 0; i < namespace.length; i += 2) { if (prefix.equals(namespace[i])) return namespace[i + 1]; } return null; } }); document = db.parse(in); } public void assertAttribute(String value, String expr) throws XPathExpressionException { System.out.println(expr); String o = (String) xpath.evaluate(expr, document, XPathConstants.STRING); Assert.assertNotNull(o); Assert.assertEquals(value, o); } } bnd-1.50.0/biz.aQute.bndlib/src/aQute/bnd/test/BndTestCase.java0000644000175000017500000000147111656076535023742 0ustar drazzibdrazzibpackage aQute.bnd.test; import java.util.*; import junit.framework.*; import aQute.libg.reporter.*; public abstract class BndTestCase extends TestCase { protected void assertOk(Reporter reporter) { try { assertEquals(0, reporter.getErrors().size()); assertEquals(0, reporter.getWarnings().size()); } catch (AssertionFailedError t) { print("Errors", reporter.getErrors()); print("Warnings", reporter.getWarnings()); throw t; } } private void print(String title, List strings) { System.out.println("-------------------------------------------------------------------------"); System.out.println(title + " " + strings.size()); System.out.println("-------------------------------------------------------------------------"); for ( Object s : strings) { System.out.println(s); } } } bnd-1.50.0/biz.aQute.bndlib/src/aQute/bnd/settings/0000755000175000017500000000000011656076535021616 5ustar drazzibdrazzibbnd-1.50.0/biz.aQute.bndlib/src/aQute/bnd/settings/Settings.java0000644000175000017500000000330111656076535024256 0ustar drazzibdrazzibpackage aQute.bnd.settings; import java.security.*; import java.security.interfaces.*; import java.util.*; import java.util.prefs.*; import aQute.libg.cryptography.*; import aQute.libg.tuple.*; public class Settings { public final static String EMAIL = "email"; public final static String NAME = "name"; public final static String PASSWORD_SHA1 = "password.sha1"; final static String KEY_PRIVATE = "key.private"; final static String KEY_PUBLIC = "key.public"; final static String KEY_SET = "key.set"; static Preferences prefs = Preferences.userNodeForPackage(Settings.class); public String globalGet(String key, String def) { return prefs.get(key, def); } public void globalSet(String key, String value) throws BackingStoreException { prefs.put(key, value); prefs.sync(); } public Collection getKeys() throws BackingStoreException { return Arrays.asList(prefs.keys()); } public void globalRemove(String key) throws BackingStoreException { prefs.remove(key); prefs.sync(); } private void generate() throws NoSuchAlgorithmException { Pair pair = RSA.generate(); prefs.put(KEY_PRIVATE, Crypto.toString(pair.a)); prefs.put(KEY_PUBLIC, Crypto.toString(pair.b)); prefs.putBoolean(KEY_SET, true); } public PrivateKey getPrivateKey() throws Exception { if (prefs.getBoolean(KEY_SET, false)) generate(); String key = prefs.get(KEY_PRIVATE, null); return Crypto.fromString(key, PrivateKey.class); } public PublicKey getPublicKey() throws Exception { if (prefs.getBoolean(KEY_SET, false)) generate(); String key = prefs.get(KEY_PUBLIC, null); return Crypto.fromString(key, PublicKey.class); } } bnd-1.50.0/biz.aQute.bndlib/src/aQute/bnd/repo/0000755000175000017500000000000011656076535020723 5ustar drazzibdrazzibbnd-1.50.0/biz.aQute.bndlib/src/aQute/bnd/repo/eclipse/0000755000175000017500000000000011656076535022347 5ustar drazzibdrazzibbnd-1.50.0/biz.aQute.bndlib/src/aQute/bnd/repo/eclipse/EclipseRepo.java0000644000175000017500000001357711656076535025441 0ustar drazzibdrazzibpackage aQute.bnd.repo.eclipse; import java.io.*; import java.util.*; import java.util.jar.*; import aQute.bnd.service.*; import aQute.lib.osgi.*; import aQute.libg.generics.*; import aQute.libg.reporter.*; import aQute.libg.version.*; public class EclipseRepo implements Plugin, RepositoryPlugin { File root; Reporter reporter; String name; Map> index; public static String LOCATION = "location"; public static String NAME = "name"; public void setProperties(Map map) { String location = (String) map.get(LOCATION); if (location == null) throw new IllegalArgumentException( "Location muse be set on a EclipseRepo plugin"); root = new File(location); if (!root.isDirectory()) throw new IllegalArgumentException( "Repository is not a valid directory " + root); if (!new File(root, "plugins").isDirectory()) throw new IllegalArgumentException( "Repository is not a valid directory (no plugins directory)" + root); name = (String) map.get(NAME); try { index = buildIndex(); } catch (Exception e) { throw new RuntimeException( "Could not build index for eclipse repo: " + root); } } Map> buildIndex() throws Exception { File index = new File(root, "bnd.index").getAbsoluteFile(); File[] plugins = new File(root, "plugins").listFiles(); for (File f : plugins) { f = f.getAbsoluteFile(); if (f.isFile()) { if (f.lastModified() > index.lastModified()) { Map> map = buildIndex(plugins); write(index, map); return map; } } } String s = read(index); return Processor.parseHeader(s, null); } private String read(File index) throws Exception { if (index.isFile()) { BufferedReader fr = new BufferedReader(new FileReader(index)); StringBuilder sb = new StringBuilder(); try { String s = fr.readLine(); while (s != null) { sb.append(s); s = fr.readLine(); } } finally { fr.close(); } } return null; } private void write(File index, Map> map) throws Exception { String s = Processor.printClauses(map); index.getParentFile().mkdirs(); FileWriter fw = new FileWriter(index); try { fw.write(s); } finally { fw.close(); } } private Map> buildIndex(File[] plugins) { Map> map = Create.map(); for (File plugin : plugins) { try { Jar jar = new Jar(plugin); Manifest manifest = jar.getManifest(); String bsn = manifest.getMainAttributes().getValue( Constants.BUNDLE_SYMBOLICNAME); String version = manifest.getMainAttributes().getValue( Constants.BUNDLE_VERSION); if (bsn != null) { if (version == null) version = "0"; Map instance = map.get(bsn); if (instance == null) { instance = Create.map(); } instance.put(version, plugin.getAbsolutePath()); } } catch (Exception e) { // Ignore exceptions in the plugins dir. } } return map; } public void setReporter(Reporter reporter) { this.reporter = reporter; } public boolean canWrite() { return false; } public File[] get(String bsn, String range) throws Exception { VersionRange r = new VersionRange(range); Map instances = index.get(bsn); if (instances == null) return null; List result = Create.list(); for (String version : instances.keySet()) { Version v = new Version(version); if (r.includes(v)) { File f = new File(instances.get(version)); if (f.isFile()) { result.add(f); } } } return result.toArray(new File[result.size()]); } public String getName() { return name; } public List list(String regex) { Instruction pattern = null; if (regex != null) pattern = Instruction.getPattern(regex); List result = new ArrayList(); for (String f : index.keySet()) { if (pattern == null || pattern.matches(f)) result.add(f); } return result; } public File put(Jar jar) throws Exception { return null; } public List versions(String bsn) { Map instances = index.get(bsn); if (instances == null) return null; List versions = Create.list(); for (String v : instances.keySet()) versions.add(new Version(v)); return versions; } public File get(String bsn, String range, Strategy strategy, Map properties) throws Exception { File[] files = get(bsn, range); if (files.length >= 0) { switch (strategy) { case LOWEST: return files[0]; case HIGHEST: return files[files.length - 1]; } } return null; } } bnd-1.50.0/biz.aQute.bndlib/src/aQute/bnd/signing/0000755000175000017500000000000011656076535021414 5ustar drazzibdrazzibbnd-1.50.0/biz.aQute.bndlib/src/aQute/bnd/signing/Signer.java0000644000175000017500000001525311656076535023514 0ustar drazzibdrazzibpackage aQute.bnd.signing; import java.io.*; import java.security.*; import java.security.KeyStore.*; import java.util.*; import java.util.jar.*; import java.util.regex.*; import aQute.lib.base64.*; import aQute.lib.osgi.*; /** * This class is used with the aQute.lib.osgi package, it signs jars with DSA * signature. * * -sign: md5, sha1 */ public class Signer extends Processor { static Pattern METAINFDIR = Pattern.compile("META-INF/[^/]*"); String digestNames[] = new String[] { "MD5" }; File keystoreFile = new File("keystore"); String password; String alias; public void signJar(Jar jar) { if (digestNames == null || digestNames.length == 0) error("Need at least one digest algorithm name, none are specified"); if (keystoreFile == null || !keystoreFile.getAbsoluteFile().exists()) { error("No such keystore file: " + keystoreFile); return; } if (alias == null) { error("Private key alias not set for signing"); return; } MessageDigest digestAlgorithms[] = new MessageDigest[digestNames.length]; getAlgorithms(digestNames, digestAlgorithms); try { Manifest manifest = jar.getManifest(); manifest.getMainAttributes().putValue("Signed-By", "Bnd"); // Create a new manifest that contains the // Name parts with the specified digests ByteArrayOutputStream o = new ByteArrayOutputStream(); manifest.write(o); doManifest(jar, digestNames, digestAlgorithms, o); o.flush(); byte newManifestBytes[] = o.toByteArray(); jar.putResource("META-INF/MANIFEST.MF", new EmbeddedResource( newManifestBytes, 0)); // Use the bytes from the new manifest to create // a signature file byte[] signatureFileBytes = doSignatureFile(digestNames, digestAlgorithms, newManifestBytes); jar.putResource("META-INF/BND.SF", new EmbeddedResource( signatureFileBytes, 0)); // Now we must create an RSA signature // this requires the private key from the keystore KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType()); KeyStore.PrivateKeyEntry privateKeyEntry = null; try { java.io.FileInputStream keystoreInputStream = new java.io.FileInputStream( keystoreFile); keystore.load(keystoreInputStream, password == null ? null : password.toCharArray()); keystoreInputStream.close(); privateKeyEntry = (PrivateKeyEntry) keystore.getEntry( alias, new KeyStore.PasswordProtection(password .toCharArray())); } catch (Exception e) { error("No able to load the private key from the give keystore("+keystoreFile.getAbsolutePath()+") with alias "+alias+" : " + e); return; } PrivateKey privateKey = privateKeyEntry.getPrivateKey(); Signature signature = Signature.getInstance("MD5withRSA"); signature.initSign(privateKey); signature.update(signatureFileBytes); signature.sign(); // TODO, place the SF in a PCKS#7 structure ... // no standard class for this? The following // is an idea but we will to have do ASN.1 BER // encoding ... ByteArrayOutputStream tmpStream = new ByteArrayOutputStream(); jar.putResource("META-INF/BND.RSA", new EmbeddedResource(tmpStream .toByteArray(), 0)); } catch (Exception e) { error("During signing: " + e); } } private byte[] doSignatureFile(String[] digestNames, MessageDigest[] algorithms, byte[] manbytes) { ByteArrayOutputStream out = new ByteArrayOutputStream(); PrintStream ps = new PrintStream(out); ps.print("Signature-Version: 1.0\r\n"); for (int a = 0; a < algorithms.length; a++) { if (algorithms[a] != null) { byte[] digest = algorithms[a].digest(manbytes); ps.print(digestNames[a] + "-Digest-Manifest: "); ps.print(new Base64(digest)); ps.print("\r\n"); } } return out.toByteArray(); } private void doManifest(Jar jar, String[] digestNames, MessageDigest[] algorithms, OutputStream out) throws Exception { for (Map.Entry entry : jar.getResources().entrySet()) { String name = entry.getKey(); if (!METAINFDIR.matcher(name).matches()) { out.write("\r\n".getBytes()); out.write("Name: ".getBytes()); out.write(name.getBytes()); out.write("\r\n".getBytes()); digest(algorithms, entry.getValue()); for (int a = 0; a < algorithms.length; a++) { if (algorithms[a] != null) { byte[] digest = algorithms[a].digest(); String header = digestNames[a] + "-Digest: " + new Base64(digest) + "\r\n"; out.write(header.getBytes()); } } } } } private void digest(MessageDigest[] algorithms, Resource r) throws Exception { InputStream in = r.openInputStream(); byte[] data = new byte[1024]; int size = in.read(data); while (size > 0) { for (int a = 0; a < algorithms.length; a++) { if (algorithms[a] != null) { algorithms[a].update(data, 0, size); } } size = in.read(data); } } private void getAlgorithms(String[] digestNames, MessageDigest[] algorithms) { for (int i = 0; i < algorithms.length; i++) { String name = digestNames[i]; try { algorithms[i] = MessageDigest.getInstance(name); } catch (NoSuchAlgorithmException e) { error("Specified digest algorithm " + digestNames[i] + ", but not such algorithm was found: " + e); } } } public void setPassword(String string) { password = string; } public void setKeystore(File keystore) { this.keystoreFile = keystore; } public void setAlias(String string) { this.alias = string; } } bnd-1.50.0/biz.aQute.bndlib/src/aQute/bnd/signing/JartoolSigner.java0000644000175000017500000000755611656076535025056 0ustar drazzibdrazzibpackage aQute.bnd.signing; import java.io.*; import java.util.*; import java.util.concurrent.*; import aQute.bnd.service.*; import aQute.lib.osgi.*; import aQute.libg.command.*; import aQute.libg.reporter.*; /** * Sign the jar file. * * -sign : [ ';' 'password:=' ] [ ';' 'keystore:=' ] [ * ';' 'sign-password:=' ] ( ',' ... )* * * @author aqute * */ public class JartoolSigner implements Plugin, SignerPlugin { String keystore; String storetype; String path = "jarsigner"; String storepass; String keypass; String sigFile; public void setProperties(Map map) { if (map.containsKey("keystore")) this.keystore = map.get("keystore"); if (map.containsKey("storetype")) this.storetype = map.get("storetype"); if (map.containsKey("storepass")) this.storepass = map.get("storepass"); if (map.containsKey("keypass")) this.keypass = map.get("keypass"); if (map.containsKey("path")) this.path = map.get("path"); if (map.containsKey("sigFile")) this.sigFile = map.get("sigFile"); } public void setReporter(Reporter processor) { } public void sign(Builder builder, String alias) throws Exception { File f = builder.getFile(keystore); if ( !f.isFile()) { builder.error("Invalid keystore %s", f.getAbsolutePath() ); return; } Jar jar = builder.getJar(); File tmp = File.createTempFile("signdjar", ".jar"); tmp.deleteOnExit(); jar.write(tmp); Command command = new Command(); command.add(path); if (keystore != null) { command.add("-keystore"); command.add(f.getAbsolutePath()); } if (storetype != null) { command.add("-storetype"); command.add(storetype); } if (keypass != null) { command.add("-keypass"); command.add(keypass); } if (storepass != null) { command.add("-storepass"); command.add(storepass); } if (sigFile != null) { command.add("-sigFile"); command.add(sigFile); } command.add(tmp.getAbsolutePath()); command.add(alias); builder.trace("Jarsigner command: %s", command); command.setTimeout(20, TimeUnit.SECONDS); StringBuffer out = new StringBuffer(); StringBuffer err = new StringBuffer(); int exitValue = command.execute(System.in, out, err); if (exitValue != 0) { builder.error("Signing Jar out: %s\nerr: %s", out, err); } else { builder.trace("Signing Jar out: %s \nerr: %s", out, err); } Jar signed = new Jar(tmp); builder.addClose(signed); Map dir = signed.getDirectories().get("META-INF"); for (String path : dir.keySet()) { if (path.matches(".*\\.(DSA|RSA|SF|MF)$")) { jar.putResource(path, dir.get(path)); } } jar.setDoNotTouchManifest(); } StringBuffer collect(final InputStream in) throws Exception { final StringBuffer sb = new StringBuffer(); Thread tin = new Thread() { public void run() { try { BufferedReader rdr = new BufferedReader(new InputStreamReader(in, Constants.DEFAULT_CHARSET)); String line = rdr.readLine(); while (line != null) { sb.append(line); line = rdr.readLine(); } rdr.close(); in.close(); } catch (Exception e) { // Ignore any exceptions } } }; tin.start(); return sb; } } bnd-1.50.0/biz.aQute.bndlib/README0000644000175000017500000000022211656076535016221 0ustar drazzibdrazzibThe bndlib project is a general library to be used with OSGi bundles. It contains lots of cool functionality that calculates dependencies, etc. bnd-1.50.0/biz.aQute.bndlib/.settings/0000755000175000017500000000000011656076535017263 5ustar drazzibdrazzibbnd-1.50.0/biz.aQute.bndlib/.settings/org.eclipse.jdt.core.prefs0000755000175000017500000000115211656076535024247 0ustar drazzibdrazzib#Mon Jul 14 16:25:03 CEST 2008 eclipse.preferences.version=1 org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.5 org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve org.eclipse.jdt.core.compiler.compliance=1.5 org.eclipse.jdt.core.compiler.debug.lineNumber=generate org.eclipse.jdt.core.compiler.debug.localVariable=generate org.eclipse.jdt.core.compiler.debug.sourceFile=generate org.eclipse.jdt.core.compiler.problem.assertIdentifier=error org.eclipse.jdt.core.compiler.problem.enumIdentifier=error org.eclipse.jdt.core.compiler.source=1.5 bnd-1.50.0/biz.aQute.bndlib/.settings/org.eclipse.core.resources.prefs0000644000175000017500000000012511656076535025474 0ustar drazzibdrazzib#Mon Sep 19 11:00:09 EDT 2005 eclipse.preferences.version=1 encoding/=UTF-8 bnd-1.50.0/biz.aQute.bndlib/.settings/org.eclipse.core.runtime.prefs0000644000175000017500000000011611656076535025145 0ustar drazzibdrazzib#Tue Dec 14 12:22:25 EST 2010 eclipse.preferences.version=1 line.separator=\n bnd-1.50.0/aQute.libg/0000755000175000017500000000000011656076535014245 5ustar drazzibdrazzibbnd-1.50.0/aQute.libg/build.xml0000644000175000017500000000017711656076535016073 0ustar drazzibdrazzib bnd-1.50.0/aQute.libg/bnd.bnd0000644000175000017500000000014211656076535015472 0ustar drazzibdrazzib-nobundles: true -buildpath: com.springsource.junit Private-Package: aQute.lib.*, aQute.libg.* bnd-1.50.0/aQute.libg/.classpath0000755000175000017500000000044511656076535016236 0ustar drazzibdrazzib bnd-1.50.0/aQute.libg/.project0000755000175000017500000000056111656076535015721 0ustar drazzibdrazzib aQute.libg org.eclipse.jdt.core.javabuilder org.eclipse.jdt.core.javanature bnd-1.50.0/aQute.libg/src/0000755000175000017500000000000011656076535015034 5ustar drazzibdrazzibbnd-1.50.0/aQute.libg/src/test/0000755000175000017500000000000011656076535016013 5ustar drazzibdrazzibbnd-1.50.0/aQute.libg/src/test/TestSAXFilters.java0000644000175000017500000000726711656076535021516 0ustar drazzibdrazzibpackage test; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import javax.xml.transform.stream.StreamResult; import junit.framework.TestCase; import org.xml.sax.Attributes; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import org.xml.sax.XMLReader; import aQute.libg.sax.SAXUtil; import aQute.libg.sax.filters.ElementSelectionFilter; import aQute.libg.sax.filters.MergeContentFilter; public class TestSAXFilters extends TestCase { private static final String SAMPLE1 = "" + ""; private static final String SAMPLE2 = "" + ""; private static final String MERGED1_2 = "" + ""; private static final String SAMPLE3 = "" + ""; private static final String SAMPLE4 = "" + ""; private static final String SAMPLE5 = ""; public void testMerge() throws Exception { ByteArrayOutputStream output = new ByteArrayOutputStream(); MergeContentFilter merger = new MergeContentFilter(); XMLReader reader = SAXUtil.buildPipeline(new StreamResult(output), merger); reader.parse(new InputSource(new ByteArrayInputStream(SAMPLE1.getBytes()))); reader.parse(new InputSource(new ByteArrayInputStream(SAMPLE2.getBytes()))); merger.closeRootAndDocument(); assertEquals(MERGED1_2, output.toString()); assertEquals(2, merger.getRootElements().size()); } public void testMergeInconsistentRoots() throws Exception { ByteArrayOutputStream output = new ByteArrayOutputStream(); MergeContentFilter merger = new MergeContentFilter(); XMLReader reader = SAXUtil.buildPipeline(new StreamResult(output), merger); try { reader.parse(new InputSource(new ByteArrayInputStream(SAMPLE1.getBytes()))); reader.parse(new InputSource(new ByteArrayInputStream(SAMPLE3.getBytes()))); fail ("Should throw exception for inconsistent roots"); } catch (SAXException e) { } } public void testDontRepeatProcessingInstruction() throws Exception { ByteArrayOutputStream output = new ByteArrayOutputStream(); MergeContentFilter merger = new MergeContentFilter(); XMLReader reader = SAXUtil.buildPipeline(new StreamResult(output), merger); reader.parse(new InputSource(new ByteArrayInputStream(SAMPLE5.getBytes()))); reader.parse(new InputSource(new ByteArrayInputStream(SAMPLE5.getBytes()))); merger.closeRootAndDocument(); assertEquals("\n", output.toString()); } public void testSelectionFilter() throws Exception { ByteArrayOutputStream output = new ByteArrayOutputStream(); ElementSelectionFilter filter = new ElementSelectionFilter() { @Override protected boolean select(int depth, String uri, String localName, String qName, Attributes attribs) { return !"e".equals(qName); } }; XMLReader reader = SAXUtil.buildPipeline(new StreamResult(output), filter); reader.parse(new InputSource(new ByteArrayInputStream(SAMPLE4.getBytes()))); assertEquals("", output.toString()); } } bnd-1.50.0/aQute.libg/src/test/TestCAFS.java0000644000175000017500000000365311656076535020241 0ustar drazzibdrazzibpackage test; import java.io.*; import java.security.*; import junit.framework.*; import aQute.lib.io.*; import aQute.libg.cafs.*; import aQute.libg.cryptography.*; public class TestCAFS extends TestCase { File tmp; public void setUp() throws Exception { tmp = new File(System.getProperty("java.io.tmpdir")); assertTrue(tmp.isDirectory()); } public void testX() {} // public void testSimple() throws Exception { // File dir = new File(tmp, getClass().getName() + System.currentTimeMillis()); // CAFS cafs = new CAFS(dir, true); // MessageDigest digester = MessageDigest.getInstance("SHA-1"); // // DigestInputStream dis = new DigestInputStream(getClass().getResourceAsStream( // "cafs/file1.txt"), digester); // SHA1 sha1 = cafs.write(dis); // // assertEquals(new SHA1(digester.digest()), sha1); // // digester.reset(); // dis = new DigestInputStream(getClass().getResourceAsStream("cafs/file1-1.txt"), digester); // // SHA1 sha1_1 = cafs.write(dis); // assertEquals(sha1, sha1_1); // assertEquals( new SHA1(digester.digest()), sha1_1); // // SHA1 sha2 = cafs.write(getClass().getResourceAsStream("cafs/file2.txt")); // // assertFalse( sha1.equals(sha2)); // // int n = 0; // for (SHA1 key : cafs) { // assertTrue(sha1.equals(key) || sha2.equals(key)); // System.out.println(n++ + ": " + key); // InputStream in = cafs.read(key); // assertNotNull(in); // String s = IO.collect(in, "UTF-8"); // byte[] b = s.getBytes("UTF-8"); // MessageDigest md = MessageDigest.getInstance("SHA1"); // md.update(b); // assertEquals(key, new SHA1(md.digest())); // } // // // Close out db and reopen it again. // cafs.close(); // cafs = new CAFS(dir, false); // // for (SHA1 key : cafs) { // assertTrue(sha1.equals(key) || sha2.equals(key)); // } // // InputStream in = cafs.read(sha2); // assertNotNull(in); // SHA1 rsha2 = SHA1.getDigester().from(in); // // assertEquals(sha2, rsha2); // // cafs.close(); // } } bnd-1.50.0/aQute.libg/src/test/TestDirectoryInputStream.java0000644000175000017500000000107611656076535023662 0ustar drazzibdrazzibpackage test; import java.io.*; import junit.framework.*; public class TestDirectoryInputStream extends TestCase { public void testComplete() throws IOException { // DirectoryInputStream din2 = new DirectoryInputStream(new File("dir")); // JarInputStream in = new JarInputStream(din2); // assertNotNull(in.getManifest()); // JarEntry entry = in.getNextJarEntry(); // while (entry != null) { // System.out.println(entry.getName()); // entry = in.getNextJarEntry(); // } // // in.close(); } } bnd-1.50.0/aQute.libg/src/test/TestIndex.java0000644000175000017500000000330011656076535020561 0ustar drazzibdrazzibpackage test; import java.io.*; import junit.framework.*; import aQute.lib.index.*; public class TestIndex extends TestCase { public void testPersistence() throws Exception { File test = new File("test.tmp"); test.delete(); Index index = new Index(test, 2000); index.insert( new byte[]{1}, 2); index.insert( new byte[]{2}, 4); index.insert( new byte[]{3}, 6); assertEquals( 2, index.search(new byte[] {1})); assertEquals( 4, index.search(new byte[] {2})); assertEquals( 6, index.search(new byte[] {3})); System.out.println(index.toString()); index.close(); index = new Index(test, 2000); System.out.println(index.toString()); assertEquals( 2, index.search(new byte[] {1})); assertEquals( 4, index.search(new byte[] {2})); assertEquals( 6, index.search(new byte[] {3})); index.close(); } public void testBasic() throws Exception { File test = new File("test.tmp"); test.delete(); Index index = new Index(test, 2000); index.insert( new byte[] {12}, 24); index.insert( new byte[] {13}, 26); index.insert( new byte[] {6}, 12); index.insert( new byte[] {16}, 32); index.insert( new byte[] {1}, 2); assertEquals( 24, index.search(new byte[] {12})); assertEquals( 26, index.search(new byte[] {13}), 26); assertEquals( 12, index.search(new byte[] {6}), 12); } // public void testMany() throws Exception { // File test = new File("test.tmp"); // test.delete(); // Index index = new Index(test, 1000); // for ( int i = 1; i<127; i++) // index.insert( new byte[]{(byte)i}, i*2); // // index.close(); // Index index2 = new Index(test, 1000); // for ( int i = 1; i<127; i++) // assertEquals(i*2, index2.search( new byte[(byte)i])); // // } } bnd-1.50.0/aQute.libg/src/test/TestForker.java0000644000175000017500000000471411656076535020754 0ustar drazzibdrazzibpackage test; import java.util.*; import junit.framework.*; import aQute.libg.forker.*; public class TestForker extends TestCase { final Collection EMPTY = Collections.emptyList(); static class R implements Runnable { final Collection result; final int n; R(Collection result, int n) { this.result = result; this.n = n; } public void run() { result.add(n); } } public void testSimple() throws InterruptedException { final Forker forker = new Forker(); final Collection result = Collections.synchronizedList(new ArrayList()); forker.doWhen(Arrays.asList(3), 2, new R(result, 2)); forker.doWhen(Arrays.asList(2), 1, new R(result, 1)); forker.doWhen(EMPTY, 3, new R(result, 3)); forker.start(1000); assertEquals(Arrays.asList(3, 2, 1), result); } public void testSimple2() throws InterruptedException { final Forker forker = new Forker(); final Collection result = Collections.synchronizedList(new ArrayList()); forker.doWhen(Arrays.asList(1, 2, 3), 4, new R(result, 4)); forker.doWhen(EMPTY, 1, new R(result, 1)); forker.doWhen(EMPTY, 2, new R(result, 2)); forker.doWhen(EMPTY, 3, new R(result, 3)); forker.start(1000); assertEquals(Arrays.asList(1, 2, 3, 4), result); } public void testInvalid() { final Forker forker = new Forker(); final Collection result = Collections.synchronizedList(new ArrayList()); forker.doWhen(Arrays.asList(1, 2, 3), 4, new R(result, 4)); try { forker.start(100); fail(); } catch (Exception e) { System.out.println(e.getMessage()); assertEquals( IllegalArgumentException.class, e.getClass()); } } public void testCancel() throws InterruptedException { final Forker forker = new Forker(); final Collection result = Collections.synchronizedList(new ArrayList()); forker.doWhen(EMPTY, 4, new Runnable() { public void run() { synchronized (result) { try { System.out.println("starting to wait"); result.wait(); System.out.println("finished wait"); } catch (Exception e) { System.out.println("exception"); e.printStackTrace(); } finally { System.out.println("leaving task"); } } } }); forker.start(-1); Thread.sleep(1000); assertEquals(1, forker.getCount()); forker.cancel(1000); assertEquals(0, forker.getCount()); } } bnd-1.50.0/aQute.libg/src/test/cafs/0000755000175000017500000000000011656076535016727 5ustar drazzibdrazzibbnd-1.50.0/aQute.libg/src/test/cafs/file1.txt0000644000175000017500000000000711656076535020465 0ustar drazzibdrazzibFile 1 bnd-1.50.0/aQute.libg/src/test/cafs/file1-1.txt0000644000175000017500000000000711656076535020623 0ustar drazzibdrazzibFile 1 bnd-1.50.0/aQute.libg/src/test/cafs/file2.txt0000644000175000017500000000000711656076535020466 0ustar drazzibdrazzibFile 2 bnd-1.50.0/aQute.libg/src/test/TestTarjan.java0000644000175000017500000000212311656076535020733 0ustar drazzibdrazzibpackage test; import java.util.*; import junit.framework.*; import aQute.lib.collections.*; import aQute.libg.tarjan.*; public class TestTarjan extends TestCase { public void testTarjan() throws Exception { MultiMap g = mkGraph("A{BC}B{A}C{DE}D{C}E{D}"); System.out.println(g); Set> scc = Tarjan.tarjan(g); assertEquals(2, scc.size()); for ( Set set : scc) { if ( set.size()==3) assertEquals( new HashSet(Arrays.asList("E","C", "D")), set); else if ( set.size()==2) assertEquals( new HashSet(Arrays.asList("B","A")), set); else fail(); } } private MultiMap mkGraph(String string) { MultiMap map = new MultiMap(); String key = null; for (int i = 0; i < string.length(); i++) { char c = string.charAt(i); switch (c) { case '{': break; case '}': key = null; break; default: if (key == null) { key = c + ""; map.put(key, new HashSet()); } else map.add(key, c + ""); } } return map; } } bnd-1.50.0/aQute.libg/src/aQute/0000755000175000017500000000000011656076535016113 5ustar drazzibdrazzibbnd-1.50.0/aQute.libg/src/aQute/lib/0000755000175000017500000000000011656076535016661 5ustar drazzibdrazzibbnd-1.50.0/aQute.libg/src/aQute/lib/tag/0000755000175000017500000000000011656076535017434 5ustar drazzibdrazzibbnd-1.50.0/aQute.libg/src/aQute/lib/tag/packageinfo0000644000175000017500000000001411656076535021621 0ustar drazzibdrazzibversion 1.0 bnd-1.50.0/aQute.libg/src/aQute/lib/tag/Tag.java0000755000175000017500000002340011656076535021014 0ustar drazzibdrazzibpackage aQute.lib.tag; import java.io.*; import java.text.*; import java.util.*; /** * The Tag class represents a minimal XML tree. It consist of a named element * with a hashtable of named attributes. Methods are provided to walk the tree * and get its constituents. The content of a Tag is a list that contains String * objects or other Tag objects. */ public class Tag { Tag parent; // Parent String name; // Name final Map attributes = new LinkedHashMap(); final List content = new ArrayList(); // Content static SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss.SSS"); boolean cdata; /** * Construct a new Tag with a name. */ public Tag(String name, Object... contents) { this.name = name; for (Object c : contents) content.add(c); } public Tag(Tag parent, String name, Object... contents) { this(name,contents); parent.addContent(this); } /** * Construct a new Tag with a name. */ public Tag(String name, Map attributes, Object... contents) { this(name,contents); this.attributes.putAll(attributes); } public Tag(String name, Map attributes) { this(name, attributes, new Object[0]); } /** * Construct a new Tag with a name and a set of attributes. The attributes * are given as ( name, value ) ... */ public Tag(String name, String[] attributes, Object... contents) { this(name,contents); for (int i = 0; i < attributes.length; i += 2) addAttribute(attributes[i], attributes[i + 1]); } public Tag(String name, String[] attributes) { this(name, attributes, new Object[0]); } /** * Add a new attribute. */ public Tag addAttribute(String key, String value) { if (value != null) attributes.put(key, value); return this; } /** * Add a new attribute. */ public Tag addAttribute(String key, Object value) { if (value == null) return this; attributes.put(key, value.toString()); return this; } /** * Add a new attribute. */ public Tag addAttribute(String key, int value) { attributes.put(key, Integer.toString(value)); return this; } /** * Add a new date attribute. The date is formatted as the SimpleDateFormat * describes at the top of this class. */ public Tag addAttribute(String key, Date value) { if (value != null) attributes.put(key, format.format(value)); return this; } /** * Add a new content string. */ public Tag addContent(String string) { if (string != null) content.add(string); return this; } /** * Add a new content tag. */ public Tag addContent(Tag tag) { content.add(tag); tag.parent = this; return this; } /** * Return the name of the tag. */ public String getName() { return name; } /** * Return the attribute value. */ public String getAttribute(String key) { return (String) attributes.get(key); } /** * Return the attribute value or a default if not defined. */ public String getAttribute(String key, String deflt) { String answer = getAttribute(key); return answer == null ? deflt : answer; } /** * Answer the attributes as a Dictionary object. */ public Map getAttributes() { return attributes; } /** * Return the contents. */ public List getContents() { return content; } /** * Return a string representation of this Tag and all its children * recursively. */ public String toString() { StringWriter sw = new StringWriter(); print(0, new PrintWriter(sw)); return sw.toString(); } /** * Return only the tags of the first level of descendants that match the * name. */ public List getContents(String tag) { List out = new ArrayList(); for (Object o : out) { if (o instanceof Tag && ((Tag) o).getName().equals(tag)) out.add(o); } return out; } /** * Return the whole contents as a String (no tag info and attributes). */ public String getContentsAsString() { StringBuffer sb = new StringBuffer(); getContentsAsString(sb); return sb.toString(); } /** * convenient method to get the contents in a StringBuffer. */ public void getContentsAsString(StringBuffer sb) { for (Object o : content) { if (o instanceof Tag) ((Tag) o).getContentsAsString(sb); else sb.append(o.toString()); } } /** * Print the tag formatted to a PrintWriter. */ public Tag print(int indent, PrintWriter pw) { pw.print("\n"); spaces(pw, indent); pw.print('<'); pw.print(name); for (String key : attributes.keySet()) { String value = escape(attributes.get(key)); pw.print(' '); pw.print(key); pw.print("="); String quote = "'"; if (value.indexOf(quote) >= 0) quote = "\""; pw.print(quote); pw.print(value); pw.print(quote); } if (content.size() == 0) pw.print('/'); else { pw.print('>'); for (Object c : content) { if (c instanceof String) { formatted(pw, indent + 2, 60, escape((String) c)); } else if (c instanceof Tag) { Tag tag = (Tag) c; tag.print(indent + 2, pw); } } pw.print("\n"); spaces(pw, indent); pw.print("'); return this; } /** * Convenience method to print a string nicely and does character conversion * to entities. */ void formatted(PrintWriter pw, int left, int width, String s) { int pos = width + 1; s = s.trim(); for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); if (i == 0 || (Character.isWhitespace(c) && pos > width - 3)) { pw.print("\n"); spaces(pw, left); pos = 0; } switch (c) { case '<': pw.print("<"); pos += 4; break; case '>': pw.print(">"); pos += 4; break; case '&': pw.print("&"); pos += 5; break; default: pw.print(c); pos++; break; } } } /** * Escape a string, do entity conversion. */ String escape(String s) { StringBuffer sb = new StringBuffer(); for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); switch (c) { case '<': sb.append("<"); break; case '>': sb.append(">"); break; case '&': sb.append("&"); break; default: sb.append(c); break; } } return sb.toString(); } /** * Make spaces. */ void spaces(PrintWriter pw, int n) { while (n-- > 0) pw.print(' '); } /** * root/preferences/native/os */ public Collection select(String path) { return select(path, (Tag) null); } public Collection select(String path, Tag mapping) { List v = new ArrayList(); select(path, v, mapping); return v; } void select(String path, List results, Tag mapping) { if (path.startsWith("//")) { int i = path.indexOf('/', 2); String name = path.substring(2, i < 0 ? path.length() : i); for (Object o : content) { if (o instanceof Tag) { Tag child = (Tag) o; if (match(name, child, mapping)) results.add(child); child.select(path, results, mapping); } } return; } if (path.length() == 0) { results.add(this); return; } int i = path.indexOf("/"); String elementName = path; String remainder = ""; if (i > 0) { elementName = path.substring(0, i); remainder = path.substring(i + 1); } for (Object o : content) { if (o instanceof Tag) { Tag child = (Tag) o; if (child.getName().equals(elementName) || elementName.equals("*")) child.select(remainder, results, mapping); } } } public boolean match(String search, Tag child, Tag mapping) { String target = child.getName(); String sn = null; String tn = null; if (search.equals("*")) return true; int s = search.indexOf(':'); if (s > 0) { sn = search.substring(0, s); search = search.substring(s + 1); } int t = target.indexOf(':'); if (t > 0) { tn = target.substring(0, t); target = target.substring(t + 1); } if (!search.equals(target)) // different tag names return false; if (mapping == null) { return tn == sn || (sn != null && sn.equals(tn)); } else { String suri = sn == null ? mapping.getAttribute("xmlns") : mapping .getAttribute("xmlns:" + sn); String turi = tn == null ? child.findRecursiveAttribute("xmlns") : child .findRecursiveAttribute("xmlns:" + tn); return turi == suri || (turi != null && suri != null && turi.equals(suri)); } } public String getString(String path) { String attribute = null; int index = path.indexOf("@"); if (index >= 0) { // attribute attribute = path.substring(index + 1); if (index > 0) { // prefix path path = path.substring(index - 1); // skip -1 } else path = ""; } Collection tags = select(path); StringBuffer sb = new StringBuffer(); for (Tag tag : tags) { if (attribute == null) tag.getContentsAsString(sb); else sb.append(tag.getAttribute(attribute)); } return sb.toString(); } public String getStringContent() { StringBuffer sb = new StringBuffer(); for (Object c : content) { if (!(c instanceof Tag)) sb.append(c); } return sb.toString(); } public String getNameSpace() { return getNameSpace(name); } public String getNameSpace(String name) { int index = name.indexOf(':'); if (index > 0) { String ns = name.substring(0, index); return findRecursiveAttribute("xmlns:" + ns); } else return findRecursiveAttribute("xmlns"); } public String findRecursiveAttribute(String name) { String value = getAttribute(name); if (value != null) return value; if (parent != null) return parent.findRecursiveAttribute(name); return null; } public String getLocalName() { int index = name.indexOf(':'); if (index <= 0) return name; return name.substring(index + 1); } public void rename(String string) { name = string; } public void setCDATA() { cdata = true; } } bnd-1.50.0/aQute.libg/src/aQute/lib/collections/0000755000175000017500000000000011656076535021177 5ustar drazzibdrazzibbnd-1.50.0/aQute.libg/src/aQute/lib/collections/Logic.java0000644000175000017500000000100011656076535023066 0ustar drazzibdrazzibpackage aQute.lib.collections; import java.util.*; public class Logic { public static Collection retain( Collection first, Collection ... sets) { Set result = new HashSet(first); for ( Collection set : sets ) { result.retainAll(set); } return result; } public static Collection remove( Collection first, Collection ... sets) { Set result = new HashSet(first); for ( Collection set : sets ) { result.removeAll(set); } return result; } } bnd-1.50.0/aQute.libg/src/aQute/lib/collections/LineCollection.java0000644000175000017500000000214111656076535024743 0ustar drazzibdrazzibpackage aQute.lib.collections; import java.io.*; import java.util.*; public class LineCollection implements Iterator, Closeable { final BufferedReader reader; String next; public LineCollection(InputStream in) throws IOException { this(new InputStreamReader(in, "UTF8")); } public LineCollection(File in) throws IOException { this(new FileReader(in)); } public LineCollection(Reader reader) throws IOException { this(new BufferedReader(reader)); } public LineCollection(BufferedReader reader) throws IOException { this.reader = reader; next = reader.readLine(); } public boolean hasNext() { return next != null; } public String next() { if (next == null) throw new IllegalStateException("Iterator has finished"); try { String result = next; next = reader.readLine(); if (next == null) reader.close(); return result; } catch (Exception e) { // ignore return null; } } public void remove() { if (next == null) throw new UnsupportedOperationException("Cannot remove"); } public void close() throws IOException { reader.close(); } } bnd-1.50.0/aQute.libg/src/aQute/lib/collections/packageinfo0000644000175000017500000000001411656076535023364 0ustar drazzibdrazzibversion 1.0 bnd-1.50.0/aQute.libg/src/aQute/lib/collections/MultiMap.java0000644000175000017500000000314411656076535023574 0ustar drazzibdrazzibpackage aQute.lib.collections; import java.util.*; public class MultiMap extends HashMap> { private static final long serialVersionUID = 1L; final Set EMPTY = Collections.emptySet(); public boolean add( K key, V value ) { Set set = get(key); if ( set == null) { set=new HashSet(); put(key,set); } return set.add(value); } public boolean addAll( K key, Collection value ) { Set set = get(key); if ( set == null) { set=new HashSet(); put(key,set); } return set.addAll(value); } public boolean remove( K key, V value ) { Set set = get(key); if ( set == null) { return false; } boolean result = set.remove(value); if ( set.isEmpty()) remove(key); return result; } public boolean removeAll( K key, Collection value ) { Set set = get(key); if ( set == null) { return false; } boolean result = set.removeAll(value); if ( set.isEmpty()) remove(key); return result; } public Iterator iterate(K key) { Set set = get(key); if ( set == null) return EMPTY.iterator(); else return set.iterator(); } public Iterator all() { return new Iterator() { Iterator> master = values().iterator(); Iterator current = null; public boolean hasNext() { if ( current == null || !current.hasNext()) { if ( master.hasNext()) { current = master.next().iterator(); return current.hasNext(); } return false; } return true; } public V next() { return current.next(); } public void remove() { current.remove(); } }; } } bnd-1.50.0/aQute.libg/src/aQute/lib/hex/0000755000175000017500000000000011656076535017445 5ustar drazzibdrazzibbnd-1.50.0/aQute.libg/src/aQute/lib/hex/packageinfo0000644000175000017500000000001411656076535021632 0ustar drazzibdrazzibversion 1.0 bnd-1.50.0/aQute.libg/src/aQute/lib/hex/Hex.java0000755000175000017500000000256311656076535021045 0ustar drazzibdrazzibpackage aQute.lib.hex; import java.io.*; /* * Hex converter. * * TODO Implement string to byte[] */ public class Hex { byte[] data; final static char[] HEX = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'}; public final static byte[] toByteArray(String string) { string = string.trim(); if ( (string.length() & 1) != 0) throw new IllegalArgumentException("a hex string must have an even length"); byte[]out = new byte[ string.length()/2]; for ( int i=0; i < out.length; i++) { out[i] = (byte) (nibble(string.charAt(i*2))<<4 + nibble(string.charAt(i*2+1))); } return out; } public final static int nibble( char c) { if (c >= '0' && c <= '9') return c - '0'; if ( c>='A' && c<='F') return c - 'A' + 10; if ( c>='a' && c<='f') return c - 'a' + 10; throw new IllegalArgumentException("Not a hex digit: " + c); } public final static String toHexString(byte data[]) { StringBuilder sb = new StringBuilder(); try { append(sb,data); } catch (IOException e) { // cannot happen with sb } return sb.toString(); } public final static void append( Appendable sb, byte [] data ) throws IOException { for ( int i =0; i> 4)); sb.append( nibble( data[i])); } } private final static char nibble(int i) { return HEX[i & 0xF]; } } bnd-1.50.0/aQute.libg/src/aQute/lib/base64/0000755000175000017500000000000011656076535017745 5ustar drazzibdrazzibbnd-1.50.0/aQute.libg/src/aQute/lib/base64/Base64.java0000755000175000017500000000517511656076535021647 0ustar drazzibdrazzibpackage aQute.lib.base64; import java.io.*; /* * Base 64 converter. * * TODO Implement string to byte[] */ public class Base64 { byte[] data; static final String alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; static byte[] values = new byte[128]; static { for (int i = 0; i < values.length; i++) { values[i] = -1; } // Create reverse index for (int i = 0; i < alphabet.length(); i++) { char c = alphabet.charAt(i); values[c] = (byte) i; } } public Base64(byte data[]) { this.data = data; } public final static byte[] decodeBase64(String string) { string = string.trim(); ByteArrayOutputStream out = new ByteArrayOutputStream(); int register = 0; int i = 0; int pads = 0; byte test[] = new byte[3]; while (i < string.length()) { char c = string.charAt(i); if (c > 0x7F) throw new IllegalArgumentException( "Invalid base64 character in " + string + ", character value > 128 "); int v = 0; if ( c == '=' ) { pads++; } else { v = values[c]; if ( v < 0 ) throw new IllegalArgumentException( "Invalid base64 character in " + string + ", " + c ); } register <<= 6; register |= v; test[2] = (byte) (register & 0xFF); test[1] = (byte) ((register >> 8) & 0xFF); test[0] = (byte) ((register >> 16) & 0xFF); i++; if ((i % 4) == 0) { flush(out, register, pads); register = 0; pads = 0; } } return out.toByteArray(); } static private void flush(ByteArrayOutputStream out, int register, int pads) { switch (pads) { case 0: out.write(0xFF & (register >> 16)); out.write(0xFF & (register >> 8)); out.write(0xFF & (register >> 0)); break; case 1: out.write(0xFF & (register >> 16)); out.write(0xFF & (register >> 8)); break; case 2: out.write(0xFF & (register >> 16)); } } public Base64(String s) { data = decodeBase64(s); } public String toString() { return encodeBase64(data); } public static String encodeBase64(byte data[]) { StringBuffer sb = new StringBuffer(); int buf = 0; int bits = 0; int n = 0; while (true) { if (bits >= 6) { bits -= 6; int v = 0x3F & (buf >> bits); sb.append(alphabet.charAt(v)); } else { if (n >= data.length) break; buf <<= 8; buf |= 0xFF & data[n++]; bits += 8; } } if (bits != 0) // must be less than 7 sb.append(alphabet.charAt(0x3F & (buf << (6 - bits)))); int mod = 4 - (sb.length() % 4); if (mod != 4) { for (int i = 0; i < mod; i++) sb.append('='); } return sb.toString(); } public Object toData() { return data; } } bnd-1.50.0/aQute.libg/src/aQute/lib/base64/packageinfo0000644000175000017500000000001411656076535022132 0ustar drazzibdrazzibversion 1.0 bnd-1.50.0/aQute.libg/src/aQute/lib/io/0000755000175000017500000000000011656076535017270 5ustar drazzibdrazzibbnd-1.50.0/aQute.libg/src/aQute/lib/io/LimitedInputStream.java0000644000175000017500000000270211656076535023717 0ustar drazzibdrazzibpackage aQute.lib.io; import java.io.*; public class LimitedInputStream extends InputStream { final InputStream in; final int size; int left; public LimitedInputStream(InputStream in, int size) { this.in = in; this.left = size; this.size = size; } @Override public int read() throws IOException { if (left <= 0) { eof(); return -1; } left--; return in.read(); } @Override public int available() throws IOException { return Math.min(left, in.available()); } @Override public void close() throws IOException { eof(); in.close(); } protected void eof() { } @Override public synchronized void mark(int readlimit) { throw new UnsupportedOperationException(); } @Override public boolean markSupported() { return false; } @Override public int read(byte[] b, int off, int len) throws IOException { int min = Math.min(len, left); if (min == 0) return 0; int read = in.read(b, off, min); if (read > 0) left -= read; return read; } @Override public int read(byte[] b) throws IOException { return read(b,0,b.length); } @Override public synchronized void reset() throws IOException { throw new UnsupportedOperationException(); } @Override public long skip(long n) throws IOException { long count = 0; byte buffer[] = new byte[1024]; while ( n > 0 && read() >= 0) { int size = read(buffer); if ( size <= 0) return count; count+=size; n-=size; } return count; } } bnd-1.50.0/aQute.libg/src/aQute/lib/io/packageinfo0000644000175000017500000000001411656076535021455 0ustar drazzibdrazzibversion 1.0 bnd-1.50.0/aQute.libg/src/aQute/lib/io/IO.java0000644000175000017500000001003311656076535020437 0ustar drazzibdrazzibpackage aQute.lib.io; import java.io.*; import java.net.*; import java.nio.*; import java.util.*; public class IO { public static void copy(InputStream in, OutputStream out) throws IOException { DataOutputStream dos = new DataOutputStream(out); copy(in, (DataOutput) dos); } public static void copy(InputStream in, DataOutput out) throws IOException { byte[] buffer = new byte[10000]; try { int size = in.read(buffer); while (size > 0) { out.write(buffer, 0, size); size = in.read(buffer); } } finally { in.close(); } } public static void copy(InputStream in, ByteBuffer bb) throws IOException { byte[] buffer = new byte[10000]; try { int size = in.read(buffer); while (size > 0) { bb.put(buffer, 0, size); size = in.read(buffer); } } finally { in.close(); } } public static void copy(File a, File b) throws IOException { if (a.isFile()) { FileOutputStream out = new FileOutputStream(b); try { copy(new FileInputStream(a), out); } finally { out.close(); } } else if ( a.isDirectory()) { b.mkdirs(); if ( !b.isDirectory()) throw new IllegalArgumentException("target directory for a directory must be a directory: " + b); File subs[] = a.listFiles(); for ( File sub : subs ) { copy(sub, new File(b,sub.getName())); } } else throw new FileNotFoundException("During copy: " + a.toString()); } public static void copy(InputStream a, File b) throws IOException { FileOutputStream out = new FileOutputStream(b); try { copy(a, out); } finally { out.close(); } } public static void copy(File a, OutputStream b) throws IOException { copy(new FileInputStream(a), b); } public static String collect(File a, String encoding) throws IOException { ByteArrayOutputStream out = new ByteArrayOutputStream(); copy(a, out); return new String(out.toByteArray(), encoding); } public static String collect(URL a, String encoding) throws IOException { ByteArrayOutputStream out = new ByteArrayOutputStream(); copy(a.openStream(), out); return new String(out.toByteArray(), encoding); } public static String collect(File a) throws IOException { return collect(a, "UTF-8"); } public static String collect(InputStream a, String encoding) throws IOException { ByteArrayOutputStream out = new ByteArrayOutputStream(); copy(a, out); return new String(out.toByteArray(), encoding); } public static String collect(InputStream a) throws IOException { return collect(a, "UTF-8"); } public static String collect(Reader a) throws IOException { StringWriter sw = new StringWriter(); char[] buffer = new char[10000]; int size = a.read(buffer); while (size > 0) { sw.write(buffer, 0, size); size = a.read(buffer); } return sw.toString(); } public static File getFile(File base, String file) { File f = new File(file); if (f.isAbsolute()) return f; int n; f = base.getAbsoluteFile(); while ((n = file.indexOf('/')) > 0) { String first = file.substring(0, n); file = file.substring(n + 1); if (first.equals("..")) f = f.getParentFile(); else f = new File(f, first); } if (file.equals("..")) return f.getParentFile(); else return new File(f, file).getAbsoluteFile(); } public static void delete(File f) { f = f.getAbsoluteFile(); if (f.getParentFile() == null) throw new IllegalArgumentException("Cannot recursively delete root for safety reasons"); if (f.isDirectory()) { File[] subs = f.listFiles(); for (File sub : subs) delete(sub); } f.delete(); } public static void drain(InputStream in) throws IOException { byte[] buffer = new byte[10000]; try { int size = in.read(buffer); while (size > 0) { size = in.read(buffer); } } finally { in.close(); } } public void copy(Collection c, OutputStream out) { PrintStream ps = new PrintStream(out); for (Object o : c) { ps.println(o); } ps.flush(); } public static Throwable close(Closeable in) { try { in.close(); return null; } catch (Throwable e) { return e; } } } bnd-1.50.0/aQute.libg/src/aQute/lib/putjar/0000755000175000017500000000000011656076535020166 5ustar drazzibdrazzibbnd-1.50.0/aQute.libg/src/aQute/lib/putjar/DirectoryInputStream.java0000644000175000017500000002125211656076535025173 0ustar drazzibdrazzibpackage aQute.lib.putjar; import java.io.*; import java.util.zip.*; import aQute.libg.fileiterator.*; public class DirectoryInputStream extends InputStream { final File root; final FileIterator fi; File element; int entries = 0; int state = START; long where = 0; final static int START = 0; final static int HEADER = 1; final static int DATA = 2; final static int DIRECTORY = 4; final static int EOF = 5; final static InputStream eof = new ByteArrayInputStream(new byte[0]); ByteArrayOutputStream directory = new ByteArrayOutputStream(); InputStream current = eof; public DirectoryInputStream(File dir) { root = dir; fi = new FileIterator(dir); } @Override public int read() throws IOException { if (fi == null) return -1; int c = current.read(); if (c < 0) { next(); c = current.read(); } if (c >= 0) where++; return c; } void next() throws IOException { switch (state) { case START: case DATA: nextHeader(); break; case HEADER: if (element.isFile() && element.length() > 0) { current = new FileInputStream(element); state = DATA; } else nextHeader(); break; case DIRECTORY: state = EOF; current = eof; break; case EOF: break; } } private void nextHeader() throws IOException { if (fi.hasNext()) { element = fi.next(); state = HEADER; current = getHeader(root, element); entries++; } else { current = getDirectory(); state = DIRECTORY; } } /** *
     *     end of central dir signature    4 bytes  (0x06054b50)
     *         number of this disk             2 bytes
     *         number of the disk with the
     *         start of the central directory  2 bytes
     *         total number of entries in the
     *         central directory on this disk  2 bytes
     *         total number of entries in
     *         the central directory           2 bytes
     *         size of the central directory   4 bytes
     *         offset of start of central
     *         directory with respect to
     *         the starting disk number        4 bytes
     *         .ZIP file comment length        2 bytes
     *         .ZIP file comment       (variable size)
     * 
* * @return */ InputStream getDirectory() throws IOException { long where = this.where; int sizeDirectory = directory.size(); writeInt(directory, 0x504b0506); // Signature writeShort(directory, 0); // # of disk writeShort(directory, 0); // # of the disk with start of the central // dir writeShort(directory, entries); // # of entries writeInt(directory, sizeDirectory); // Size of central dir writeInt(directory, (int) where); writeShort(directory, 0); directory.close(); byte[] data = directory.toByteArray(); return new ByteArrayInputStream(data); } private void writeShort(OutputStream out, int v) throws IOException { for (int i = 0; i < 2; i++) { out.write((byte) (v & 0xFF)); v = v >> 8; } } private void writeInt(OutputStream out, int v) throws IOException { for (int i = 0; i < 4; i++) { out.write((byte) (v & 0xFF)); v = v >> 8; } } /** * Local file header: * *
     * 
     *         local file header signature     4 bytes  (0x04034b50)
     *         version needed to extract       2 bytes
     *         general purpose bit flag        2 bytes
     *         compression method              2 bytes
     *         last mod file time              2 bytes
     *         last mod file date              2 bytes
     *         crc-32                          4 bytes
     *         compressed size                 4 bytes
     *         uncompressed size               4 bytes
     *         file name length                2 bytes
     *         extra field length              2 bytes
     * 
     *         file name (variable size)
     *         extra field (variable size)
     * 
     *     central file header signature   4 bytes  (0x02014b50)
     *         version made by                 2 bytes
     *         version needed to extract       2 bytes
     *         general purpose bit flag        2 bytes
     *         compression method              2 bytes
     *         last mod file time              2 bytes
     *         last mod file date              2 bytes
     *         crc-32                          4 bytes
     *         compressed size                 4 bytes
     *         uncompressed size               4 bytes
     *         file name length                2 bytes
     *         extra field length              2 bytes
     *         file comment length             2 bytes
     *         disk number start               2 bytes
     *         internal file attributes        2 bytes
     *         external file attributes        4 bytes
     *         relative offset of local header 4 bytes
     * 
     *         file name (variable size)
     *         extra field (variable size)
     *         file comment (variable size)
     * 
* * * @param file * @return */ private InputStream getHeader(File root, File file) throws IOException { long where = this.where; ByteArrayOutputStream bout = new ByteArrayOutputStream(); // Signature writeInt(bout, 0x04034b50); writeInt(directory, 0x504b0102); // Version needed to extract writeShort(directory, 0); // Version needed to extract writeShort(bout, 10); writeShort(directory, 10); // General purpose bit flag (use descriptor) writeShort(bout, 0); // descriptor follows data writeShort(directory, 0); // descriptor follows data // Compresson method (stored) writeShort(bout, 0); writeShort(directory, 0); // Mod time writeInt(bout, 0); writeInt(directory, 0); if (file.isDirectory()) { writeInt(bout, 0); // CRC writeInt(bout, 0); // Compressed size writeInt(bout, 0); // Uncompressed Size writeInt(directory, 0); writeInt(directory, 0); writeInt(directory, 0); } else { CRC32 crc = getCRC(file); writeInt(bout, (int) crc.getValue()); writeInt(bout, (int) file.length()); writeInt(bout, (int) file.length()); writeInt(directory, (int) crc.getValue()); writeInt(directory, (int) file.length()); writeInt(directory, (int) file.length()); } String p = getPath(root, file); if (file.isDirectory()) p = p + "/"; byte[] path = p.getBytes("UTF-8"); writeShort(bout, path.length); writeShort(directory, path.length); writeShort(bout, 0); // extra length writeShort(directory, 0); bout.write(path); writeShort(directory, 0); // File comment length writeShort(directory, 0); // disk number start 2 bytes writeShort(directory, 0); // internal file attributes 2 bytes writeInt(directory, 0); // external file attributes 4 bytes writeInt(directory, (int) where); // relative offset of local header 4 // bytes directory.write(path); byte[] bytes = bout.toByteArray(); return new ByteArrayInputStream(bytes); } private String getPath(File root, File file) { if (file.equals(root)) return ""; String p = getPath(root, file.getParentFile()); if (p.length() == 0) p = file.getName(); else { p = p + "/" + file.getName(); } return p; } private CRC32 getCRC(File file) throws IOException { CRC32 crc = new CRC32(); FileInputStream in = new FileInputStream(file); try { byte data[] = new byte[10000]; int size = in.read(data); while (size > 0) { crc.update(data, 0, size); size = in.read(data); } } finally { in.close(); } return crc; } } bnd-1.50.0/aQute.libg/src/aQute/lib/putjar/packageinfo0000644000175000017500000000001411656076535022353 0ustar drazzibdrazzibversion 1.0 bnd-1.50.0/aQute.libg/src/aQute/lib/index/0000755000175000017500000000000011656076535017770 5ustar drazzibdrazzibbnd-1.50.0/aQute.libg/src/aQute/lib/index/Index.java0000644000175000017500000001745511656076535021716 0ustar drazzibdrazzibpackage aQute.lib.index; import java.io.*; import java.nio.*; import java.nio.channels.*; import java.nio.channels.FileChannel.MapMode; import java.util.*; /** *
 *   0   ->   0, 122   -> 1
 *   123 -> 123, 244   -> 2
 *   245 -> 245, ...
 * 
* * */ public class Index implements Iterable { final static int LEAF = 0; final static int INDEX = 1; final static int SIGNATURE = 0; final static int MAGIC = 0x494C4458; final static int KEYSIZE = 4; private FileChannel file; final int pageSize = 4096; final int keySize; final int valueSize = 8; final int capacity; public Page root; final LinkedHashMap cache = new LinkedHashMap(); final MappedByteBuffer settings; private int nextPage; class Page { final int TYPE_OFFSET = 0; final int COUNT_OFFSET = 2; final static int START_OFFSET = 4; final int number; boolean leaf; final MappedByteBuffer buffer; int n = 0; boolean dirty; Page(int number) throws IOException { this.number = number; buffer = file.map(MapMode.READ_WRITE, number * pageSize, pageSize); n = buffer.getShort(COUNT_OFFSET); int type = buffer.getShort(TYPE_OFFSET); leaf = type != 0; } Page(int number, boolean leaf) throws IOException { this.number = number; this.leaf = leaf; this.n = 0; buffer = file.map(MapMode.READ_WRITE, number * pageSize, pageSize); } Iterator iterator() { return new Iterator() { Iterator i; int rover = 0; public byte[] next() { if (leaf) { return k(rover++); } return i.next(); } public boolean hasNext() { try { if (leaf) return rover < n; else { while (i == null || i.hasNext() == false) { int c = (int) c(rover++); i = getPage(c).iterator(); } return i.hasNext(); } } catch (IOException e) { throw new RuntimeException(e); } } public void remove() { throw new UnsupportedOperationException(); } }; } void write() throws IOException { buffer.putShort(COUNT_OFFSET, (short) n); buffer.put(TYPE_OFFSET, (byte) (leaf ? 1 : 0)); buffer.force(); } int compare(byte[] key, int i) { int index = pos(i); for (int j = 0; j < keySize; j++, index++) { int a = 0; if (j < key.length) a = key[j] & 0xFF; int b = buffer.get(index) & 0xFF; if (a == b) continue; return a > b ? 1 : -1; } return 0; } int pos(int i) { return START_OFFSET + size(i); } int size(int n) { return n * (keySize + valueSize); } void copyFrom(Page page, int start, int length) { copy(page.buffer, pos(start), buffer, pos(0), size(length)); } void copy(ByteBuffer src, int srcPos, ByteBuffer dst, int dstPos, int length) { if (srcPos < dstPos) { while (length-- > 0) dst.put(dstPos + length, src.get(srcPos + length)); } else { while (length-- > 0) dst.put(dstPos++, src.get(srcPos++)); } } long search(byte[] k) throws Exception { int cmp = 0; int i = n - 1; while (i >= 0 && (cmp = compare(k, i)) < 0) i--; if (leaf) { if (cmp != 0) return -1; else return c(i); } else { long value = c(i); Page child = getPage((int) value); return child.search(k); } } void insert(byte[] k, long v) throws IOException { if (n == capacity) { int t = capacity / 2; Page left = allocate(leaf); Page right = allocate(leaf); left.copyFrom(this, 0, t); left.n = t; right.copyFrom(this, t, capacity - t); right.n = capacity - t; leaf = false; set(0, left.k(0), left.number); set(1, right.k(0), right.number); n = 2; left.write(); right.write(); } insertNonFull(k, v); } byte[] k(int i) { buffer.position(pos(i)); byte[] key = new byte[keySize]; buffer.get(key); return key; } long c(int i) { if (i < 0) { System.out.println("Arghhh"); } int index = pos(i) + keySize; return buffer.getLong(index); } void set(int i, byte[] k, long v) { int index = pos(i); for (int j = 0; j < keySize; j++) { byte a = 0; if (j < k.length) a = k[j]; buffer.put(index + j, a); } buffer.putLong(index + keySize, v); } void insertNonFull(byte[] k, long v) throws IOException { int cmp = 0; int i = n - 1; while (i >= 0 && (cmp = compare(k, i)) < 0) i--; if (leaf) { if (cmp != 0) { i++; if (i != n) copy(buffer, pos(i), buffer, pos(i + 1), size(n - i)); } set(i, k, v); n++; dirty = true; } else { long value = c(i); Page child = getPage((int) value); if (child.n == capacity) { Page left = child; int t = capacity / 2; Page right = allocate(child.leaf); right.copyFrom(left, t, capacity - t); right.n = capacity - t; left.n = t; i++; // place to insert if (i < n) // ok if at end copy(buffer, pos(i), buffer, pos(i + 1), size(n - i)); set(i, right.k(0), right.number); n++; assert i < n; child = right.compare(k, 0) >= 0 ? right : left; left.dirty = true; right.dirty = true; this.dirty = true; } child.insertNonFull(k, v); } write(); } public String toString() { StringBuilder sb = new StringBuilder(); try { toString( sb, ""); } catch (IOException e) { e.printStackTrace(); } return sb.toString(); } public void toString( StringBuilder sb, String indent ) throws IOException { for (int i = 0; i < n; i++) { sb.append(String.format("%s %02d:%02d %20s %s %d\n", indent, number, i, hex(k(i), 0, 4), leaf ? "==" : "->", c(i))); if (! leaf ) { long c = c(i); Page sub = getPage((int)c); sub.toString(sb,indent+" "); } } } private String hex(byte[] k, int i, int j) { StringBuilder sb = new StringBuilder(); while ( i < j) { int b = 0xFF & k[i]; sb.append(nibble(b>>4)); sb.append(nibble(b)); i++; } return sb.toString(); } private char nibble(int i) { i = i & 0xF; return (char) ( i >= 10 ? i + 'A' - 10 : i + '0'); } } public Index(File file, int keySize) throws IOException { capacity = (pageSize - Page.START_OFFSET) / (keySize + valueSize); RandomAccessFile raf = new RandomAccessFile(file, "rw"); this.file = raf.getChannel(); settings = this.file.map(MapMode.READ_WRITE, 0, pageSize); if (this.file.size() == pageSize) { this.keySize = keySize; settings.putInt(SIGNATURE, MAGIC); settings.putInt(KEYSIZE, keySize); nextPage = 1; root = allocate(true); root.n = 1; root.set(0, new byte[KEYSIZE], 0); root.write(); } else { if (settings.getInt(SIGNATURE) != MAGIC) throw new IllegalStateException("No Index file, magic is not " + MAGIC); this.keySize = settings.getInt(KEYSIZE); if (keySize != 0 && this.keySize != keySize) throw new IllegalStateException("Invalid key size for Index file. The file is " + this.keySize + " and was expected to be " + this.keySize); root = getPage(1); nextPage = (int) (this.file.size() / pageSize); } } public void insert(byte[] k, long v) throws Exception { root.insert(k, v); } public long search(byte[] k) throws Exception { return root.search(k); } Page allocate(boolean leaf) throws IOException { Page page = new Page(nextPage++, leaf); cache.put(page.number, page); return page; } Page getPage(int number) throws IOException { Page page = cache.get(number); if (page == null) { page = new Page(number); cache.put(number, page); } return page; } public String toString() { return root.toString(); } public void close() throws IOException { file.close(); cache.clear(); } public Iterator iterator() { return root.iterator(); } } bnd-1.50.0/aQute.libg/src/aQute/lib/index/packageinfo0000644000175000017500000000001411656076535022155 0ustar drazzibdrazzibversion 1.0 bnd-1.50.0/aQute.libg/src/aQute/lib/filter/0000755000175000017500000000000011656076535020146 5ustar drazzibdrazzibbnd-1.50.0/aQute.libg/src/aQute/lib/filter/Filter.java0000755000175000017500000002600011656076535022237 0ustar drazzibdrazzib/** * Copyright (c) 2000 Gatespace AB. All Rights Reserved. * * Gatespace grants Open Services Gateway Initiative (OSGi) an irrevocable, * perpetual, non-exclusive, worldwide, paid-up right and license to * reproduce, display, perform, prepare and have prepared derivative works * based upon and distribute and sublicense this material and derivative * works thereof as set out in the OSGi MEMBER AGREEMENT as of January 24 * 2000, for use in accordance with Section 2.2 of the BY-LAWS of the * OSGi MEMBER AGREEMENT. */ package aQute.lib.filter; import java.lang.reflect.*; import java.math.*; import java.util.*; public class Filter { final char WILDCARD = 65535; final int EQ = 0; final int LE = 1; final int GE = 2; final int APPROX = 3; private String filter; abstract class Query { static final String GARBAGE = "Trailing garbage"; static final String MALFORMED = "Malformed query"; static final String EMPTY = "Empty list"; static final String SUBEXPR = "No subexpression"; static final String OPERATOR = "Undefined operator"; static final String TRUNCATED = "Truncated expression"; static final String EQUALITY = "Only equality supported"; private String tail; boolean match() throws IllegalArgumentException { tail = filter; boolean val = doQuery(); if (tail.length() > 0) error(GARBAGE); return val; } private boolean doQuery() throws IllegalArgumentException { if (tail.length() < 3 || !prefix("(")) error(MALFORMED); boolean val; switch (tail.charAt(0)) { case '&': val = doAnd(); break; case '|': val = doOr(); break; case '!': val = doNot(); break; default: val = doSimple(); break; } if (!prefix(")")) error(MALFORMED); return val; } private boolean doAnd() throws IllegalArgumentException { tail = tail.substring(1); boolean val = true; if (!tail.startsWith("(")) error(EMPTY); do { if (!doQuery()) val = false; } while (tail.startsWith("(")); return val; } private boolean doOr() throws IllegalArgumentException { tail = tail.substring(1); boolean val = false; if (!tail.startsWith("(")) error(EMPTY); do { if (doQuery()) val = true; } while (tail.startsWith("(")); return val; } private boolean doNot() throws IllegalArgumentException { tail = tail.substring(1); if (!tail.startsWith("(")) error(SUBEXPR); return !doQuery(); } private boolean doSimple() throws IllegalArgumentException { int op = 0; Object attr = getAttr(); if (prefix("=")) op = EQ; else if (prefix("<=")) op = LE; else if (prefix(">=")) op = GE; else if (prefix("~=")) op = APPROX; else error(OPERATOR); return compare(attr, op, getValue()); } private boolean prefix(String pre) { if (!tail.startsWith(pre)) return false; tail = tail.substring(pre.length()); return true; } private Object getAttr() { int len = tail.length(); int ix = 0; label: for (; ix < len; ix++) { switch (tail.charAt(ix)) { case '(': case ')': case '<': case '>': case '=': case '~': case '*': case '\\': break label; } } String attr = tail.substring(0, ix).toLowerCase(); tail = tail.substring(ix); return getProp(attr); } abstract Object getProp(String key); private String getValue() { StringBuffer sb = new StringBuffer(); int len = tail.length(); int ix = 0; label: for (; ix < len; ix++) { char c = tail.charAt(ix); switch (c) { case '(': case ')': break label; case '*': sb.append(WILDCARD); break; case '\\': if (ix == len - 1) break label; sb.append(tail.charAt(++ix)); break; default: sb.append(c); break; } } tail = tail.substring(ix); return sb.toString(); } private void error(String m) throws IllegalArgumentException { throw new IllegalArgumentException(m + " " + tail); } private boolean compare(Object obj, int op, String s) { if (obj == null) return false; try { Class numClass = obj.getClass(); if (numClass == String.class) { return compareString((String) obj, op, s); } else if (numClass == Character.class) { return compareString(obj.toString(), op, s); } else if (numClass == Long.class) { return compareSign(op, Long.valueOf(s) .compareTo((Long) obj)); } else if (numClass == Integer.class) { return compareSign(op, Integer.valueOf(s).compareTo( (Integer) obj)); } else if (numClass == Short.class) { return compareSign(op, Short.valueOf(s).compareTo( (Short) obj)); } else if (numClass == Byte.class) { return compareSign(op, Byte.valueOf(s) .compareTo((Byte) obj)); } else if (numClass == Double.class) { return compareSign(op, Double.valueOf(s).compareTo( (Double) obj)); } else if (numClass == Float.class) { return compareSign(op, Float.valueOf(s).compareTo( (Float) obj)); } else if (numClass == Boolean.class) { if (op != EQ) return false; int a = Boolean.valueOf(s).booleanValue() ? 1 : 0; int b = ((Boolean) obj).booleanValue() ? 1 : 0; return compareSign(op, a - b); } else if (numClass == BigInteger.class) { return compareSign(op, new BigInteger(s) .compareTo((BigInteger) obj)); } else if (numClass == BigDecimal.class) { return compareSign(op, new BigDecimal(s) .compareTo((BigDecimal) obj)); } else if (obj instanceof Collection) { for (Object x : (Collection) obj) if (compare(x, op, s)) return true; } else if (numClass.isArray()) { int len = Array.getLength(obj); for (int i = 0; i < len; i++) if (compare(Array.get(obj, i), op, s)) return true; } } catch (Exception e) { } return false; } } class DictQuery extends Query { private Dictionary dict; DictQuery(Dictionary dict) { this.dict = dict; } Object getProp(String key) { return dict.get(key); } } public Filter(String filter) throws IllegalArgumentException { // NYI: Normalize the filter string? this.filter = filter; if (filter == null || filter.length() == 0) throw new IllegalArgumentException("Null query"); } public boolean match(Dictionary dict) { try { return new DictQuery(dict).match(); } catch (IllegalArgumentException e) { return false; } } public String verify() { try { new DictQuery(new Hashtable()).match(); } catch (IllegalArgumentException e) { return e.getMessage(); } return null; } public String toString() { return filter; } public boolean equals(Object obj) { return obj != null && obj instanceof Filter && filter.equals(((Filter) obj).filter); } public int hashCode() { return filter.hashCode(); } boolean compareString(String s1, int op, String s2) { switch (op) { case EQ: return patSubstr(s1, s2); case APPROX: return fixupString(s2).equals(fixupString(s1)); default: return compareSign(op, s2.compareTo(s1)); } } boolean compareSign(int op, int cmp) { switch (op) { case LE: return cmp >= 0; case GE: return cmp <= 0; case EQ: return cmp == 0; default: /* APPROX */ return cmp == 0; } } String fixupString(String s) { StringBuffer sb = new StringBuffer(); int len = s.length(); boolean isStart = true; boolean isWhite = false; for (int i = 0; i < len; i++) { char c = s.charAt(i); if (Character.isWhitespace(c)) { isWhite = true; } else { if (!isStart && isWhite) sb.append(' '); if (Character.isUpperCase(c)) c = Character.toLowerCase(c); sb.append(c); isStart = false; isWhite = false; } } return sb.toString(); } boolean patSubstr(String s, String pat) { if (s == null) return false; if (pat.length() == 0) return s.length() == 0; if (pat.charAt(0) == WILDCARD) { pat = pat.substring(1); for (;;) { if (patSubstr(s, pat)) return true; if (s.length() == 0) return false; s = s.substring(1); } } else { if (s.length() == 0 || s.charAt(0) != pat.charAt(0)) return false; return patSubstr(s.substring(1), pat.substring(1)); } } } bnd-1.50.0/aQute.libg/src/aQute/lib/filter/packageinfo0000644000175000017500000000001411656076535022333 0ustar drazzibdrazzibversion 1.0 bnd-1.50.0/aQute.libg/src/aQute/libg/0000755000175000017500000000000011656076535017030 5ustar drazzibdrazzibbnd-1.50.0/aQute.libg/src/aQute/libg/log/0000755000175000017500000000000011656076535017611 5ustar drazzibdrazzibbnd-1.50.0/aQute.libg/src/aQute/libg/log/Logger.java0000755000175000017500000000047011656076535021677 0ustar drazzibdrazzibpackage aQute.libg.log; import java.util.*; public interface Logger { void error(String s, Object ... args); void warning(String s, Object ... args); void progress(String s, Object ... args); List getWarnings(); List getErrors(); List getProgress(); boolean isPedantic(); } bnd-1.50.0/aQute.libg/src/aQute/libg/log/packageinfo0000644000175000017500000000001411656076535021776 0ustar drazzibdrazzibversion 1.0 bnd-1.50.0/aQute.libg/src/aQute/libg/sax/0000755000175000017500000000000011656076535017623 5ustar drazzibdrazzibbnd-1.50.0/aQute.libg/src/aQute/libg/sax/SAXUtil.java0000644000175000017500000000155611656076535021766 0ustar drazzibdrazzibpackage aQute.libg.sax; import javax.xml.parsers.SAXParserFactory; import javax.xml.transform.Result; import javax.xml.transform.sax.SAXTransformerFactory; import javax.xml.transform.sax.TransformerHandler; import org.xml.sax.ContentHandler; import org.xml.sax.XMLReader; public class SAXUtil { public static XMLReader buildPipeline(Result output, ContentFilter... filters) throws Exception { SAXTransformerFactory factory = (SAXTransformerFactory) SAXTransformerFactory.newInstance(); TransformerHandler handler = factory.newTransformerHandler(); handler.setResult(output); ContentHandler last = handler; if (filters != null) for (ContentFilter filter : filters) { filter.setParent(last); last = filter; } XMLReader reader = SAXParserFactory.newInstance().newSAXParser().getXMLReader(); reader.setContentHandler(last); return reader; } } bnd-1.50.0/aQute.libg/src/aQute/libg/sax/SAXElement.java0000644000175000017500000000111111656076535022425 0ustar drazzibdrazzibpackage aQute.libg.sax; import org.xml.sax.Attributes; public class SAXElement { private final String uri; private final String localName; private final String qName; private final Attributes atts; public SAXElement(String uri, String localName, String qName, Attributes atts) { this.uri = uri; this.localName = localName; this.qName = qName; this.atts = atts; } public String getUri() { return uri; } public String getLocalName() { return localName; } public String getqName() { return qName; } public Attributes getAtts() { return atts; } } bnd-1.50.0/aQute.libg/src/aQute/libg/sax/filters/0000755000175000017500000000000011656076535021273 5ustar drazzibdrazzibbnd-1.50.0/aQute.libg/src/aQute/libg/sax/filters/MergeContentFilter.java0000644000175000017500000000327311656076535025703 0ustar drazzibdrazzibpackage aQute.libg.sax.filters; import java.util.Collections; import java.util.LinkedList; import java.util.List; import org.xml.sax.Attributes; import org.xml.sax.SAXException; import aQute.libg.sax.ContentFilterImpl; import aQute.libg.sax.SAXElement; public class MergeContentFilter extends ContentFilterImpl { private int elementDepth = 0; private final List rootElements = new LinkedList(); @Override public void startElement(String uri, String localName, String qName, Attributes atts) throws SAXException { if (elementDepth++ == 0) { if (rootElements.isEmpty()) super.startElement(uri, localName, qName, atts); else if (!rootElements.get(0).getqName().equals(qName)) throw new SAXException(String.format("Documents have inconsistent root element names: first was %s, current is %s.", rootElements.get(0).getqName(), qName)); rootElements.add(new SAXElement(uri, localName, qName, atts)); } else { super.startElement(uri, localName, qName, atts); } } @Override public void endElement(String uri, String localName, String qName) throws SAXException { if (--elementDepth > 0) { super.endElement(uri, localName, qName); } } @Override public void processingInstruction(String target, String data) throws SAXException { if (rootElements.isEmpty()) super.processingInstruction(target, data); } public void closeRootAndDocument() throws SAXException { if (!rootElements.isEmpty()) { SAXElement root = rootElements.get(0); super.endElement(root.getUri(), root.getLocalName(), root.getqName()); } super.endDocument(); } public List getRootElements() { return Collections.unmodifiableList(rootElements); } } bnd-1.50.0/aQute.libg/src/aQute/libg/sax/filters/ElementSelectionFilter.java0000644000175000017500000000240711656076535026546 0ustar drazzibdrazzibpackage aQute.libg.sax.filters; import org.xml.sax.Attributes; import org.xml.sax.SAXException; import aQute.libg.sax.ContentFilterImpl; public abstract class ElementSelectionFilter extends ContentFilterImpl{ int depth = 0; int hiddenDepth = -1; protected abstract boolean select(int depth, String uri, String localName, String qName, Attributes attribs); @Override public final void startElement(String uri, String localName, String qName, Attributes atts) throws SAXException { if (hiddenDepth < 0) { boolean allow = select(depth, uri, localName, qName, atts); if (allow) super.startElement(uri, localName, qName, atts); else hiddenDepth = 0; } else { hiddenDepth ++; } depth++; } @Override public final void endElement(String uri, String localName, String qName) throws SAXException { if (hiddenDepth < 0) { super.endElement(uri, localName, qName); } else { hiddenDepth --; } depth --; } @Override public void characters(char[] ch, int start, int length) throws SAXException { if (hiddenDepth < 0) super.characters(ch, start, length); } @Override public void ignorableWhitespace(char[] ch, int start, int length) throws SAXException { if (hiddenDepth < 0) super.ignorableWhitespace(ch, start, length); } } bnd-1.50.0/aQute.libg/src/aQute/libg/sax/filters/packageinfo0000644000175000017500000000001311656076535023457 0ustar drazzibdrazzibversion 1.0bnd-1.50.0/aQute.libg/src/aQute/libg/sax/packageinfo0000644000175000017500000000001311656076535022007 0ustar drazzibdrazzibversion 1.0bnd-1.50.0/aQute.libg/src/aQute/libg/sax/ContentFilterImpl.java0000644000175000017500000000322611656076535024073 0ustar drazzibdrazzibpackage aQute.libg.sax; import org.xml.sax.Attributes; import org.xml.sax.ContentHandler; import org.xml.sax.Locator; import org.xml.sax.SAXException; public class ContentFilterImpl implements ContentFilter { private ContentHandler parent; public void setParent(ContentHandler parent) { this.parent = parent; } public ContentHandler getParent() { return parent; } public void setDocumentLocator(Locator locator) { parent.setDocumentLocator(locator); } public void startDocument() throws SAXException { parent.startDocument(); } public void endDocument() throws SAXException { parent.endDocument(); } public void startPrefixMapping(String prefix, String uri) throws SAXException { parent.startPrefixMapping(prefix, uri); } public void endPrefixMapping(String prefix) throws SAXException { parent.endPrefixMapping(prefix); } public void startElement(String uri, String localName, String qName, Attributes atts) throws SAXException { parent.startElement(uri, localName, qName, atts); } public void endElement(String uri, String localName, String qName) throws SAXException { parent.endElement(uri, localName, qName); } public void characters(char[] ch, int start, int length) throws SAXException { parent.characters(ch, start, length); } public void ignorableWhitespace(char[] ch, int start, int length) throws SAXException { parent.ignorableWhitespace(ch, start, length); } public void processingInstruction(String target, String data) throws SAXException { parent.processingInstruction(target, data); } public void skippedEntity(String name) throws SAXException { parent.skippedEntity(name); } } bnd-1.50.0/aQute.libg/src/aQute/libg/sax/ContentFilter.java0000644000175000017500000000027411656076535023251 0ustar drazzibdrazzibpackage aQute.libg.sax; import org.xml.sax.ContentHandler; public interface ContentFilter extends ContentHandler { void setParent(ContentHandler parent); ContentHandler getParent(); } bnd-1.50.0/aQute.libg/src/aQute/libg/glob/0000755000175000017500000000000011656076535017753 5ustar drazzibdrazzibbnd-1.50.0/aQute.libg/src/aQute/libg/glob/Glob.java0000644000175000017500000000411211656076535021477 0ustar drazzibdrazzibpackage aQute.libg.glob; import java.util.regex.Matcher; import java.util.regex.Pattern; public class Glob { private final String glob; private final Pattern pattern; public Glob(String globString) { this.glob = globString; this.pattern = Pattern.compile(convertGlobToRegEx(globString)); } public Matcher matcher(CharSequence input) { return pattern.matcher(input); } @Override public String toString() { return glob; } private static String convertGlobToRegEx(String line) { line = line.trim(); int strLen = line.length(); StringBuilder sb = new StringBuilder(strLen); // Remove beginning and ending * globs because they're useless if (line.startsWith("*")) { line = line.substring(1); strLen--; } if (line.endsWith("*")) { line = line.substring(0, strLen - 1); strLen--; } boolean escaping = false; int inCurlies = 0; for (char currentChar : line.toCharArray()) { switch (currentChar) { case '*': if (escaping) sb.append("\\*"); else sb.append(".*"); escaping = false; break; case '?': if (escaping) sb.append("\\?"); else sb.append('.'); escaping = false; break; case '.': case '(': case ')': case '+': case '|': case '^': case '$': case '@': case '%': sb.append('\\'); sb.append(currentChar); escaping = false; break; case '\\': if (escaping) { sb.append("\\\\"); escaping = false; } else escaping = true; break; case '{': if (escaping) { sb.append("\\{"); } else { sb.append('('); inCurlies++; } escaping = false; break; case '}': if (inCurlies > 0 && !escaping) { sb.append(')'); inCurlies--; } else if (escaping) sb.append("\\}"); else sb.append("}"); escaping = false; break; case ',': if (inCurlies > 0 && !escaping) { sb.append('|'); } else if (escaping) sb.append("\\,"); else sb.append(","); break; default: escaping = false; sb.append(currentChar); } } return sb.toString(); } } bnd-1.50.0/aQute.libg/src/aQute/libg/sed/0000755000175000017500000000000011656076535017603 5ustar drazzibdrazzibbnd-1.50.0/aQute.libg/src/aQute/libg/sed/packageinfo0000644000175000017500000000001411656076535021770 0ustar drazzibdrazzibversion 1.0 bnd-1.50.0/aQute.libg/src/aQute/libg/sed/Replacer.java0000644000175000017500000000013011656076535022175 0ustar drazzibdrazzibpackage aQute.libg.sed; public interface Replacer { String process(String line); } bnd-1.50.0/aQute.libg/src/aQute/libg/sed/Sed.java0000644000175000017500000000477711656076535021200 0ustar drazzibdrazzibpackage aQute.libg.sed; import java.io.*; import java.util.*; import java.util.regex.*; public class Sed { final File file; final Replacer macro; File output; final Map replacements = new LinkedHashMap(); public Sed(Replacer macro, File file) { assert file.isFile(); this.file = file; this.macro = macro; } public void setOutput(File f) { output = f; } public void replace(String pattern, String replacement) { replacements.put(Pattern.compile(pattern), replacement); } public void doIt() throws IOException { BufferedReader brdr = new BufferedReader(new FileReader(file)); File out; if (output != null) out = output; else out = new File(file.getAbsolutePath() + ".tmp"); File bak = new File(file.getAbsolutePath() + ".bak"); PrintWriter pw = new PrintWriter(new FileWriter(out)); try { String line; while ((line = brdr.readLine()) != null) { for (Pattern p : replacements.keySet()) { String replace = replacements.get(p); Matcher m = p.matcher(line); StringBuffer sb = new StringBuffer(); while (m.find()) { String tmp = setReferences(m, replace); tmp = macro.process(tmp); m.appendReplacement(sb, Matcher.quoteReplacement(tmp)); } m.appendTail(sb); line = sb.toString(); } pw.println(line); } pw.close(); if (output == null) { file.renameTo(bak); out.renameTo(file); } } finally { brdr.close(); pw.close(); } } private String setReferences(Matcher m, String replace) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < replace.length(); i++) { char c = replace.charAt(i); if (c == '$' && i < replace.length() - 1 && Character.isDigit(replace.charAt(i + 1))) { int n = replace.charAt(i + 1) - '0'; if ( n <= m.groupCount() ) sb.append(m.group(n)); i++; } else sb.append(c); } return sb.toString(); } } bnd-1.50.0/aQute.libg/src/aQute/libg/filerepo/0000755000175000017500000000000011656076535020635 5ustar drazzibdrazzibbnd-1.50.0/aQute.libg/src/aQute/libg/filerepo/FileRepo.java0000644000175000017500000000456511656076535023217 0ustar drazzibdrazzibpackage aQute.libg.filerepo; import java.io.*; import java.util.*; import java.util.regex.*; import aQute.libg.version.*; public class FileRepo { File root; Pattern REPO_FILE = Pattern.compile("([-a-zA-z0-9_\\.]+)-([0-9\\.]+|latest)\\.(jar|lib)"); public FileRepo(File root) { this.root = root; } /** * Get a list of URLs to bundles that are constrained by the bsn and * versionRange. */ public File[] get(String bsn, final VersionRange versionRange) throws Exception { // // Check if the entry exists // File f = new File(root, bsn); if (!f.isDirectory()) return null; // // Iterator over all the versions for this BSN. // Create a sorted map over the version as key // and the file as URL as value. Only versions // that match the desired range are included in // this list. // return f.listFiles(new FilenameFilter() { public boolean accept(File dir, String name) { Matcher m = REPO_FILE.matcher(name); if (!m.matches()) return false; Version v = new Version(m.group(2)); return versionRange.includes(v); } }); } public List list(String regex) throws Exception { if (regex == null) regex = ".*"; final Pattern pattern = Pattern.compile(regex); String list[] = root.list(new FilenameFilter() { public boolean accept(File dir, String name) { Matcher matcher = pattern.matcher(name); return matcher.matches(); } }); return Arrays.asList(list); } public List versions(String bsn) throws Exception { File dir = new File(root, bsn); final List versions = new ArrayList(); dir.list(new FilenameFilter() { public boolean accept(File dir, String name) { Matcher m = REPO_FILE.matcher(name); if (m.matches()) { versions.add(new Version(m.group(2))); return true; } return false; } }); return versions; } public File get(String bsn, VersionRange range, int strategy) throws Exception { File[] files = get(bsn, range); if (files.length == 0) return null; if (files.length == 1) return files[0]; if (strategy < 0) { return files[0]; } else return files[files.length - 1]; } public File put(String bsn, Version version) { File dir = new File(bsn); dir.mkdirs(); File file = new File(dir, bsn + "-" + version.getMajor() + "." + version.getMinor() + "." + version.getMicro()); return file; } } bnd-1.50.0/aQute.libg/src/aQute/libg/filerepo/packageinfo0000644000175000017500000000001411656076535023022 0ustar drazzibdrazzibversion 1.0 bnd-1.50.0/aQute.libg/src/aQute/libg/clauses/0000755000175000017500000000000011656076535020467 5ustar drazzibdrazzibbnd-1.50.0/aQute.libg/src/aQute/libg/clauses/Clauses.java0000755000175000017500000000351711656076535022742 0ustar drazzibdrazzibpackage aQute.libg.clauses; import java.util.*; import aQute.libg.log.*; import aQute.libg.qtokens.*; public class Clauses extends LinkedHashMap>{ private static final long serialVersionUID = 1L; /** * Standard OSGi header parser. This parser can handle the format clauses * ::= clause ( ',' clause ) + clause ::= name ( ';' name ) (';' key '=' * value ) * * This is mapped to a Map { name => Map { attr|directive => value } } * * @param value * @return * @throws MojoExecutionException */ static public Clauses parse(String value, Logger logger) { if (value == null || value.trim().length() == 0) return new Clauses(); Clauses result = new Clauses(); QuotedTokenizer qt = new QuotedTokenizer(value, ";=,"); char del; do { boolean hadAttribute = false; Clause clause = new Clause(); List aliases = new ArrayList(); aliases.add(qt.nextToken()); del = qt.getSeparator(); while (del == ';') { String adname = qt.nextToken(); if ((del = qt.getSeparator()) != '=') { if (hadAttribute) throw new IllegalArgumentException( "Header contains name field after attribute or directive: " + adname + " from " + value); aliases.add(adname); } else { String advalue = qt.nextToken(); clause.put(adname, advalue); del = qt.getSeparator(); hadAttribute = true; } } for (Iterator i = aliases.iterator(); i.hasNext();) { String packageName = (String) i.next(); if (result.containsKey(packageName)) { if (logger != null) logger .warning("Duplicate package name in header: " + packageName + ". Multiple package names in one clause not supported in Bnd."); } else result.put(packageName, clause); } } while (del == ','); return result; } } bnd-1.50.0/aQute.libg/src/aQute/libg/clauses/Clause.java0000755000175000017500000000024211656076535022547 0ustar drazzibdrazzibpackage aQute.libg.clauses; import java.util.*; public class Clause extends LinkedHashMap { private static final long serialVersionUID = 1L; } bnd-1.50.0/aQute.libg/src/aQute/libg/clauses/packageinfo0000644000175000017500000000001411656076535022654 0ustar drazzibdrazzibversion 1.0 bnd-1.50.0/aQute.libg/src/aQute/libg/clauses/Selector.java0000755000175000017500000000611411656076535023117 0ustar drazzibdrazzib/* * $Header: /cvsroot/bnd/aQute.libg/src/aQute/libg/clauses/Selector.java,v 1.1 2009/01/19 14:17:42 pkriens Exp $ * * Copyright (c) OSGi Alliance (2006). All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package aQute.libg.clauses; import java.util.*; import java.util.regex.*; public class Selector { Pattern pattern; String instruction; boolean negated; Clause clause; public Selector(String instruction, boolean negated) { this.instruction = instruction; this.negated = negated; } public boolean matches(String value) { if (pattern == null) { pattern = Pattern.compile(instruction); } Matcher m = pattern.matcher(value); return m.matches(); } public boolean isNegated() { return negated; } public String getPattern() { return instruction; } /** * Convert a string based pattern to a regular expression based pattern. * This is called an instruction, this object makes it easier to handle the * different cases * * @param string * @return */ public static Selector getPattern(String string) { boolean negated = false; if (string.startsWith("!")) { negated = true; string = string.substring(1); } StringBuffer sb = new StringBuffer(); for (int c = 0; c < string.length(); c++) { switch (string.charAt(c)) { case '.': sb.append("\\."); break; case '*': sb.append(".*"); break; case '?': sb.append(".?"); break; default: sb.append(string.charAt(c)); break; } } string = sb.toString(); if (string.endsWith("\\..*")) { sb.append("|"); sb.append(string.substring(0, string.length() - 4)); } return new Selector(sb.toString(), negated); } public String toString() { return getPattern(); } public Clause getClause() { return clause; } public void setClause(Clause clause) { this.clause = clause; } public static List getInstructions(Clauses clauses) { List result = new ArrayList(); for (Map.Entry> entry : clauses.entrySet()) { Selector instruction = getPattern(entry.getKey()); result.add(instruction); } return result; } public static List select(Collection domain, List instructions) { List result = new ArrayList(); Iterator iterator = domain.iterator(); value: while (iterator.hasNext()) { T value = iterator.next(); for (Selector instruction : instructions) { if (instruction.matches(value.toString())) { if (!instruction.isNegated()) result.add(value); continue value; } } } return result; } } bnd-1.50.0/aQute.libg/src/aQute/libg/fileiterator/0000755000175000017500000000000011656076535021521 5ustar drazzibdrazzibbnd-1.50.0/aQute.libg/src/aQute/libg/fileiterator/packageinfo0000644000175000017500000000001411656076535023706 0ustar drazzibdrazzibversion 1.0 bnd-1.50.0/aQute.libg/src/aQute/libg/fileiterator/FileIterator.java0000644000175000017500000000213511656076535024756 0ustar drazzibdrazzibpackage aQute.libg.fileiterator; import java.io.*; import java.util.*; public class FileIterator implements Iterator { File dir; int n = 0; FileIterator next; public FileIterator(File nxt) { assert nxt.isDirectory(); this.dir = nxt; } public boolean hasNext() { if (next != null) return next.hasNext(); else return n < dir.list().length; } public File next() { if (next != null) { File answer = next.next(); if (!next.hasNext()) next = null; return answer; } else { File nxt = dir.listFiles()[n++]; if (nxt.isDirectory()) { next = new FileIterator(nxt); return nxt; } else if (nxt.isFile()) { return nxt; } else throw new IllegalStateException("File disappeared"); } } public void remove() { throw new UnsupportedOperationException( "Cannot remove from a file iterator"); } } bnd-1.50.0/aQute.libg/src/aQute/libg/map/0000755000175000017500000000000011656076535017605 5ustar drazzibdrazzibbnd-1.50.0/aQute.libg/src/aQute/libg/map/MAP.java0000644000175000017500000000062411656076535021067 0ustar drazzibdrazzibpackage aQute.libg.map; import java.util.*; public class MAP { static public class MAPX extends LinkedHashMap { private static final long serialVersionUID = 1L; public MAPX $(K key, V value) { put(key, value); return this; } } public static MAPX $(Kx key, Vx value) { MAPX map = new MAPX(); map.put(key, value); return map; } }bnd-1.50.0/aQute.libg/src/aQute/libg/filelock/0000755000175000017500000000000011656076535020620 5ustar drazzibdrazzibbnd-1.50.0/aQute.libg/src/aQute/libg/filelock/DirectoryLock.java0000644000175000017500000000117111656076535024240 0ustar drazzibdrazzibpackage aQute.libg.filelock; import java.io.*; public class DirectoryLock { final File lock; final long timeout; final public static String LOCKNAME = ".lock"; public DirectoryLock(File directory, long timeout) { this.lock = new File(directory, LOCKNAME); this.lock.deleteOnExit(); this.timeout = timeout; } public void release() { lock.delete(); } public void lock() throws InterruptedException { if (lock.mkdir()) return; long deadline = System.currentTimeMillis()+ timeout; while ( System.currentTimeMillis() < deadline) { if (lock.mkdir()) return; Thread.sleep(50); } } } bnd-1.50.0/aQute.libg/src/aQute/libg/dumpzip/0000755000175000017500000000000011656076535020520 5ustar drazzibdrazzibbnd-1.50.0/aQute.libg/src/aQute/libg/dumpzip/DumpZip.java0000644000175000017500000000015011656076535022747 0ustar drazzibdrazzibpackage aQute.libg.dumpzip; import java.io.*; public class DumpZip { PrintStream out; } bnd-1.50.0/aQute.libg/src/aQute/libg/dumpzip/packageinfo0000644000175000017500000000001411656076535022705 0ustar drazzibdrazzibversion 1.0 bnd-1.50.0/aQute.libg/src/aQute/libg/reporter/0000755000175000017500000000000011656076535020672 5ustar drazzibdrazzibbnd-1.50.0/aQute.libg/src/aQute/libg/reporter/Reporter.java0000755000175000017500000000051011656076535023336 0ustar drazzibdrazzibpackage aQute.libg.reporter; import java.util.*; public interface Reporter { void error(String s, Object ... args); void warning(String s, Object ... args); void progress(String s, Object ... args); void trace(String s, Object ... args); List getWarnings(); List getErrors(); boolean isPedantic(); } bnd-1.50.0/aQute.libg/src/aQute/libg/reporter/packageinfo0000644000175000017500000000001411656076535023057 0ustar drazzibdrazzibversion 1.0 bnd-1.50.0/aQute.libg/src/aQute/libg/qtokens/0000755000175000017500000000000011656076535020514 5ustar drazzibdrazzibbnd-1.50.0/aQute.libg/src/aQute/libg/qtokens/QuotedTokenizer.java0000755000175000017500000000451411656076535024522 0ustar drazzibdrazzibpackage aQute.libg.qtokens; import java.util.*; import aQute.libg.generics.*; public class QuotedTokenizer { String string; int index = 0; String separators; boolean returnTokens; boolean ignoreWhiteSpace = true; String peek; char separator; public QuotedTokenizer(String string, String separators, boolean returnTokens ) { if ( string == null ) throw new IllegalArgumentException("string argument must be not null"); this.string = string; this.separators = separators; this.returnTokens = returnTokens; } public QuotedTokenizer(String string, String separators) { this(string,separators,false); } public String nextToken(String separators) { separator = 0; if ( peek != null ) { String tmp = peek; peek = null; return tmp; } if ( index == string.length()) return null; StringBuffer sb = new StringBuffer(); while (index < string.length()) { char c = string.charAt(index++); if ( Character.isWhitespace(c)) { if ( index == string.length()) break; else { sb.append(c); continue; } } if (separators.indexOf(c) >= 0) { if (returnTokens) peek = Character.toString(c); else separator = c; break; } switch (c) { case '"' : case '\'' : quotedString(sb, c); break; default : sb.append(c); } } String result = sb.toString().trim(); if ( result.length()==0 && index==string.length()) return null; return result; } public String nextToken() { return nextToken(separators); } private void quotedString(StringBuffer sb, char c) { char quote = c; while (index < string.length()) { c = string.charAt(index++); if (c == quote) break; if (c == '\\' && index < string.length() && string.charAt(index + 1) == quote) c = string.charAt(index++); sb.append(c); } } public String[] getTokens() { return getTokens(0); } private String [] getTokens(int cnt){ String token = nextToken(); if ( token == null ) return new String[cnt]; String result[] = getTokens(cnt+1); result[cnt]=token; return result; } public char getSeparator() { return separator; } public List getTokenSet() { List list = Create.list(); String token = nextToken(); while ( token != null ) { list.add(token); token = nextToken(); } return list; } } bnd-1.50.0/aQute.libg/src/aQute/libg/qtokens/packageinfo0000644000175000017500000000001411656076535022701 0ustar drazzibdrazzibversion 1.0 bnd-1.50.0/aQute.libg/src/aQute/libg/version/0000755000175000017500000000000011656076535020515 5ustar drazzibdrazzibbnd-1.50.0/aQute.libg/src/aQute/libg/version/VersionRange.java0000755000175000017500000000321611656076535023767 0ustar drazzibdrazzibpackage aQute.libg.version; import java.util.regex.*; public class VersionRange { Version high; Version low; char start = '['; char end = ']'; static Pattern RANGE = Pattern.compile("(\\(|\\[)\\s*(" + Version.VERSION_STRING + ")\\s*,\\s*(" + Version.VERSION_STRING + ")\\s*(\\)|\\])"); public VersionRange(String string) { string = string.trim(); Matcher m = RANGE.matcher(string); if (m.matches()) { start = m.group(1).charAt(0); String v1 = m.group(2); String v2 = m.group(10); low = new Version(v1); high = new Version(v2); end = m.group(18).charAt(0); if (low.compareTo(high) > 0) throw new IllegalArgumentException( "Low Range is higher than High Range: " + low + "-" + high); } else high = low = new Version(string); } public boolean isRange() { return high != low; } public boolean includeLow() { return start == '['; } public boolean includeHigh() { return end == ']'; } public String toString() { if (high == low) return high.toString(); StringBuffer sb = new StringBuffer(); sb.append(start); sb.append(low); sb.append(','); sb.append(high); sb.append(end); return sb.toString(); } public Version getLow() { return low; } public Version getHigh() { return high; } public boolean includes(Version v) { if ( !isRange() ) { return low.compareTo(v) <=0; } if (includeLow()) { if (v.compareTo(low) < 0) return false; } else if (v.compareTo(low) <= 0) return false; if (includeHigh()) { if (v.compareTo(high) > 0) return false; } else if (v.compareTo(high) >= 0) return false; return true; } }bnd-1.50.0/aQute.libg/src/aQute/libg/version/packageinfo0000644000175000017500000000001411656076535022702 0ustar drazzibdrazzibversion 1.0 bnd-1.50.0/aQute.libg/src/aQute/libg/version/Version.java0000755000175000017500000001014411656076535023010 0ustar drazzibdrazzibpackage aQute.libg.version; import java.util.regex.*; public class Version implements Comparable { final int major; final int minor; final int micro; final String qualifier; public final static String VERSION_STRING = "(\\d+)(\\.(\\d+)(\\.(\\d+)(\\.([-_\\da-zA-Z]+))?)?)?"; public final static Pattern VERSION = Pattern .compile(VERSION_STRING); public final static Version LOWEST = new Version(); public final static Version HIGHEST = new Version(Integer.MAX_VALUE, Integer.MAX_VALUE, Integer.MAX_VALUE, "\uFFFF"); public static final Version emptyVersion = LOWEST; public Version() { this(0); } public Version(int major, int minor, int micro, String qualifier) { this.major = major; this.minor = minor; this.micro = micro; this.qualifier = qualifier; } public Version(int major, int minor, int micro) { this(major, minor, micro, null); } public Version(int major, int minor) { this(major, minor, 0, null); } public Version(int major) { this(major, 0, 0, null); } public Version(String version) { Matcher m = VERSION.matcher(version); if (!m.matches()) throw new IllegalArgumentException("Invalid syntax for version: " + version); major = Integer.parseInt(m.group(1)); if (m.group(3) != null) minor = Integer.parseInt(m.group(3)); else minor = 0; if (m.group(5) != null) micro = Integer.parseInt(m.group(5)); else micro = 0; qualifier = m.group(7); } public int getMajor() { return major; } public int getMinor() { return minor; } public int getMicro() { return micro; } public String getQualifier() { return qualifier; } public int compareTo(Version other) { if (other == this) return 0; if (!(other instanceof Version)) throw new IllegalArgumentException( "Can only compare versions to versions"); Version o = (Version) other; if (major != o.major) return major - o.major; if (minor != o.minor) return minor - o.minor; if (micro != o.micro) return micro - o.micro; int c = 0; if (qualifier != null) c = 1; if (o.qualifier != null) c += 2; switch (c) { case 0: return 0; case 1: return 1; case 2: return -1; } return qualifier.compareTo(o.qualifier); } public String toString() { StringBuffer sb = new StringBuffer(); sb.append(major); sb.append("."); sb.append(minor); sb.append("."); sb.append(micro); if (qualifier != null) { sb.append("."); sb.append(qualifier); } return sb.toString(); } public boolean equals(Object ot) { if ( ! (ot instanceof Version)) return false; return compareTo((Version)ot) == 0; } public int hashCode() { return major * 97 ^ minor * 13 ^ micro + (qualifier == null ? 97 : qualifier.hashCode()); } public int get(int i) { switch(i) { case 0 : return major; case 1 : return minor; case 2 : return micro; default: throw new IllegalArgumentException("Version can only get 0 (major), 1 (minor), or 2 (micro)"); } } public static Version parseVersion(String version) { if (version == null) { return LOWEST; } version = version.trim(); if (version.length() == 0) { return LOWEST; } return new Version(version); } } bnd-1.50.0/aQute.libg/src/aQute/libg/classdump/0000755000175000017500000000000011656076535021023 5ustar drazzibdrazzibbnd-1.50.0/aQute.libg/src/aQute/libg/classdump/ClassDumper.java0000755000175000017500000006063111656076535024121 0ustar drazzibdrazzib/* Copyright 2006 aQute SARL * Licensed under the Apache License, Version 2.0, see http://www.apache.org/licenses/LICENSE-2.0 */ package aQute.libg.classdump; import java.io.*; import java.lang.reflect.*; public class ClassDumper { /** *
     * ACC_PUBLIC 0x0001 Declared public; may be accessed from outside its
     * package. 
     * ACC_FINAL 0x0010 Declared final; no subclasses allowed.
     * ACC_SUPER 0x0020 Treat superclass methods specially when invoked by the
     * invokespecial instruction. 
     * ACC_INTERFACE 0x0200 Is an interface, not a
     * class. 
     * ACC_ABSTRACT 0x0400 Declared abstract; may not be instantiated.
     * 
* * @param mod */ final static int ACC_PUBLIC = 0x0001; // Declared public; may be accessed // from outside its package. final static int ACC_FINAL = 0x0010; // Declared final; no subclasses // allowed. final static int ACC_SUPER = 0x0020; // Treat superclass methods // specially when invoked by the // invokespecial instruction. final static int ACC_INTERFACE = 0x0200; // Is an interface, not a classs final static int ACC_ABSTRACT = 0x0400; // Declared abstract; may not be // instantiated. final static protected class Assoc { Assoc(byte tag, int a, int b) { this.tag = tag; this.a = a; this.b = b; } byte tag; int a; int b; } final String path; final static String NUM_COLUMN = "%-30s %d\n"; final static String HEX_COLUMN = "%-30s %x\n"; final static String STR_COLUMN = "%-30s %s\n"; PrintStream ps = System.out; Object[] pool; InputStream in; public ClassDumper(String path) throws Exception { this(path, new FileInputStream(new File(path))); } public ClassDumper(String path, InputStream in) throws IOException { this.path = path; this.in = in; } public void dump(PrintStream ps) throws Exception { if (ps != null) this.ps = ps; DataInputStream din = new DataInputStream(in); parseClassFile(din); din.close(); } void parseClassFile(DataInputStream in) throws IOException { int magic = in.readInt(); if (magic != 0xCAFEBABE) throw new IOException("Not a valid class file (no CAFEBABE header)"); ps.printf(HEX_COLUMN, "magic", magic); int minor = in.readUnsignedShort(); // minor version int major = in.readUnsignedShort(); // major version ps.printf(STR_COLUMN, "version", "" + major + "." + minor); int pool_size = in.readUnsignedShort(); ps.printf(NUM_COLUMN, "pool size", pool_size); pool = new Object[pool_size]; process: for (int poolIndex = 1; poolIndex < pool_size; poolIndex++) { byte tag = in.readByte(); switch (tag) { case 0: ps.printf("%30d tag (0)\n", poolIndex); break process; case 1: String name = in.readUTF(); pool[poolIndex] = name; ps.printf("%30d tag(1) utf8 '%s'\n", poolIndex, name); break; case 2: throw new IOException("Invalid tag " + tag); case 3: int i = in.readInt(); pool[poolIndex] = new Integer(i); ps.printf("%30d tag(3) int %s\n", poolIndex, i); break; case 4: float f = in.readFloat(); pool[poolIndex] = new Float(f); ps.printf("%30d tag(4) float %s\n", poolIndex, f); break; // For some insane optimization reason are // the long and the double two entries in the // constant pool. See 4.4.5 case 5: long l = in.readLong(); pool[poolIndex] = new Long(l); ps.printf("%30d tag(5) long %s\n", poolIndex, l); poolIndex++; break; case 6: double d = in.readDouble(); pool[poolIndex] = new Double(d); ps.printf("%30d tag(6) double %s\n", poolIndex, d); poolIndex++; break; case 7: int class_index = in.readUnsignedShort(); pool[poolIndex] = new Integer(class_index); ps.printf("%30d tag(7) constant classs %d\n", poolIndex, class_index); break; case 8: int string_index = in.readUnsignedShort(); pool[poolIndex] = new Integer(string_index); ps.printf("%30d tag(8) constant string %d\n", poolIndex, string_index); break; case 9: // Field ref class_index = in.readUnsignedShort(); int name_and_type_index = in.readUnsignedShort(); pool[poolIndex] = new Assoc((byte) 9, class_index, name_and_type_index); ps.printf("%30d tag(9) field ref %d/%d\n", poolIndex, class_index, name_and_type_index); break; case 10: // Method ref class_index = in.readUnsignedShort(); name_and_type_index = in.readUnsignedShort(); pool[poolIndex] = new Assoc((byte) 10, class_index, name_and_type_index); ps.printf("%30d tag(10) method ref %d/%d\n", poolIndex, class_index, name_and_type_index); break; case 11: // Interface and Method ref class_index = in.readUnsignedShort(); name_and_type_index = in.readUnsignedShort(); pool[poolIndex] = new Assoc((byte) 11, class_index, name_and_type_index); ps.printf("%30d tag(11) interface and method ref %d/%d\n", poolIndex, class_index, name_and_type_index); break; // Name and Type case 12: int name_index = in.readUnsignedShort(); int descriptor_index = in.readUnsignedShort(); pool[poolIndex] = new Assoc(tag, name_index, descriptor_index); ps.printf("%30d tag(12) name and type %d/%d\n", poolIndex, name_index, descriptor_index); break; default: throw new IllegalArgumentException("Unknown tag: " + tag); } } int access = in.readUnsignedShort(); // access printAccess(access); int this_class = in.readUnsignedShort(); int super_class = in.readUnsignedShort(); ps.printf("%-30s %x %s(#%d)\n", "this_class", access, pool[this_class], this_class); ps.printf("%-30s %s(#%d)\n", "super_class", pool[super_class], super_class); int interfaces_count = in.readUnsignedShort(); ps.printf(NUM_COLUMN, "interface count", interfaces_count); for (int i = 0; i < interfaces_count; i++) { int interface_index = in.readUnsignedShort(); ps.printf("%-30s interface %s(#%d)", "interface count", pool[interface_index], interfaces_count); } int field_count = in.readUnsignedShort(); ps.printf(NUM_COLUMN, "field count", field_count); for (int i = 0; i < field_count; i++) { access = in.readUnsignedShort(); // access printAccess(access); int name_index = in.readUnsignedShort(); int descriptor_index = in.readUnsignedShort(); ps.printf("%-30s %x %s(#%d) %s(#%d)\n", "field def", access, pool[name_index], name_index, pool[descriptor_index], descriptor_index); doAttributes(in, " "); } int method_count = in.readUnsignedShort(); ps.printf(NUM_COLUMN, "method count", method_count); for (int i = 0; i < method_count; i++) { int access_flags = in.readUnsignedShort(); printAccess(access_flags); int name_index = in.readUnsignedShort(); int descriptor_index = in.readUnsignedShort(); ps.printf("%-30s %x %s(#%d) %s(#%d)\n", "method def", access_flags, pool[name_index], name_index, pool[descriptor_index], descriptor_index); doAttributes(in, " "); } doAttributes(in, ""); if (in.read() >= 0) ps.printf("Extra bytes follow ..."); } /** * Called for each attribute in the class, field, or method. * * @param in * The stream * @throws IOException */ private void doAttributes(DataInputStream in, String indent) throws IOException { int attribute_count = in.readUnsignedShort(); ps.printf(NUM_COLUMN, indent + "attribute count", attribute_count); for (int j = 0; j < attribute_count; j++) { doAttribute(in, indent + j + ": "); } } /** * Process a single attribute, if not recognized, skip it. * * @param in * the data stream * @throws IOException */ private void doAttribute(DataInputStream in, String indent) throws IOException { int attribute_name_index = in.readUnsignedShort(); long attribute_length = in.readInt(); attribute_length &= 0xFFFF; String attributeName = (String) pool[attribute_name_index]; ps.printf("%-30s %s(#%d)\n", indent + "attribute", attributeName, attribute_name_index); if ("RuntimeVisibleAnnotations".equals(attributeName)) doAnnotations(in, indent); else if ("SourceFile".equals(attributeName)) doSourceFile(in, indent); else if ("Code".equals(attributeName)) doCode(in, indent); else if ("LineNumberTable".equals(attributeName)) doLineNumberTable(in, indent); else if ("LocalVariableTable".equals(attributeName)) doLocalVariableTable(in, indent); else if ("InnerClasses".equals(attributeName)) doInnerClasses(in, indent); else if ("Exceptions".equals(attributeName)) doExceptions(in, indent); else if ("EnclosingMethod".equals(attributeName)) doEnclosingMethod(in, indent); else if ("Signature".equals(attributeName)) doSignature(in, indent); else if ("Synthetic".equals(attributeName)) ; // Is empty! else if ("Deprecated".equals(attributeName)) ; // Is Empty else { ps.printf("%-30s %d\n", indent + "Unknown attribute, skipping", attribute_length); if (attribute_length > 0x7FFFFFFF) { throw new IllegalArgumentException("Attribute > 2Gb"); } byte buffer[] = new byte[(int) attribute_length]; in.readFully(buffer); printHex(buffer); } } /** *
     * Signature_attribute {
     * 	u2 attribute_name_index;
     * 	u4 attribute_length;
     * 	u2 signature_index;
     * 	}
     * 
* * @param in * @param indent */ void doSignature(DataInputStream in, String indent) throws IOException { int signature_index = in.readUnsignedShort(); ps.printf("%-30s %s(#%d)\n", indent + "signature", pool[signature_index], signature_index); } /** *
     * EnclosingMethod_attribute {
     * 	u2 attribute_name_index;
     * 	u4 attribute_length;
     * 	u2 class_index
     * 	u2 method_index;
     * 	}
     * 	
     * 
*/ void doEnclosingMethod(DataInputStream in, String indent) throws IOException { int class_index = in.readUnsignedShort(); int method_index = in.readUnsignedShort(); ps.printf("%-30s %s(#%d/c) %s(#%d)\n", indent + "enclosing method", pool[((Integer) pool[class_index]).intValue()], class_index, (method_index == 0 ? "<>" : pool[method_index])); } /** *
     *  Exceptions_attribute {
     * 		u2 attribute_name_index;
     * 		u4 attribute_length;
     * 		u2 number_of_exceptions;
     * 		u2 exception_index_table[number_of_exceptions];
     * 	}
     * 
* * @param in * @param indent */ private void doExceptions(DataInputStream in, String indent) throws IOException { int number_of_exceptions = in.readUnsignedShort(); ps.printf(NUM_COLUMN, indent + "number of exceptions", number_of_exceptions); StringBuffer sb = new StringBuffer(); String del = ""; for (int i = 0; i < number_of_exceptions; i++) { int exception_index_table = in.readUnsignedShort(); sb.append(del); sb.append(pool[((Integer) pool[exception_index_table])]); sb.append("(#"); sb.append(exception_index_table); sb.append("/c)"); del = ", "; } ps.printf("%-30s %d: %s\n", indent + "exceptions", number_of_exceptions, sb); } /** *
     * Code_attribute {
     * 		u2 attribute_name_index;
     * 		u4 attribute_length;
     * 		u2 max_stack;
     * 		u2 max_locals;
     * 		u4 code_length;
     * 		u1 code[code_length];
     * 		u2 exception_table_length;
     * 		{    	u2 start_pc;
     * 		      	u2 end_pc;
     * 		      	u2  handler_pc;
     * 		      	u2  catch_type;
     * 		}	exception_table[exception_table_length];
     * 		u2 attributes_count;
     * 		attribute_info attributes[attributes_count];
     * 	}
     * 
* * @param in * @param pool * @throws IOException */ private void doCode(DataInputStream in, String indent) throws IOException { int max_stack = in.readUnsignedShort(); int max_locals = in.readUnsignedShort(); int code_length = in.readInt(); ps.printf(NUM_COLUMN, indent + "max_stack", max_stack); ps.printf(NUM_COLUMN, indent + "max_locals", max_locals); ps.printf(NUM_COLUMN, indent + "code_length", code_length); byte code[] = new byte[code_length]; in.readFully(code); printHex(code); int exception_table_length = in.readUnsignedShort(); ps.printf(NUM_COLUMN, indent + "exception_table_length", exception_table_length); for (int i = 0; i < exception_table_length; i++) { int start_pc = in.readUnsignedShort(); int end_pc = in.readUnsignedShort(); int handler_pc = in.readUnsignedShort(); int catch_type = in.readUnsignedShort(); ps.printf("%-30s %d/%d/%d/%d\n", indent + "exception_table", start_pc, end_pc, handler_pc, catch_type); } doAttributes(in, indent + " "); } /** * We must find Class.forName references ... * * @param code */ protected void printHex(byte[] code) { int index = 0; while (index < code.length) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < 16 && index < code.length; i++) { String s = Integer.toHexString((0xFF & code[index++])) .toUpperCase(); if (s.length() == 1) sb.append("0"); sb.append(s); sb.append(" "); } ps.printf(STR_COLUMN, "", sb.toString()); } } private void doSourceFile(DataInputStream in, String indent) throws IOException { int sourcefile_index = in.readUnsignedShort(); ps.printf("%-30s %s(#%d)\n", indent + "Source file", pool[sourcefile_index], sourcefile_index); } private void doAnnotations(DataInputStream in, String indent) throws IOException { int num_annotations = in.readUnsignedShort(); // # of annotations ps .printf(NUM_COLUMN, indent + "Number of annotations", num_annotations); for (int a = 0; a < num_annotations; a++) { doAnnotation(in, indent); } } private void doAnnotation(DataInputStream in, String indent) throws IOException { int type_index = in.readUnsignedShort(); ps.printf("%-30s %s(#%d)", indent + "type", pool[type_index], type_index); int num_element_value_pairs = in.readUnsignedShort(); ps.printf(NUM_COLUMN, indent + "num_element_value_pairs", num_element_value_pairs); for (int v = 0; v < num_element_value_pairs; v++) { int element_name_index = in.readUnsignedShort(); ps.printf(NUM_COLUMN, indent + "element_name_index", element_name_index); doElementValue(in, indent); } } private void doElementValue(DataInputStream in, String indent) throws IOException { int tag = in.readUnsignedByte(); switch (tag) { case 'B': case 'C': case 'D': case 'F': case 'I': case 'J': case 'S': case 'Z': case 's': int const_value_index = in.readUnsignedShort(); ps.printf("%-30s %c %s(#%d)\n", indent + "element value", tag, pool[const_value_index], const_value_index); break; case 'e': int type_name_index = in.readUnsignedShort(); int const_name_index = in.readUnsignedShort(); ps.printf("%-30s %c %s(#%d) %s(#%d)\n", indent + "type+const", tag, pool[type_name_index], type_name_index, pool[const_name_index], const_name_index); break; case 'c': int class_info_index = in.readUnsignedShort(); ps.printf("%-30s %c %s(#%d)\n", indent + "element value", tag, pool[class_info_index], class_info_index); break; case '@': ps.printf("%-30s %c\n", indent + "sub annotation", tag); doAnnotation(in, indent); break; case '[': int num_values = in.readUnsignedShort(); ps.printf("%-30s %c num_values=%d\n", indent + "sub element value", tag, num_values); for (int i = 0; i < num_values; i++) { doElementValue(in, indent); } break; default: throw new IllegalArgumentException( "Invalid value for Annotation ElementValue tag " + tag); } } /** *
     *  LineNumberTable_attribute {
     * 		u2 attribute_name_index;
     * 		u4 attribute_length;
     * 		u2 line_number_table_length;
     * 		{  u2 start_pc;	     
     * 		   u2 line_number;	     
     * 		} line_number_table[line_number_table_length];
     * 	}
     * 	
     * 
*/ void doLineNumberTable(DataInputStream in, String indent) throws IOException { int line_number_table_length = in.readUnsignedShort(); ps.printf(NUM_COLUMN, indent + "line number table length", line_number_table_length); StringBuffer sb = new StringBuffer(); for (int i = 0; i < line_number_table_length; i++) { int start_pc = in.readUnsignedShort(); int line_number = in.readUnsignedShort(); sb.append(start_pc); sb.append("/"); sb.append(line_number); sb.append(" "); } ps.printf("%-30s %d: %s\n", indent + "line number table", line_number_table_length, sb); } /** * *
     * 	LocalVariableTable_attribute {
     * 		u2 attribute_name_index;
     * 		u4 attribute_length;
     * 		u2 local_variable_table_length;
     * 		{  u2 start_pc;
     * 		    u2 length;
     * 		    u2 name_index;
     * 		    u2 descriptor_index;
     * 		    u2 index;
     * 		} local_variable_table[local_variable_table_length];
     * 	}	
     * 
*/ void doLocalVariableTable(DataInputStream in, String indent) throws IOException { int local_variable_table_length = in.readUnsignedShort(); ps.printf(NUM_COLUMN, indent + "local variable table length", local_variable_table_length); for (int i = 0; i < local_variable_table_length; i++) { int start_pc = in.readUnsignedShort(); int length = in.readUnsignedShort(); int name_index = in.readUnsignedShort(); int descriptor_index = in.readUnsignedShort(); int index = in.readUnsignedShort(); ps.printf("%-30s %d: %d/%d %s(#%d) %s(#%d)\n", indent, index, start_pc, length, pool[name_index], name_index, pool[descriptor_index], descriptor_index); } } /** *
     *    InnerClasses_attribute {
     * 		u2 attribute_name_index;
     * 		u4 attribute_length;
     * 		u2 number_of_classes;
     * 		{  u2 inner_class_info_index;	     
     * 		   u2 outer_class_info_index;	     
     * 		   u2 inner_name_index;	     
     * 		   u2 inner_class_access_flags;	     
     * 		} classes[number_of_classes];
     * 	}
     * 
* */ void doInnerClasses(DataInputStream in, String indent) throws IOException { int number_of_classes = in.readUnsignedShort(); ps.printf(NUM_COLUMN, indent + "number of classes", number_of_classes); for (int i = 0; i < number_of_classes; i++) { int inner_class_info_index = in.readUnsignedShort(); int outer_class_info_index = in.readUnsignedShort(); int inner_name_index = in.readUnsignedShort(); int inner_class_access_flags = in.readUnsignedShort(); printAccess(inner_class_access_flags); String iname = "<>"; String oname = iname; if (inner_class_info_index != 0) iname = (String) pool[((Integer) pool[inner_class_info_index]) .intValue()]; if (outer_class_info_index != 0) oname = (String) pool[((Integer) pool[outer_class_info_index]) .intValue()]; ps.printf("%-30s %d: %x %s(#%d/c) %s(#%d/c) %s(#%d) \n", indent, i, inner_class_access_flags, iname, inner_class_info_index, oname, outer_class_info_index, pool[inner_name_index], inner_name_index); } } void printClassAccess(int mod) { ps.printf("%-30s", "Class Access"); if ((ACC_PUBLIC&mod)!= 0) ps.print(" public"); if ((ACC_FINAL&mod)!= 0) ps.print(" final"); if ((ACC_SUPER&mod)!= 0) ps.print(" super"); if ((ACC_INTERFACE&mod)!= 0) ps.print(" interface"); if ((ACC_ABSTRACT&mod)!= 0) ps.print(" abstract"); ps.println(); } void printAccess(int mod) { ps.printf("%-30s", "Access"); if (Modifier.isStatic(mod)) ps.print(" static"); if (Modifier.isAbstract(mod)) ps.print(" abstract"); if (Modifier.isPublic(mod)) ps.print(" public"); if (Modifier.isFinal(mod)) ps.print(" final"); if (Modifier.isInterface(mod)) ps.print(" interface"); if (Modifier.isNative(mod)) ps.print(" native"); if (Modifier.isPrivate(mod)) ps.print(" private"); if (Modifier.isProtected(mod)) ps.print(" protected"); if (Modifier.isStrict(mod)) ps.print(" strict"); if (Modifier.isSynchronized(mod)) ps.print(" synchronized"); if (Modifier.isTransient(mod)) ps.print(" transient"); if (Modifier.isVolatile(mod)) ps.print(" volatile"); ps.println(); } public static void main(String args[]) throws Exception { if (args.length == 0) { System.err.println("clsd +"); } for (int i = 0; i < args.length; i++) { File f = new File(args[i]); if (!f.isFile()) System.err.println("File does not exist or is directory " + f); else { ClassDumper cd = new ClassDumper(args[i]); cd.dump(null); } } } } bnd-1.50.0/aQute.libg/src/aQute/libg/classdump/packageinfo0000644000175000017500000000001411656076535023210 0ustar drazzibdrazzibversion 1.0 bnd-1.50.0/aQute.libg/src/aQute/libg/generics/0000755000175000017500000000000011656076535020627 5ustar drazzibdrazzibbnd-1.50.0/aQute.libg/src/aQute/libg/generics/packageinfo0000644000175000017500000000001411656076535023014 0ustar drazzibdrazzibversion 1.0 bnd-1.50.0/aQute.libg/src/aQute/libg/generics/Create.java0000644000175000017500000000164511656076535022703 0ustar drazzibdrazzibpackage aQute.libg.generics; import java.util.*; public class Create { public static Map map() { return new LinkedHashMap(); } public static List list() { return new ArrayList(); } public static Set set() { return new HashSet(); } public static List list(T[] source) { return new ArrayList(Arrays.asList(source)); } public static Set set(T[]source) { return new HashSet(Arrays.asList(source)); } public static Map copy(Map source) { return new LinkedHashMap(source); } public static List copy(List source) { return new ArrayList(source); } public static Set copy(Collection source) { if ( source == null ) return set(); return new HashSet(source); } } bnd-1.50.0/aQute.libg/src/aQute/libg/forker/0000755000175000017500000000000011656076535020320 5ustar drazzibdrazzibbnd-1.50.0/aQute.libg/src/aQute/libg/forker/Forker.java0000644000175000017500000001145411656076535022420 0ustar drazzibdrazzibpackage aQute.libg.forker; import java.util.*; import java.util.concurrent.*; import java.util.concurrent.atomic.*; /** * A Forker is good in parallel scheduling tasks with dependencies. You can add * tasks with {@link #doWhen(Collection, Object, Runnable)}. The collection is * the list of dependencies, the object is the target, and the runnable is run * to update the target. The runnable will only run when all its dependencies * have ran their associated runnable. * * @author aqute * * @param */ public class Forker { final Executor executor; final Map waiting = new HashMap(); final Set executing = new HashSet(); final AtomicBoolean canceled = new AtomicBoolean(); private int count; /** * Helper class to model a Job */ class Job implements Runnable { T target; Set dependencies; Runnable runnable; Throwable exception; volatile Thread t; volatile AtomicBoolean canceled = new AtomicBoolean(false); /** * Run when the job's dependencies are done. */ public void run() { Thread.interrupted(); // clear the interrupt flag try { synchronized (this) { // Check if we got canceled if (canceled.get()) return; t = Thread.currentThread(); } System.out.println("Running " + target); runnable.run(); System.out.println("Done running " + target); } catch (Exception e) { exception = e; e.printStackTrace(); } finally { synchronized (this) { t = null; } Thread.interrupted(); // clear the interrupt flag done(this); } } /** * Cancel this job */ private void cancel() { if (!canceled.getAndSet(true)) { synchronized (this) { if (t != null) t.interrupt(); } } } } /** * Constructor * * @param executor */ public Forker(Executor executor) { this.executor = executor; } /** * Constructor * */ public Forker() { this.executor = Executors.newFixedThreadPool(4); } /** * Schedule a job for execution when the dependencies are done of target are * done. * * @param dependencies * the dependencies that must have run * @param target * the target, is removed from all the dependencies when it ran * @param runnable * the runnable to run */ public synchronized void doWhen(Collection dependencies, T target, Runnable runnable) { if (waiting.containsKey(target)) throw new IllegalArgumentException("You can only add a target once to the forker"); System.out.println("doWhen " + dependencies + " " + target); Job job = new Job(); job.dependencies = new HashSet(dependencies); job.target = target; job.runnable = runnable; waiting.put(target, job); } public void start(long ms) throws InterruptedException { check(); count = waiting.size(); System.out.println("Count " + count); schedule(); if (ms >= 0) sync(ms); } private void check() { Set dependencies = new HashSet(); for (Job job : waiting.values()) dependencies.addAll(job.dependencies); dependencies.removeAll(waiting.keySet()); if (dependencies.size() > 0) throw new IllegalArgumentException( "There are dependencies in the jobs that are not present in the targets: " + dependencies); } public synchronized void sync(long ms) throws InterruptedException { System.out.println("Waiting for sync"); while (count > 0) { System.out.println("Waiting for sync " + count); wait(ms); } System.out.println("Exiting sync " + count); } private void schedule() { if (canceled.get()) return; List torun = new ArrayList(); synchronized (this) { for (Iterator e = waiting.values().iterator(); e.hasNext();) { Job job = e.next(); if (job.dependencies.isEmpty()) { torun.add(job); executing.add(job); e.remove(); } } } for (Runnable r : torun) executor.execute(r); } /** * Called when the target has ran by the Job. * * @param done */ private void done(Job done) { synchronized (this) { System.out.println("count = " + count); executing.remove(done); count--; if (count == 0) { System.out.println("finished"); notifyAll(); return; } for (Job job : waiting.values()) { boolean x = job.dependencies.remove(done.target); //System.out.println( "Removing " + done.target + " from " + job.target + " ?" + x + " " + job.dependencies.size()); } } schedule(); } /** * Cancel the forker. * * @throws InterruptedException */ public void cancel(long ms) throws InterruptedException { System.out.println("canceled " + count); if (!canceled.getAndSet(true)) { synchronized (this) { for (Job job : executing) { job.cancel(); } } } sync(ms); } public int getCount() { return count; } } bnd-1.50.0/aQute.libg/src/aQute/libg/forker/packageinfo0000644000175000017500000000001411656076535022505 0ustar drazzibdrazzibversion 1.0 bnd-1.50.0/aQute.libg/src/aQute/libg/command/0000755000175000017500000000000011656076535020446 5ustar drazzibdrazzibbnd-1.50.0/aQute.libg/src/aQute/libg/command/packageinfo0000644000175000017500000000001411656076535022633 0ustar drazzibdrazzibversion 1.0 bnd-1.50.0/aQute.libg/src/aQute/libg/command/Command.java0000644000175000017500000001047411656076535022675 0ustar drazzibdrazzibpackage aQute.libg.command; import java.io.*; import java.util.*; import java.util.concurrent.*; import aQute.libg.reporter.*; public class Command { boolean trace; Reporter reporter; List arguments = new ArrayList(); long timeout = 0; File cwd = new File("").getAbsoluteFile(); static Timer timer = new Timer(); Process process; volatile boolean timedout; public int execute(Appendable stdout, Appendable stderr) throws Exception { return execute((InputStream) null, stdout, stderr); } public int execute(String input, Appendable stdout, Appendable stderr) throws Exception { InputStream in = new ByteArrayInputStream(input.getBytes("UTF-8")); return execute(in, stdout, stderr); } public int execute(InputStream in, Appendable stdout, Appendable stderr) throws Exception { int result; if (reporter != null) { reporter.trace("executing cmd: %s", arguments); } String args[] = arguments.toArray(new String[arguments.size()]); process = Runtime.getRuntime().exec(args, null, cwd); // Make sure the command will not linger when we go Runnable r = new Runnable() { public void run() { process.destroy(); } }; Thread hook = new Thread(r, arguments.toString()); Runtime.getRuntime().addShutdownHook(hook); TimerTask timer = null; OutputStream stdin = process.getOutputStream(); final InputStreamHandler handler = in != null ? new InputStreamHandler(in, stdin) : null; if (timeout != 0) { timer = new TimerTask() { public void run() { timedout = true; process.destroy(); if (handler != null) handler.interrupt(); } }; Command.timer.schedule(timer, timeout); } InputStream out = process.getInputStream(); try { InputStream err = process.getErrorStream(); try { new Collector(out, stdout).start(); new Collector(err, stdout).start(); if (handler != null) handler.start(); result = process.waitFor(); } finally { err.close(); } } finally { out.close(); if (timer != null) timer.cancel(); Runtime.getRuntime().removeShutdownHook(hook); if (handler != null) handler.interrupt(); } if (reporter != null) reporter.trace("cmd %s executed with result=%d, result: %s/%s", arguments, result, stdout, stderr); if( timedout ) return Integer.MIN_VALUE; byte exitValue = (byte) process.exitValue(); return exitValue; } public void add(String... args) { for (String arg : args) arguments.add(arg); } public void addAll(Collection args) { arguments.addAll(args); } public void setTimeout(long duration, TimeUnit unit) { timeout = unit.toMillis(duration); } public void setTrace() { this.trace = true; } public void setReporter(Reporter reporter) { this.reporter = reporter; } public void setCwd(File dir) { if (!dir.isDirectory()) throw new IllegalArgumentException("Working directory must be a directory: " + dir); this.cwd = dir; } public void cancel() { process.destroy(); } class Collector extends Thread { final InputStream in; final Appendable sb; public Collector(InputStream inputStream, Appendable sb) { this.in = inputStream; this.sb = sb; } public void run() { try { int c = in.read(); while (c >= 0) { if (trace) System.out.print((char) c); sb.append((char) c); c = in.read(); } } catch (Exception e) { try { sb.append("\n**************************************\n"); sb.append(e.toString()); sb.append("\n**************************************\n"); } catch (IOException e1) { } if (reporter != null) { reporter.trace("cmd exec: %s", e); } } } } class InputStreamHandler extends Thread { final InputStream in; final OutputStream stdin; public InputStreamHandler(InputStream in, OutputStream stdin) { this.stdin = stdin; this.in = in; } public void run() { try { int c = in.read(); while (c >= 0) { stdin.write(c); stdin.flush(); c = in.read(); } } catch (InterruptedIOException e) { // Ignore here } catch (Exception e) { // Who cares? } } } public String toString() { StringBuilder sb = new StringBuilder(); String del = ""; for (String argument : arguments) { sb.append(del); sb.append(argument); del = " "; } return sb.toString(); } } bnd-1.50.0/aQute.libg/src/aQute/libg/tuple/0000755000175000017500000000000011656076535020161 5ustar drazzibdrazzibbnd-1.50.0/aQute.libg/src/aQute/libg/tuple/Pair.java0000644000175000017500000000022611656076535021717 0ustar drazzibdrazzibpackage aQute.libg.tuple; public class Pair { final public A a; final public B b; public Pair(A a, B b) { this.a = a; this.b = b; } } bnd-1.50.0/aQute.libg/src/aQute/libg/tuple/packageinfo0000644000175000017500000000001411656076535022346 0ustar drazzibdrazzibversion 1.0 bnd-1.50.0/aQute.libg/src/aQute/libg/classloaders/0000755000175000017500000000000011656076535021507 5ustar drazzibdrazzibbnd-1.50.0/aQute.libg/src/aQute/libg/classloaders/URLClassLoaderWrapper.java0000644000175000017500000000124211656076535026471 0ustar drazzibdrazzibpackage aQute.libg.classloaders; import java.lang.reflect.*; import java.net.*; public class URLClassLoaderWrapper { final URLClassLoader loader; final Method addURL; public URLClassLoaderWrapper(ClassLoader loader) throws Exception { this.loader = (URLClassLoader) loader; addURL = URLClassLoader.class.getDeclaredMethod("addURL", URL.class); addURL.setAccessible(true); } public void addURL(URL url) throws Exception { try { addURL.invoke(loader, url); } catch( InvocationTargetException ite) { throw (Exception) ite.getTargetException(); } } public Class loadClass(String name) throws Exception { return loader.loadClass(name); } } bnd-1.50.0/aQute.libg/src/aQute/libg/cafs/0000755000175000017500000000000011656076535017744 5ustar drazzibdrazzibbnd-1.50.0/aQute.libg/src/aQute/libg/cafs/packageinfo0000644000175000017500000000001411656076535022131 0ustar drazzibdrazzibversion 1.0 bnd-1.50.0/aQute.libg/src/aQute/libg/cafs/CAFS.java0000644000175000017500000002661011656076535021330 0ustar drazzibdrazzibpackage aQute.libg.cafs; import static aQute.lib.io.IO.*; import java.io.*; import java.nio.channels.*; import java.security.*; import java.util.*; import java.util.concurrent.atomic.*; import java.util.zip.*; import aQute.lib.index.*; import aQute.libg.cryptography.*; /** * CAFS implements a SHA-1 based file store. The basic idea is that every file * in the universe has a unique SHA-1. Hard to believe but people smarter than * me have come to that conclusion. This class maintains a compressed store of * SHA-1 identified files. So if you have the SHA-1, you can get the contents. * * This makes it easy to store a SHA-1 instead of the whole file or maintain a * naming scheme. An added advantage is that it is always easy to verify you get * the right stuff. The SHA-1 Content Addressable File Store is the core * underlying idea in Git. */ public class CAFS implements Closeable, Iterable { final static byte[] CAFS = "CAFS".getBytes(); final static byte[] CAFE = "CAFE".getBytes(); final static String INDEXFILE = "index.idx"; final static String STOREFILE = "store.cafs"; final static String ALGORITHM = "SHA-1"; final static int KEYLENGTH = 20; final static int HEADERLENGTH = 4 // CAFS + 4 // flags + 4 // compressed length + 4 // uncompressed length + KEYLENGTH // key + 2 // header checksum ; final File home; Index index; RandomAccessFile store; FileChannel channel; /** * Constructor for a Content Addressable File Store * * @param home * @param create * @throws Exception */ public CAFS(File home, boolean create) throws Exception { this.home = home; if (!home.isDirectory()) { if (create) { home.mkdirs(); } else throw new IllegalArgumentException("CAFS requires a directory with create=false"); } index = new Index(new File(home, INDEXFILE), KEYLENGTH); store = new RandomAccessFile(new File(home, STOREFILE), "rw"); channel = store.getChannel(); if (store.length() < 0x100) { if (create) { store.write(CAFS); for (int i = 1; i < 64; i++) store.writeInt(0); channel.force(true); } else throw new IllegalArgumentException("Invalid store file, length is too short " + store); System.out.println(store.length()); } store.seek(0); if (!verifySignature(store, CAFS)) throw new IllegalArgumentException("Not a valid signature: CAFS at start of file"); } /** * Store an input stream in the CAFS while calculating and returning the * SHA-1 code. * * @param in * The input stream to store. * @return The SHA-1 code. * @throws Exception * if anything goes wrong */ public SHA1 write(InputStream in) throws Exception { Deflater deflater = new Deflater(); MessageDigest md = MessageDigest.getInstance(ALGORITHM); DigestInputStream din = new DigestInputStream(in, md); DeflaterInputStream dfl = new DeflaterInputStream(din, deflater); ByteArrayOutputStream bout = new ByteArrayOutputStream(); copy(dfl, bout); synchronized (store) { // First check if it already exists SHA1 sha1 = new SHA1(md.digest()); long search = index.search(sha1.digest()); if (search > 0) return sha1; byte[] compressed = bout.toByteArray(); // we need to append this file to our store, // which requires a lock. However, we are in a race // so others can get the lock between us getting // the length and someone else getting the lock. // So we must verify after we get the lock that the // length was unchanged. FileLock lock = null; try { long insertPoint; int recordLength = compressed.length + HEADERLENGTH; while (true) { insertPoint = store.length(); lock = channel.lock(insertPoint, recordLength, false); if (store.length() == insertPoint) break; // We got the wrong lock, someone else // got in between reading the length // and locking lock.release(); } int totalLength = deflater.getTotalIn(); store.seek(insertPoint); update(sha1.digest(), compressed, totalLength); index.insert(sha1.digest(), insertPoint); return sha1; } finally { if (lock != null) lock.release(); } } } /** * Read the contents of a sha 1 key. * * @param sha1 * The key * @return An Input Stream on the content or null of key not found * @throws Exception */ public InputStream read(final SHA1 sha1) throws Exception { synchronized (store) { long offset = index.search(sha1.digest()); if (offset < 0) return null; byte[] readSha1; byte[] buffer; store.seek(offset); if (!verifySignature(store, CAFE)) throw new IllegalArgumentException("No signature"); int flags =store.readInt(); int compressedLength = store.readInt(); int uncompressedLength = store.readInt(); readSha1 = new byte[KEYLENGTH]; store.read(readSha1); SHA1 rsha1 = new SHA1(readSha1); if (!sha1.equals(rsha1)) throw new IOException("SHA1 read and asked mismatch: " + sha1 + " " + rsha1); short crc = store.readShort(); // Read CRC if ( crc != checksum(flags,compressedLength, uncompressedLength, readSha1)) throw new IllegalArgumentException("Invalid header checksum: " + sha1); buffer = new byte[compressedLength]; store.readFully(buffer); return getSha1Stream(sha1, buffer, uncompressedLength); } } public boolean exists(byte[] sha1) throws Exception { return index.search(sha1) >= 0; } public void reindex() throws Exception { long length; synchronized (store) { length = store.length(); if (length < 0x100) throw new IllegalArgumentException( "Store file is too small, need to be at least 256 bytes: " + store); } RandomAccessFile in = new RandomAccessFile(new File(home, STOREFILE), "r"); try { byte[] signature = new byte[4]; in.readFully(signature); if (!Arrays.equals(CAFS, signature)) throw new IllegalArgumentException("Store file does not start with CAFS: " + in); in.seek(0x100); File ixf = new File(home, "index.new"); Index index = new Index(ixf, KEYLENGTH); while (in.getFilePointer() < length) { long entry = in.getFilePointer(); SHA1 sha1 = verifyEntry(in); index.insert(sha1.digest(), entry); } synchronized (store) { index.close(); File indexFile = new File(home, INDEXFILE); ixf.renameTo(indexFile); index = new Index(indexFile, KEYLENGTH); } } finally { in.close(); } } public void close() throws IOException { synchronized (store) { try { store.close(); } finally { index.close(); } } } private SHA1 verifyEntry(RandomAccessFile in) throws IOException, NoSuchAlgorithmException { byte[] signature = new byte[4]; in.readFully(signature); if (!Arrays.equals(CAFE, signature)) throw new IllegalArgumentException("File is corrupted: " + in); /* int flags = */in.readInt(); int compressedSize = in.readInt(); int uncompressedSize = in.readInt(); byte[] key = new byte[KEYLENGTH]; in.readFully(key); SHA1 sha1 = new SHA1(key); byte[] buffer = new byte[compressedSize]; in.readFully(buffer); InputStream xin = getSha1Stream(sha1, buffer, uncompressedSize); xin.skip(uncompressedSize); xin.close(); return sha1; } private boolean verifySignature(DataInput din, byte[] org) throws IOException { byte[] read = new byte[org.length]; din.readFully(read); return Arrays.equals(read, org); } private InputStream getSha1Stream(final SHA1 sha1, byte[] buffer, final int total) throws NoSuchAlgorithmException { ByteArrayInputStream in = new ByteArrayInputStream(buffer); InflaterInputStream iin = new InflaterInputStream(in) { int count = 0; final MessageDigest digestx = MessageDigest.getInstance(ALGORITHM); final AtomicBoolean calculated = new AtomicBoolean(); @Override public int read(byte[] data, int offset, int length) throws IOException { int size = super.read(data, offset, length); if (size <= 0) eof(); else { count+=size; this.digestx.update(data, offset, size); } return size; } public int read() throws IOException { int c = super.read(); if (c < 0) eof(); else { count++; this.digestx.update((byte) c); } return c; } void eof() throws IOException { if ( calculated.getAndSet(true)) return; if ( count != total ) throw new IOException("Counts do not match. Expected to read: " + total + " Actually read: " + count); SHA1 calculatedSha1 = new SHA1(digestx.digest()); if (!sha1.equals(calculatedSha1)) throw ( new IOException("SHA1 caclulated and asked mismatch, asked: " + sha1 + ", \nfound: " +calculatedSha1)); } public void close() throws IOException { eof(); super.close(); } }; return iin; } /** * Update a record in the store, assuming the store is at the right * position. * * @param sha1 * The checksum * @param compressed * The compressed length * @param totalLength * The uncompressed length * @throws IOException * The exception */ private void update(byte[] sha1, byte[] compressed, int totalLength) throws IOException { System.out.println("pos: " + store.getFilePointer()); store.write(CAFE); // 00-03 Signature store.writeInt(0); // 04-07 Flags for the future store.writeInt(compressed.length); // 08-11 Length deflated data store.writeInt(totalLength); // 12-15 Length store.write(sha1); // 16-35 store.writeShort( checksum(0,compressed.length, totalLength, sha1)); store.write(compressed); channel.force(false); } private short checksum(int flags, int compressedLength, int totalLength, byte[] sha1) { CRC32 crc = new CRC32(); crc.update(flags); crc.update(flags>>8); crc.update(flags>>16); crc.update(flags>>24); crc.update(compressedLength); crc.update(compressedLength>>8); crc.update(compressedLength>>16); crc.update(compressedLength>>24); crc.update(totalLength); crc.update(totalLength>>8); crc.update(totalLength>>16); crc.update(totalLength>>24); crc.update(sha1); return (short) crc.getValue(); } public Iterator iterator() { return new Iterator() { long position = 0x100; public boolean hasNext() { synchronized(store) { try { return position < store.length(); } catch (IOException e) { throw new RuntimeException(e); } } } public SHA1 next() { synchronized(store) { try { store.seek(position); byte [] signature = new byte[4]; store.readFully(signature); if ( !Arrays.equals(CAFE, signature)) throw new IllegalArgumentException("No signature"); int flags = store.readInt(); int compressedLength = store.readInt(); int totalLength = store.readInt(); byte []sha1 = new byte[KEYLENGTH]; store.readFully(sha1); short crc = store.readShort(); if ( crc != checksum(flags,compressedLength, totalLength, sha1)) throw new IllegalArgumentException("Header checksum fails"); position += HEADERLENGTH + compressedLength; return new SHA1(sha1); } catch (IOException e) { throw new RuntimeException(e); } } } public void remove() { throw new UnsupportedOperationException("Remvoe not supported, CAFS is write once"); } }; } public boolean isEmpty() throws IOException { synchronized(store) { return store.getFilePointer() <= 256; } } } bnd-1.50.0/aQute.libg/src/aQute/libg/asn1/0000755000175000017500000000000011656076535017672 5ustar drazzibdrazzibbnd-1.50.0/aQute.libg/src/aQute/libg/asn1/BER.java0000644000175000017500000003370511656076535021155 0ustar drazzibdrazzibpackage aQute.libg.asn1; import java.io.*; import java.text.*; import java.util.*; public class BER implements Types { final DataInputStream xin; long position; public BER(InputStream in) { this.xin = new DataInputStream(in); } public void dump(PrintStream out) throws Exception { int type = readByte(); long length = readLength(); if (type == -1 || length == -1) throw new EOFException("Empty file"); dump(out, type, length, ""); } void dump(PrintStream out, int type, long length, String indent) throws Exception { int clss = type >> 6; int nmbr = type & 0x1F; boolean cnst = (type & 0x20) != 0; String tag = "[" + nmbr + "]"; if (clss == 0) tag = TAGS[nmbr]; if (cnst) { System.out.printf("%5d %s %s %s\n", length, indent, CLASSES[clss], tag); while (length > 1) { long atStart = getPosition(); int t2 = read(); long l2 = readLength(); dump(out, t2, l2, indent + " "); length -= getPosition() - atStart; } } else { assert length < Integer.MAX_VALUE; assert length >= 0; byte[] data = new byte[(int) length]; readFully(data); String summary; switch (nmbr) { case BOOLEAN: assert length == 1; summary = data[0] != 0 ? "true" : "false"; break; case INTEGER: long n = toLong(data); summary = n + ""; break; case UTF8_STRING: case IA5STRING: case VISIBLE_STRING: case UNIVERSAL_STRING: case PRINTABLE_STRING: case UTCTIME: summary = new String(data, "UTF-8"); break; case OBJECT_IDENTIFIER: summary = readOID(data); break; case GENERALIZED_TIME: case GRAPHIC_STRING: case GENERAL_STRING: case CHARACTER_STRING: case REAL: case EOC: case BIT_STRING: case OCTET_STRING: case NULL: case OBJECT_DESCRIPTOR: case EXTERNAL: case ENUMERATED: case EMBEDDED_PDV: case RELATIVE_OID: case NUMERIC_STRING: case T61_STRING: case VIDEOTEX_STRING: case BMP_STRING: default: StringBuilder sb = new StringBuilder(); for (int i = 0; i < 10 && i < data.length; i++) { sb.append(Integer.toHexString(data[i])); } if (data.length > 10) { sb.append("..."); } summary = sb.toString(); break; } out.printf("%5d %s %s %s %s\n", length, indent, CLASSES[clss], tag, summary); } } long toLong(byte[] data) { if (data[0] < 0) { for (int i = 0; i < data.length; i++) data[i] = (byte) (0xFF ^ data[i]); return -(toLong(data) + 1); } long n = 0; for (int i = 0; i < data.length; i++) { n = n * 256 + data[i]; } return n; } /** * 8.1.3.3 For the definite form, the length octets shall consist of one or * more octets, and shall represent the number of octets in the contents * octets using either the short form (see 8.1.3.4) or the long form (see * 8.1.3.5) as a sender's option. NOTE – The short form can only be used if * the number of octets in the contents octets is less than or equal to 127. * 8.1.3.4 In the short form, the length octets shall consist of a single * octet in which bit 8 is zero and bits 7 to 1 encode the number of octets * in the contents octets (which may be zero), as an unsigned binary integer * with bit 7 as the most significant bit. EXAMPLE L = 38 can be encoded as * 001001102 8.1.3.5 In the long form, the length octets shall consist of an * initial octet and one or more subsequent octets. The initial octet shall * be encoded as follows: a) bit 8 shall be one; b) bits 7 to 1 shall encode * the number of subsequent octets in the length octets, as an unsigned * binary integer with bit 7 as the most significant bit; c) the value * 111111112 shall not be used. ISO/IEC 8825-1:2003 (E) NOTE 1 – This * restriction is introduced for possible future extension. Bits 8 to 1 of * the first subsequent octet, followed by bits 8 to 1 of the second * subsequent octet, followed in turn by bits 8 to 1 of each further octet * up to and including the last subsequent octet, shall be the encoding of * an unsigned binary integer equal to the number of octets in the contents * octets, with bit 8 of the first subsequent octet as the most significant * bit. EXAMPLE L = 201 can be encoded as: 100000012 110010012 NOTE 2 – In * the long form, it is a sender's option whether to use more length octets * than the minimum necessary. 8.1.3.6 For the indefinite form, the length * octets indicate that the contents octets are terminated by * end-of-contents octets (see 8.1.5), and shall consist of a single octet. * 8.1.3.6.1 The single octet shall have bit 8 set to one, and bits 7 to 1 * set to zero. 8.1.3.6.2 If this form of length is used, then * end-of-contents octets (see 8.1.5) shall be present in the encoding * following the contents octets. 8.1.4 Contents octets The contents octets * shall consist of zero, one or more octets, and shall encode the data * value as specified in subsequent clauses. NOTE – The contents octets * depend on the type of the data value; subsequent clauses follow the same * sequence as the definition of types in ASN.1. 8.1.5 End-of-contents * octets The end-of-contents octets shall be present if the length is * encoded as specified in 8.1.3.6, otherwise they shall not be present. The * end-of-contents octets shall consist of two zero octets. NOTE – The * end-of-contents octets can be considered as the encoding of a value whose * tag is universal class, whose form is primitive, whose number of the tag * is zero, and whose contents are absent, thus: * * End-of-contents Length Contents 0016 0016 Absent * * @return */ private long readLength() throws IOException { long n = readByte(); if (n > 0) { // short form return n; } else { // long form int count = (int) (n & 0x7F); if (count == 0) { // indefinite form return 0; } else { n = 0; while (count-- > 0) { n = n * 256 + read(); } return n; } } } private int readByte() throws IOException { position++; return xin.readByte(); } private void readFully(byte[] data) throws IOException { position += data.length; xin.readFully(data); } private long getPosition() { return position; } private int read() throws IOException { position++; return xin.read(); } String readOID(byte[] data) { StringBuilder sb = new StringBuilder(); sb.append((0xFF & data[0]) / 40); sb.append("."); sb.append((0xFF & data[0]) % 40); int i = 0; while (++i < data.length) { int n = 0; while (data[i] < 0) { n = n * 128 + (0x7F & data[i]); i++; } n = n * 128 + data[i]; sb.append("."); sb.append(n); } return sb.toString(); } int getPayloadLength(PDU pdu) throws Exception { switch (pdu.getTag() & 0x1F) { case EOC: return 1; case BOOLEAN: return 1; case INTEGER: return size(pdu.getInt()); case UTF8_STRING: String s = pdu.getString(); byte[] encoded = s.getBytes("UTF-8"); return encoded.length; case IA5STRING: case VISIBLE_STRING: case UNIVERSAL_STRING: case PRINTABLE_STRING: case GENERALIZED_TIME: case GRAPHIC_STRING: case GENERAL_STRING: case CHARACTER_STRING: case UTCTIME: case NUMERIC_STRING: { String str = pdu.getString(); encoded = str.getBytes("ASCII"); return encoded.length; } case OBJECT_IDENTIFIER: case REAL: case BIT_STRING: return pdu.getBytes().length; case OCTET_STRING: case NULL: case OBJECT_DESCRIPTOR: case EXTERNAL: case ENUMERATED: case EMBEDDED_PDV: case RELATIVE_OID: case T61_STRING: case VIDEOTEX_STRING: case BMP_STRING: return pdu.getBytes().length; default: throw new IllegalArgumentException("Invalid type: " + pdu); } } int size(long value) { if (value < 128) return 1; if (value <= 0xFF) return 2; if (value <= 0xFFFF) return 3; if (value <= 0xFFFFFF) return 4; if (value <= 0xFFFFFFFF) return 5; if (value <= 0xFFFFFFFFFFL) return 6; if (value <= 0xFFFFFFFFFFFFL) return 7; if (value <= 0xFFFFFFFFFFFFFFL) return 8; if (value <= 0xFFFFFFFFFFFFFFFFL) return 9; throw new IllegalArgumentException("length too long"); } public void write(OutputStream out, PDU pdu) throws Exception { byte id = 0; switch (pdu.getClss()) { case UNIVERSAL: id |= 0; break; case APPLICATION: id |= 0x40; break; case CONTEXT: id |= 0x80; break; case PRIVATE: id |= 0xC0; break; } if (pdu.isConstructed()) id |= 0x20; int tag = pdu.getTag(); if (tag >= 0 && tag < 31) { id |= tag; } else { throw new UnsupportedOperationException("Cant do tags > 30"); } out.write(id); int length = getPayloadLength(pdu); int size = size(length); if (size == 1) { out.write(length); } else { out.write(size); while (--size >= 0) { byte data = (byte) ((length >> (size * 8)) & 0xFF); out.write(data); } } writePayload(out, pdu); } void writePayload(OutputStream out, PDU pdu) throws Exception { switch (pdu.getTag()) { case EOC: out.write(0); break; case BOOLEAN: if (pdu.getBoolean()) out.write(-1); else out.write(0); break; case ENUMERATED: case INTEGER: { long value = pdu.getInt(); int size = size(value); for (int i = size; i >= 0; i--) { byte b = (byte) ((value >> (i * 8)) & 0xFF); out.write(b); } } case BIT_STRING: { byte bytes[] = pdu.getBytes(); int unused = bytes[0]; assert unused <= 7; int[] mask = { 0xFF, 0x7F, 0x3F, 0x1F, 0xF, 0x7, 0x3, 0x1 }; bytes[bytes.length - 1] &= (byte) mask[unused]; out.write(bytes); break; } case RELATIVE_OID: case OBJECT_IDENTIFIER: { int[] oid = pdu.getOID(); assert oid.length > 2; assert oid[0] < 4; assert oid[1] < 40; byte top = (byte) (oid[0] * 40 + oid[1]); out.write(top); for (int i = 2; i < oid.length; i++) { putOid(out,oid[i]); } break; } case OCTET_STRING: { byte bytes[] = pdu.getBytes(); out.write(bytes); break; } case NULL: break; case BMP_STRING: case GRAPHIC_STRING: case VISIBLE_STRING: case GENERAL_STRING: case UNIVERSAL_STRING: case CHARACTER_STRING: case NUMERIC_STRING: case PRINTABLE_STRING: case VIDEOTEX_STRING: case T61_STRING: case REAL: case EMBEDDED_PDV: case EXTERNAL: throw new UnsupportedEncodingException("dont know real, embedded PDV or external"); case UTF8_STRING: { String s = pdu.getString(); byte [] data = s.getBytes("UTF-8"); out.write(data); break; } case OBJECT_DESCRIPTOR: case IA5STRING: String s = pdu.getString(); byte [] data = s.getBytes("ASCII"); out.write(data); break; case SEQUENCE: case SET: { PDU pdus[] = pdu.getChildren(); for ( PDU p : pdus ) { write(out, p); } } case UTCTIME: case GENERALIZED_TIME: Date date = pdu.getDate(); String ss= df.format(date); byte d[] = ss.getBytes("ASCII"); out.write(d); break; } } static DateFormat df = new SimpleDateFormat("yyyyMMddHHmmss\\Z"); private void putOid(OutputStream out, int i) throws IOException { if (i > 127) { putOid(out, i >> 7); out.write(0x80 + (i & 0x7F)); } else out.write(i & 0x7F); } } bnd-1.50.0/aQute.libg/src/aQute/libg/asn1/algorithms0000644000175000017500000000220111656076535021761 0ustar drazzibdrazzib--------------------------------------------------------------------------- SignatureAlgorithm digestAlgo (I) signatureAlgo (RFC 2630) (II) digestEncrAlgo(PKCS#7) --------------------------------------------------------------------------- (A) sha1WithRSA 1.3.14.3.2.26 (Ia) 1.2.840.113549.1.1.5 (1.2.840.113549.1.1.5) (Ib) 1.2.840.113549.1.1.1 (II) 1.2.840.113549.1.1.1 (B) md5WithRSA 1.2.840.1x9.2.5 (Ia) 1.2.840.113549.1.1.4 (1.2.840.113549.1.1.4) (Ib) 1.2.840.113549.1.1.1 (II) 1.2.840.113549.1.1.1 (C) ripeMD160WithRsa 1.3.36.3.2.1 (Ia) 1.3.36.3.3.1.2 (1.3.36.3.3.1.2) (Ib) 1.2.840.113549.1.1.1 (II) 1.2.840.113549.1.1.1 (D) sha1WithDsa 1.3.14.3.2.26 (Ia) 1.2.840.10040.4.3 (1.2.840.10040.4.3) (Ib) 1.2.840.10040.4.1 (?) (II) 1.2.840.10040.4.1 bnd-1.50.0/aQute.libg/src/aQute/libg/asn1/PDU.java0000644000175000017500000000456411656076535021176 0ustar drazzibdrazzibpackage aQute.libg.asn1; import java.util.*; public class PDU implements Types, Iterable { final int identifier; final Object payload; byte data[] = new byte[100]; public PDU(int id, Object payload) { identifier = id; this.payload = payload; } public PDU(Date payload) { identifier = UTCTIME; this.payload = payload; } public PDU(int n) { this(UNIVERSAL+INTEGER, n); } public PDU(boolean value) { this(UNIVERSAL+BOOLEAN, value); } public PDU(String s) throws Exception { this(UNIVERSAL+IA5STRING, s); } public PDU(byte[] data) { this(UNIVERSAL+OCTET_STRING, data); } public PDU(BitSet bits) { this(UNIVERSAL+BIT_STRING, bits); } public PDU(int top, int l1, int... remainder) { identifier = UNIVERSAL+OBJECT_IDENTIFIER; int[] ids = new int[remainder.length + 2]; ids[0] = top; ids[1] = l1; System.arraycopy(remainder, 0, ids, 2, remainder.length); payload = ids; } public PDU(int tag, PDU... set) { this(tag,(Object)set); } public PDU(PDU... set) { this(SEQUENCE+CONSTRUCTED,set); } public int getTag() { return identifier & TAGMASK; } int getClss() { return identifier & CLASSMASK; } public boolean isConstructed() { return (identifier & CONSTRUCTED) != 0; } public String getString() { return (String) payload; } public Iterator iterator() { return Arrays.asList((PDU[]) payload).iterator(); } public int[] getOID() { assert getTag() == OBJECT_IDENTIFIER; return (int[]) payload; } public Boolean getBoolean() { assert getTag() == BOOLEAN; return (Boolean) payload; } public BitSet getBits() { assert getTag() == BIT_STRING; return (BitSet) payload; } public int getInt() { assert getTag() == INTEGER || getTag() == ENUMERATED; return (Integer) payload; } public byte[] getBytes() { return (byte[]) payload; } public PDU[] getChildren() { assert isConstructed(); return (PDU[]) payload; } public Date getDate() { assert getTag() == UTCTIME || getTag() == GENERALIZED_TIME; return (Date) payload; } } bnd-1.50.0/aQute.libg/src/aQute/libg/asn1/packageinfo0000644000175000017500000000001411656076535022057 0ustar drazzibdrazzibversion 1.0 bnd-1.50.0/aQute.libg/src/aQute/libg/asn1/Types.java0000644000175000017500000000666111656076535021652 0ustar drazzibdrazzibpackage aQute.libg.asn1; public interface Types { int UNIVERSAL = 0x00000000; int APPLICATION = 0x40000000; int CONTEXT = 0x80000000; int PRIVATE = 0xC0000000; int CLASSMASK = 0xC0000000; int CONSTRUCTED = 0x20000000; int TAGMASK = 0x1FFFFFFF; String [] CLASSES = {"U", "A", "C", "P"}; // Payload Primitve int EOC = 0; // null // x int BOOLEAN = 1; // Boolean // x int INTEGER = 2; // Long // x int BIT_STRING = 3; // byte // [] - int OCTET_STRING = 4; // byte // [] - int NULL = 5; // null // x int OBJECT_IDENTIFIER = 6; // int[] // x int OBJECT_DESCRIPTOR = 7; // int EXTERNAL = 8; // int REAL = 9; // double // x int ENUMERATED = 10; // int EMBEDDED_PDV = 11; // int UTF8_STRING = 12; // String int RELATIVE_OID = 13; // int SEQUENCE = 16; // int SET = 17; int NUMERIC_STRING = 18; // String int PRINTABLE_STRING = 19; // String int T61_STRING = 20; // String int VIDEOTEX_STRING = 21; // String int IA5STRING = 22; // String int UTCTIME = 23; // Date int GENERALIZED_TIME = 24; // Date int GRAPHIC_STRING = 25; // String int VISIBLE_STRING = 26; // String int GENERAL_STRING = 27; // String int UNIVERSAL_STRING = 28; // String int CHARACTER_STRING = 29; // String int BMP_STRING = 30; // byte[] String[] TAGS = { "EOC ", "BOOLEAN ", "INTEGER ", "BIT_STRING ", "OCTET_STRING ", "NULL ", "OBJECT_IDENTIFIER ", "OBJECT_DESCRIPTOR ", "EXTERNAL ", "REAL ", "ENUMERATED ", "EMBEDDED_PDV ", "UTF8_STRING ", "RELATIVE_OID ", "?(14) ", "?(15) ", "SEQUENCE ", "SET ", "NUMERIC_STRING ", "PRINTABLE_STRING ", "T61_STRING ", "VIDEOTEX_STRING ", "IA5STRING ", "UTCTIME ", "GENERALIZED_TIME ", "GRAPHIC_STRING ", "VISIBLE_STRING ", "GENERAL_STRING ", "UNIVERSAL_STRING ", "CHARACTER_STRING ", "BMP_STRING ", }; } bnd-1.50.0/aQute.libg/src/aQute/libg/filecheck/0000755000175000017500000000000011656076535020745 5ustar drazzibdrazzibbnd-1.50.0/aQute.libg/src/aQute/libg/filecheck/FileCheck.java0000644000175000017500000000037311656076535023430 0ustar drazzibdrazzibpackage aQute.libg.filecheck; public class FileCheck { public static void main(String args[] ) { // File f = new File("/Ws/osgi/build").getAbsoluteFile(); // long now = System.currentTimeMillis(); // traverse(f); // System.out.printf("") } } bnd-1.50.0/aQute.libg/src/aQute/libg/filecheck/packageinfo0000644000175000017500000000001411656076535023132 0ustar drazzibdrazzibversion 1.0 bnd-1.50.0/aQute.libg/src/aQute/libg/xslt/0000755000175000017500000000000011656076535020022 5ustar drazzibdrazzibbnd-1.50.0/aQute.libg/src/aQute/libg/xslt/Transform.java0000644000175000017500000000267511656076535022652 0ustar drazzibdrazzibpackage aQute.libg.xslt; import java.io.*; import java.net.*; import java.util.*; import java.util.concurrent.*; import javax.xml.transform.*; import javax.xml.transform.stream.*; public class Transform { static TransformerFactory transformerFactory = TransformerFactory .newInstance(); static Map cache = new ConcurrentHashMap(); public static void transform(TransformerFactory transformerFactory, URL xslt, InputStream in, OutputStream out) throws Exception { if ( xslt == null ) throw new IllegalArgumentException("No source template specified"); Templates templates = cache.get(xslt); if (templates == null) { InputStream xsltIn = xslt.openStream(); try { templates = transformerFactory .newTemplates(new StreamSource(xsltIn)); cache.put(xslt, templates); } finally { in.close(); } } Result xmlResult = new StreamResult(out); Source xmlSource = new StreamSource(in); Transformer t = templates.newTransformer(); t.transform(xmlSource, xmlResult); out.flush(); } public static void transform(URL xslt, InputStream in, OutputStream out) throws Exception { transform(transformerFactory,xslt, in, out); } } bnd-1.50.0/aQute.libg/src/aQute/libg/xslt/packageinfo0000644000175000017500000000001411656076535022207 0ustar drazzibdrazzibversion 1.0 bnd-1.50.0/aQute.libg/src/aQute/libg/header/0000755000175000017500000000000011656076535020260 5ustar drazzibdrazzibbnd-1.50.0/aQute.libg/src/aQute/libg/header/packageinfo0000644000175000017500000000001411656076535022445 0ustar drazzibdrazzibversion 1.0 bnd-1.50.0/aQute.libg/src/aQute/libg/header/OSGiHeader.java0000755000175000017500000001350011656076535023037 0ustar drazzibdrazzibpackage aQute.libg.header; import java.util.*; import aQute.libg.generics.*; import aQute.libg.qtokens.*; import aQute.libg.reporter.*; public class OSGiHeader { static public Map> parseHeader(String value) { return parseHeader(value, null); } /** * Standard OSGi header parser. This parser can handle the format clauses * ::= clause ( ',' clause ) + clause ::= name ( ';' name ) (';' key '=' * value ) * * This is mapped to a Map { name => Map { attr|directive => value } } * * @param value * A string * @return a Map> */ static public Map> parseHeader(String value, Reporter logger) { if (value == null || value.trim().length() == 0) return Create.map(); Map> result = Create.map(); QuotedTokenizer qt = new QuotedTokenizer(value, ";=,"); char del = 0; do { boolean hadAttribute = false; Map clause = Create.map(); List aliases = Create.list(); String name = qt.nextToken(",;"); del = qt.getSeparator(); if (name == null || name.length() == 0) { if (logger != null && logger.isPedantic()) { logger .warning("Empty clause, usually caused by repeating a comma without any name field or by having spaces after the backslash of a property file: " + value); } if (name == null) break; } else { name = name.trim(); aliases.add(name); while (del == ';') { String adname = qt.nextToken(); if ((del = qt.getSeparator()) != '=') { if (hadAttribute) if (logger != null) { logger .error("Header contains name field after attribute or directive: " + adname + " from " + value + ". Name fields must be consecutive, separated by a ';' like a;b;c;x=3;y=4"); } if (adname != null && adname.length() > 0) aliases.add(adname.trim()); } else { String advalue = qt.nextToken(); if (clause.containsKey(adname)) { if (logger != null && logger.isPedantic()) logger .warning("Duplicate attribute/directive name " + adname + " in " + value + ". This attribute/directive will be ignored"); } if (advalue == null) { if (logger != null) logger .error("No value after '=' sign for attribute " + adname); advalue = ""; } clause.put(adname.trim(), advalue.trim()); del = qt.getSeparator(); hadAttribute = true; } } // Check for duplicate names. The aliases list contains // the list of nams, for each check if it exists. If so, // add a number of "~" to make it unique. for (String clauseName : aliases) { if (result.containsKey(clauseName)) { if (logger != null && logger.isPedantic()) logger .warning("Duplicate name " + clauseName + " used in header: '" + clauseName + "'. Duplicate names are specially marked in Bnd with a ~ at the end (which is stripped at printing time)."); while (result.containsKey(clauseName)) clauseName += "~"; } result.put(clauseName, clause); } } } while (del == ','); return result; } public static Map parseProperties(String input) { return parseProperties(input, null); } public static Map parseProperties(String input, Reporter logger) { if (input == null || input.trim().length() == 0) return Create.map(); Map result = Create.map(); QuotedTokenizer qt = new QuotedTokenizer(input, "=,"); char del = ','; while (del == ',') { String key = qt.nextToken(",="); String value = ""; del = qt.getSeparator(); if (del == '=') { value = qt.nextToken(",="); del = qt.getSeparator(); } result.put(key, value); } if (del != 0) if ( logger == null ) throw new IllegalArgumentException( "Invalid syntax for properties: " + input); else logger.error("Invalid syntax for properties: " + input); return result; } } bnd-1.50.0/aQute.libg/src/aQute/libg/cryptography/0000755000175000017500000000000011656076535021563 5ustar drazzibdrazzibbnd-1.50.0/aQute.libg/src/aQute/libg/cryptography/Digest.java0000644000175000017500000000103711656076535023646 0ustar drazzibdrazzibpackage aQute.libg.cryptography; import aQute.lib.hex.*; public abstract class Digest { final byte[] digest; protected Digest(byte[] checksum, int width) { this.digest = checksum; if (digest.length != width) throw new IllegalArgumentException("Invalid width for digest: " + digest.length + " expected " + width); } public byte[] digest() { return digest; } @Override public String toString() { return String.format("%s(d=%s)", getAlgorithm(), Hex.toHexString(digest)); } public abstract String getAlgorithm(); } bnd-1.50.0/aQute.libg/src/aQute/libg/cryptography/RSA.java0000644000175000017500000000256611656076535023064 0ustar drazzibdrazzibpackage aQute.libg.cryptography; import java.math.*; import java.security.*; import java.security.interfaces.*; import java.security.spec.*; import aQute.libg.tuple.*; public class RSA { final static String ALGORITHM = "RSA"; final static KeyFactory factory = getKeyFactory(); static private KeyFactory getKeyFactory() { try { return KeyFactory.getInstance(ALGORITHM); } catch (Exception e) { // built in } return null; } public static RSAPrivateKey create(RSAPrivateKeySpec keyspec) throws InvalidKeySpecException { return (RSAPrivateKey) factory.generatePrivate(keyspec); } public static RSAPublicKey create(RSAPublicKeySpec keyspec) throws InvalidKeySpecException { return (RSAPublicKey) factory.generatePrivate(keyspec); } public static RSAPublicKey createPublic(BigInteger m, BigInteger e) throws InvalidKeySpecException { return create( new RSAPublicKeySpec(m,e)); } public static RSAPrivateKey createPrivate(BigInteger m, BigInteger e) throws InvalidKeySpecException { return create( new RSAPrivateKeySpec(m,e)); } public static Pair generate() throws NoSuchAlgorithmException { KeyPairGenerator kpg = KeyPairGenerator.getInstance(ALGORITHM); KeyPair keypair = kpg.generateKeyPair(); return new Pair( (RSAPrivateKey) keypair.getPrivate(), (RSAPublicKey) keypair.getPublic()); } } bnd-1.50.0/aQute.libg/src/aQute/libg/cryptography/MD5.java0000644000175000017500000000120711656076535023013 0ustar drazzibdrazzibpackage aQute.libg.cryptography; import java.security.*; public class MD5 extends Digest { public final static String ALGORITHM = "MD5"; public static Digester getDigester() throws Exception { return new Digester(MessageDigest.getInstance(ALGORITHM)) { @Override public MD5 digest() throws Exception { return new MD5(md.digest()); } @Override public MD5 digest(byte[] bytes) { return new MD5(bytes); } @Override public String getAlgorithm() { return ALGORITHM; } }; } public MD5(byte[] digest) { super(digest,16); } @Override public String getAlgorithm() { return ALGORITHM; } }bnd-1.50.0/aQute.libg/src/aQute/libg/cryptography/Digester.java0000644000175000017500000000144111656076535024174 0ustar drazzibdrazzibpackage aQute.libg.cryptography; import java.io.*; import java.security.*; import aQute.lib.io.*; public abstract class Digester extends OutputStream { protected MessageDigest md; public Digester(MessageDigest instance){ md = instance; } @Override public void write( byte[] buffer, int offset, int length) throws IOException{ md.update(buffer,offset,length); } @Override public void write( int b) throws IOException{ md.update((byte) b); } public MessageDigest getMessageDigest() throws Exception { return md; } public T from(InputStream in) throws Exception { IO.copy(in,this); return digest(); } public abstract T digest() throws Exception; public abstract T digest( byte [] bytes) throws Exception; public abstract String getAlgorithm(); } bnd-1.50.0/aQute.libg/src/aQute/libg/cryptography/Verifier.java0000644000175000017500000000132211656076535024177 0ustar drazzibdrazzibpackage aQute.libg.cryptography; import java.io.*; import java.security.*; public class Verifier extends OutputStream { final Signature signature; final Digest d; Verifier(Signature s, Digest d) { this.signature = s; this.d = d; } @Override public void write( byte[] buffer, int offset, int length) throws IOException { try { signature.update(buffer, offset, length); } catch (SignatureException e) { throw new IOException(e); } } @Override public void write( int b) throws IOException { try { signature.update((byte) b); } catch (SignatureException e) { throw new IOException(e); } } public boolean verify() throws Exception { return signature.verify(d.digest()); } } bnd-1.50.0/aQute.libg/src/aQute/libg/cryptography/packageinfo0000644000175000017500000000001411656076535023750 0ustar drazzibdrazzibversion 1.0 bnd-1.50.0/aQute.libg/src/aQute/libg/cryptography/Crypto.java0000644000175000017500000000412611656076535023711 0ustar drazzibdrazzibpackage aQute.libg.cryptography; import java.math.*; import java.security.*; import java.security.interfaces.*; import java.security.spec.*; import java.util.regex.*; public class Crypto { static final Pattern RSA_PRIVATE = Pattern .compile("\\s*RSA.Private\\((\\p{xDigit})+:(\\p{xDigit})+\\)\\s*"); static final Pattern RSA_PUBLIC = Pattern .compile("\\s*RSA.Public\\((\\p{xDigit})+:(\\p{xDigit})+\\)\\s*"); /** * * @param * @param spec * @return * @throws Exception */ @SuppressWarnings("unchecked") public static T fromString(String spec, Class c) throws Exception { if ( PrivateKey.class.isAssignableFrom(c)) { Matcher m = RSA_PRIVATE.matcher(spec); if ( m.matches()) { return (T) RSA.createPrivate( new BigInteger(m.group(1)), new BigInteger(m.group(2))); } throw new IllegalArgumentException("No such private key " + spec ); } if ( PublicKey.class.isAssignableFrom(c)) { Matcher m = RSA_PUBLIC.matcher(spec); if ( m.matches()) { return (T) RSA.create( new RSAPublicKeySpec( new BigInteger(m.group(1)), new BigInteger(m.group(2)))); } throw new IllegalArgumentException("No such public key " + spec ); } return null; } public static String toString( Object key ) { if ( key instanceof RSAPrivateKey ) { RSAPrivateKey pk = (RSAPrivateKey) key; return "RSA.Private(" + pk.getModulus() + ":" + pk.getPrivateExponent() + ")"; } if ( key instanceof RSAPublicKey ) { RSAPublicKey pk = (RSAPublicKey) key; return "RSA.Private(" + pk.getModulus() + ":" + pk.getPublicExponent() + ")"; } return null; } public static Signer signer(PrivateKey key, Digester digester) throws NoSuchAlgorithmException { Signature s = Signature.getInstance(key.getAlgorithm() + "with" + digester.getAlgorithm()); return new Signer(s,digester); } public static Verifier verifier(PublicKey key, Digest digest) throws NoSuchAlgorithmException { Signature s = Signature.getInstance(key.getAlgorithm() + "with" + digest.getAlgorithm()); return new Verifier(s,digest); } } bnd-1.50.0/aQute.libg/src/aQute/libg/cryptography/Key.java0000644000175000017500000000022211656076535023152 0ustar drazzibdrazzibpackage aQute.libg.cryptography; public abstract class Key implements java.security.Key { private static final long serialVersionUID = 1L; } bnd-1.50.0/aQute.libg/src/aQute/libg/cryptography/Signer.java0000644000175000017500000000137311656076535023661 0ustar drazzibdrazzibpackage aQute.libg.cryptography; import java.io.*; import java.security.*; public class Signer extends OutputStream { Signature signature; Digester digester; Signer(Signature s, Digester digester) { this.signature = s; this.digester = digester; } @Override public void write(byte[] buffer, int offset, int length) throws IOException { try { signature.update(buffer, offset, length); } catch (SignatureException e) { throw new IOException(e); } } @Override public void write(int b) throws IOException { try { signature.update((byte) b); } catch (SignatureException e) { throw new IOException(e); } } public D signature() throws Exception { return digester.digest(signature().digest()); } } bnd-1.50.0/aQute.libg/src/aQute/libg/cryptography/SHA1.java0000644000175000017500000000125211656076535023122 0ustar drazzibdrazzibpackage aQute.libg.cryptography; import java.security.*; public class SHA1 extends Digest { public final static String ALGORITHM = "SHA1"; public static Digester getDigester() throws NoSuchAlgorithmException { MessageDigest md = MessageDigest.getInstance(ALGORITHM); return new Digester(md) { @Override public SHA1 digest() throws Exception { return new SHA1(md.digest()); } @Override public SHA1 digest(byte[] bytes) { return new SHA1(bytes); } @Override public String getAlgorithm() { return ALGORITHM; } }; } public SHA1(byte[] b) { super(b, 20); } @Override public String getAlgorithm() { return ALGORITHM; } }bnd-1.50.0/aQute.libg/src/aQute/libg/tarjan/0000755000175000017500000000000011656076535020307 5ustar drazzibdrazzibbnd-1.50.0/aQute.libg/src/aQute/libg/tarjan/Tarjan.java0000644000175000017500000000501611656076535022373 0ustar drazzibdrazzibpackage aQute.libg.tarjan; import static java.lang.Math.*; import java.util.*; public class Tarjan { public class Node { final T name; final List adjacent = new ArrayList(); int low = -1; int index = -1; public Node(T name) { this.name = name; } public String toString() { return name + "{" + index + "," + low + "}"; } } private int index = 0; private List stack = new ArrayList(); private Set> scc = new HashSet>(); private Node root = new Node(null); // public ArrayList> tarjan(Node v, AdjacencyList list){ // v.index = index; // v.lowlink = index; // index++; // stack.add(0, v); // for(Edge e : list.getAdjacent(v)){ // Node n = e.to; // if(n.index == -1){ // tarjan(n, list); // v.lowlink = Math.min(v.lowlink, n.lowlink); // }else if(stack.contains(n)){ // v.lowlink = Math.min(v.lowlink, n.index); // } // } // if(v.lowlink == v.index){ // Node n; // ArrayList component = new ArrayList(); // do{ // n = stack.remove(0); // component.add(n); // }while(n != v); // SCC.add(component); // } // return SCC; // } void tarjan(Node v) { v.index = index; v.low = index; index++; stack.add(0, v); for (Node n : v.adjacent) { if (n.index == -1) { // first time visit tarjan(n); v.low = min(v.low, n.low); } else if (stack.contains(n)) { v.low = min(v.low, n.index); } } if (v!=root && v.low == v.index) { Set component = new HashSet(); Node n; do { n = stack.remove(0); component.add(n.name); } while (n != v); scc.add(component); } } Set> getResult(Map> graph) { Map index = new HashMap(); for (Map.Entry> entry : graph.entrySet()) { Node node = getNode(index, entry.getKey()); root.adjacent.add(node); for (T adj : entry.getValue()) node.adjacent.add(getNode(index, adj)); } tarjan(root); return scc; } private Node getNode(Map index, T key) { Node node = index.get(key); if (node == null) { node = new Node(key); index.put(key, node); } return node; } public static Set> tarjan(Map> graph) { Tarjan tarjan = new Tarjan(); return tarjan.getResult(graph); } } bnd-1.50.0/aQute.libg/src/aQute/libg/tarjan/packageinfo0000644000175000017500000000001411656076535022474 0ustar drazzibdrazzibversion 1.0 bnd-1.50.0/aQute.libg/README0000644000175000017500000000051211656076535015123 0ustar drazzibdrazzibThis is a project that contains lots of small utilties, each in their own package. This library is intended to be used with the bnd Conditinal-Package header. This header will include all packages in a given namespace. Just put the JAR of this project on your claspath and then: Conditional-Package: aQute.lib.*, aQute.libg.* bnd-1.50.0/aQute.libg/.settings/0000755000175000017500000000000011656076535016163 5ustar drazzibdrazzibbnd-1.50.0/aQute.libg/.settings/org.eclipse.jdt.core.prefs0000644000175000017500000000115211656076535023144 0ustar drazzibdrazzib#Mon Oct 12 17:22:15 CEST 2009 eclipse.preferences.version=1 org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.5 org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve org.eclipse.jdt.core.compiler.compliance=1.5 org.eclipse.jdt.core.compiler.debug.lineNumber=generate org.eclipse.jdt.core.compiler.debug.localVariable=generate org.eclipse.jdt.core.compiler.debug.sourceFile=generate org.eclipse.jdt.core.compiler.problem.assertIdentifier=error org.eclipse.jdt.core.compiler.problem.enumIdentifier=error org.eclipse.jdt.core.compiler.source=1.5 bnd-1.50.0/aQute.libg/.settings/org.eclipse.core.resources.prefs0000644000175000017500000000012511656076535024374 0ustar drazzibdrazzib#Mon Sep 19 11:00:09 EDT 2005 eclipse.preferences.version=1 encoding/=UTF-8 bnd-1.50.0/aQute.libg/.settings/org.eclipse.core.runtime.prefs0000644000175000017500000000011611656076535024045 0ustar drazzibdrazzib#Tue Dec 14 12:22:25 EST 2010 eclipse.preferences.version=1 line.separator=\n

* Throws an IOException if the socket is already in use */ public NanoHTTPD( File baseDir, int port ) throws IOException { this.baseDir = baseDir; myTcpPort = port; myServerSocket = new ServerSocket( myTcpPort ); myThread = new Thread( new Runnable() { public void run() { try { while( true ) new HTTPSession( myServerSocket.accept()); } catch ( IOException ioe ) {} } }); myThread.setDaemon( true ); myThread.start(); } /** * Stops the server. */ public void stop() { try { myServerSocket.close(); myThread.join(); } catch ( IOException ioe ) {} catch ( InterruptedException e ) {} } /** * Handles one session, i.e. parses the HTTP request * and returns the response. */ private class HTTPSession implements Runnable { public HTTPSession( Socket s ) { mySocket = s; Thread t = new Thread( this ); t.setDaemon( true ); t.start(); } public void run() { try { InputStream is = mySocket.getInputStream(); if ( is == null) return; // Read the first 8192 bytes. // The full header should fit in here. // Apache's default header limit is 8KB. int bufsize = 8192; byte[] buf = new byte[bufsize]; int rlen = is.read(buf, 0, bufsize); if (rlen <= 0) return; // Create a BufferedReader for parsing the header. ByteArrayInputStream hbis = new ByteArrayInputStream(buf, 0, rlen); BufferedReader hin = new BufferedReader( new InputStreamReader( hbis )); Properties pre = new Properties(); Properties parms = new Properties(); Properties header = new Properties(); Properties files = new Properties(); // Decode the header into parms and header java properties decodeHeader(hin, pre, parms, header); String method = pre.getProperty("method"); String uri = pre.getProperty("uri"); long size = 0x7FFFFFFFFFFFFFFFl; String contentLength = header.getProperty("content-length"); if (contentLength != null) { try { size = Integer.parseInt(contentLength); } catch (NumberFormatException ex) {} } // We are looking for the byte separating header from body. // It must be the last byte of the first two sequential new lines. int splitbyte = 0; boolean sbfound = false; while (splitbyte < rlen) { if (buf[splitbyte] == '\r' && buf[++splitbyte] == '\n' && buf[++splitbyte] == '\r' && buf[++splitbyte] == '\n') { sbfound = true; break; } splitbyte++; } splitbyte++; // Write the part of body already read to ByteArrayOutputStream f ByteArrayOutputStream f = new ByteArrayOutputStream(); if (splitbyte < rlen) f.write(buf, splitbyte, rlen-splitbyte); // While Firefox sends on the first read all the data fitting // our buffer, Chrome and Opera sends only the headers even if // there is data for the body. So we do some magic here to find // out whether we have already consumed part of body, if we // have reached the end of the data to be sent or we should // expect the first byte of the body at the next read. if (splitbyte < rlen) size -= rlen - splitbyte +1; else if (!sbfound || size == 0x7FFFFFFFFFFFFFFFl) size = 0; // Now read all the body and write it to f buf = new byte[512]; while ( rlen >= 0 && size > 0 ) { rlen = is.read(buf, 0, 512); size -= rlen; if (rlen > 0) f.write(buf, 0, rlen); } // Get the raw body as a byte [] byte [] fbuf = f.toByteArray(); // Create a BufferedReader for easily reading it as string. ByteArrayInputStream bin = new ByteArrayInputStream(fbuf); BufferedReader in = new BufferedReader( new InputStreamReader(bin)); // If the method is POST, there may be parameters // in data section, too, read it: if ( method.equalsIgnoreCase( "POST" )) { String contentType = ""; String contentTypeHeader = header.getProperty("content-type"); StringTokenizer st = new StringTokenizer( contentTypeHeader , "; " ); if ( st.hasMoreTokens()) { contentType = st.nextToken(); } if (contentType.equalsIgnoreCase("multipart/form-data")) { // Handle multipart/form-data if ( !st.hasMoreTokens()) sendError( HTTP_BADREQUEST, "BAD REQUEST: Content type is multipart/form-data but boundary missing. Usage: GET /example/file.html" ); String boundaryExp = st.nextToken(); st = new StringTokenizer( boundaryExp , "=" ); if (st.countTokens() != 2) sendError( HTTP_BADREQUEST, "BAD REQUEST: Content type is multipart/form-data but boundary syntax error. Usage: GET /example/file.html" ); st.nextToken(); String boundary = st.nextToken(); decodeMultipartData(boundary, fbuf, in, parms, files); } else { // Handle application/x-www-form-urlencoded String postLine = ""; char pbuf[] = new char[512]; int read = in.read(pbuf); while ( read >= 0 && !postLine.endsWith("\r\n") ) { postLine += String.valueOf(pbuf, 0, read); read = in.read(pbuf); } postLine = postLine.trim(); decodeParms( postLine, parms ); } } // Ok, now do the serve() Response r = serve( uri, method, header, parms, files ); if ( r == null ) sendError( HTTP_INTERNALERROR, "SERVER INTERNAL ERROR: Serve() returned a null response." ); else sendResponse( r.status, r.mimeType, r.header, r.data ); in.close(); is.close(); } catch ( IOException ioe ) { try { sendError( HTTP_INTERNALERROR, "SERVER INTERNAL ERROR: IOException: " + ioe.getMessage()); } catch ( Throwable t ) {} } catch ( InterruptedException ie ) { // Thrown by sendError, ignore and exit the thread. } } /** * Decodes the sent headers and loads the data into * java Properties' key - value pairs **/ private void decodeHeader(BufferedReader in, Properties pre, Properties parms, Properties header) throws InterruptedException { try { // Read the request line String inLine = in.readLine(); if (inLine == null) return; StringTokenizer st = new StringTokenizer( inLine ); if ( !st.hasMoreTokens()) sendError( HTTP_BADREQUEST, "BAD REQUEST: Syntax error. Usage: GET /example/file.html" ); String method = st.nextToken(); pre.put("method", method); if ( !st.hasMoreTokens()) sendError( HTTP_BADREQUEST, "BAD REQUEST: Missing URI. Usage: GET /example/file.html" ); String uri = st.nextToken(); // Decode parameters from the URI int qmi = uri.indexOf( '?' ); if ( qmi >= 0 ) { decodeParms( uri.substring( qmi+1 ), parms ); uri = decodePercent( uri.substring( 0, qmi )); } else uri = decodePercent(uri); // If there's another token, it's protocol version, // followed by HTTP headers. Ignore version but parse headers. // NOTE: this now forces header names lowercase since they are // case insensitive and vary by client. if ( st.hasMoreTokens()) { String line = in.readLine(); while ( line != null && line.trim().length() > 0 ) { int p = line.indexOf( ':' ); if ( p >= 0 ) header.put( line.substring(0,p).trim().toLowerCase(), line.substring(p+1).trim()); line = in.readLine(); } } pre.put("uri", uri); } catch ( IOException ioe ) { sendError( HTTP_INTERNALERROR, "SERVER INTERNAL ERROR: IOException: " + ioe.getMessage()); } } /** * Decodes the Multipart Body data and put it * into java Properties' key - value pairs. **/ private void decodeMultipartData(String boundary, byte[] fbuf, BufferedReader in, Properties parms, Properties files) throws InterruptedException { try { int[] bpositions = getBoundaryPositions(fbuf,boundary.getBytes()); int boundarycount = 1; String mpline = in.readLine(); while ( mpline != null ) { if (mpline.indexOf(boundary) == -1) sendError( HTTP_BADREQUEST, "BAD REQUEST: Content type is multipart/form-data but next chunk does not start with boundary. Usage: GET /example/file.html" ); boundarycount++; Properties item = new Properties(); mpline = in.readLine(); while (mpline != null && mpline.trim().length() > 0) { int p = mpline.indexOf( ':' ); if (p != -1) item.put( mpline.substring(0,p).trim().toLowerCase(), mpline.substring(p+1).trim()); mpline = in.readLine(); } if (mpline != null) { String contentDisposition = item.getProperty("content-disposition"); if (contentDisposition == null) { sendError( HTTP_BADREQUEST, "BAD REQUEST: Content type is multipart/form-data but no content-disposition info found. Usage: GET /example/file.html" ); } StringTokenizer st = new StringTokenizer( contentDisposition , "; " ); Properties disposition = new Properties(); while ( st.hasMoreTokens()) { String token = st.nextToken(); int p = token.indexOf( '=' ); if (p!=-1) disposition.put( token.substring(0,p).trim().toLowerCase(), token.substring(p+1).trim()); } String pname = disposition.getProperty("name"); pname = pname.substring(1,pname.length()-1); String value = ""; if (item.getProperty("content-type") == null) { while (mpline != null && mpline.indexOf(boundary) == -1) { mpline = in.readLine(); if ( mpline != null) { int d = mpline.indexOf(boundary); if (d == -1) value+=mpline; else value+=mpline.substring(0,d-2); } } } else { if (boundarycount> bpositions.length) sendError( HTTP_INTERNALERROR, "Error processing request" ); int offset = stripMultipartHeaders(fbuf, bpositions[boundarycount-2]); String path = saveTmpFile(fbuf, offset, bpositions[boundarycount-1]-offset-4); files.put(pname, path); value = disposition.getProperty("filename"); value = value.substring(1,value.length()-1); do { mpline = in.readLine(); } while (mpline != null && mpline.indexOf(boundary) == -1); } parms.put(pname, value); } } } catch ( IOException ioe ) { sendError( HTTP_INTERNALERROR, "SERVER INTERNAL ERROR: IOException: " + ioe.getMessage()); } } /** * Find the byte positions where multipart boundaries start. **/ public int[] getBoundaryPositions(byte[] b, byte[] boundary) { int matchcount = 0; int matchbyte = -1; Vector matchbytes = new Vector(); for (int i=0; i 0) { String tmpdir = System.getProperty("java.io.tmpdir"); try { File temp = File.createTempFile("NanoHTTPD", "", new File(tmpdir)); OutputStream fstream = new FileOutputStream(temp); fstream.write(b, offset, len); fstream.close(); path = temp.getAbsolutePath(); } catch (Exception e) { // Catch exception if any System.err.println("Error: " + e.getMessage()); } } return path; } /** * It returns the offset separating multipart file headers * from the file's data. **/ private int stripMultipartHeaders(byte[] b, int offset) { int i = 0; for (i=offset; i * For example: "an+example%20string" -> "an example string" */ private String decodePercent( String str ) throws InterruptedException { try { StringBuffer sb = new StringBuffer(); for( int i=0; i= 0 ) uri = uri.substring(0, uri.indexOf( '?' )); // Prohibit getting out of current directory if ( uri.startsWith( ".." ) || uri.endsWith( ".." ) || uri.indexOf( "../" ) >= 0 ) return new Response( HTTP_FORBIDDEN, MIME_PLAINTEXT, "FORBIDDEN: Won't serve ../ for security reasons." ); File f = new File( homeDir, uri ); if ( !f.exists()) return new Response( HTTP_NOTFOUND, MIME_PLAINTEXT, "Error 404, file not found." ); // List the directory, if necessary if ( f.isDirectory()) { // Browsers get confused without '/' after the // directory, send a redirect. if ( !uri.endsWith( "/" )) { uri += "/"; Response r = new Response( HTTP_REDIRECT, MIME_HTML, "Redirected: " + uri + ""); r.addHeader( "Location", uri ); return r; } // First try index.html and index.htm if ( new File( f, "index.html" ).exists()) f = new File( homeDir, uri + "/index.html" ); else if ( new File( f, "index.htm" ).exists()) f = new File( homeDir, uri + "/index.htm" ); // No index file, list the directory else if ( allowDirectoryListing ) { String[] files = f.list(); String msg = "