@Test public void testFragmentAttachOrder() throws Exception { Bundle fragE1 = installBundle(getFragmentE1()); Bundle fragE2 = installBundle(getFragmentE2()); Bundle hostE = installBundle(getHostE()); Bundle hostF = installBundle(getHostF()); hostE.start(); assertTrue(fragE1.getBundleId() < fragE2.getBundleId()); // Load class provided by the fragment assertLoadClass(hostE, FragE1Class.class.getName()); assertLoadClass(hostE, FragE2Class.class.getName()); // Tests that if a classpath entry cannot be located in the bundle, then the // Framework attempts to locate the classpath entry in each attached // fragment bundle. The attached fragment bundles are searched in ascending // bundle id order. URL resourceURL = hostE.getResource("resource.txt"); BufferedReader br = new BufferedReader(new InputStreamReader(resourceURL.openStream())); assertEquals("fragE1", br.readLine()); hostF.uninstall(); hostE.uninstall(); fragE2.uninstall(); fragE1.uninstall(); }
protected void register(final Bundle bundle) { debug("checking bundle " + bundle.getBundleId()); if (isOurBundle(bundle) || isImportingUs(bundle)) { debug("Registering bundle for extension resolution: " + bundle.getBundleId()); bundleWrappers.put(bundle.getBundleId(), new BundleWrapper(bundle)); } }
@Override public boolean start(URI uri) { final String warName = extractDecodedWarNameFromString(uri.toString()); String extractionFolderName = WebBundleUtils.calculateCorrectSymbolicName( extractDecodedWarNameFromString(uri.toString())); Bundle bundle = getInstalledBundle(extractionFolderName); if (bundle == null) { this.eventLogger.log(WARDeployerLogEvents.NANO_STARTING_ERROR, uri); logger.error( "Cannot start deployable with URI + [" + uri + "]. There is no bundle installed with this URI."); return false; } StatusFileModificator.deleteStatusFile(warName, this.pickupDir); final long lastModified = new File(uri).lastModified(); this.eventLogger.log( WARDeployerLogEvents.NANO_WEB_STARTING, bundle.getSymbolicName(), bundle.getVersion()); try { bundle.start(); } catch (Exception e) { this.eventLogger.log( WARDeployerLogEvents.NANO_STARTING_ERROR, e, bundle.getSymbolicName(), bundle.getVersion()); StatusFileModificator.createStatusFile( warName, this.pickupDir, StatusFileModificator.OP_DEPLOY, STATUS_ERROR, bundle.getBundleId(), lastModified); return STATUS_ERROR; } this.eventLogger.log( WARDeployerLogEvents.NANO_WEB_STARTED, bundle.getSymbolicName(), bundle.getVersion()); // now update bundle's info if (!updateBundlesInfo(bundle, getLocationForBundlesInfo(extractionFolderName))) { StatusFileModificator.createStatusFile( warName, this.pickupDir, StatusFileModificator.OP_DEPLOY, STATUS_ERROR, bundle.getBundleId(), lastModified); return STATUS_ERROR; } StatusFileModificator.createStatusFile( warName, this.pickupDir, StatusFileModificator.OP_DEPLOY, STATUS_OK, bundle.getBundleId(), lastModified); return STATUS_OK; }
@Test public void testIsFrameworkBundle() { final Bundle bundle = Mockito.mock(Bundle.class); Mockito.when(bundle.getBundleId()).thenReturn(1L); assertFalse(OsgiHelper.isFrameworkBundle(bundle)); Mockito.when(bundle.getBundleId()).thenReturn(0L); assertTrue(OsgiHelper.isFrameworkBundle(bundle)); }
@Override public void bundleChanged(BundleEvent event) { Bundle bundle = event.getBundle(); if (event.getType() == BundleEvent.STARTED) { logger.info( String.format( "Starting %s [%d] bundle.", bundle.getSymbolicName(), bundle.getBundleId())); } else if (event.getType() == BundleEvent.STOPPED) { logger.info( String.format( "Stopping %s [%d] bundle.", bundle.getSymbolicName(), bundle.getBundleId())); } }
private void considerTracking(Bundle bundle) { BundleManager existing = bundleManagers.get(bundle.getBundleId()); if (existing == null) { BundleManager bundleManager = BundleManager.manage(bundle, asynch, queuer); if (bundleManager != null) { storeBundleManager(bundle.getBundleId(), bundleManager); launchUnhostedModuleSpecifications(bundleManager); log.info(this + " tracks bundle " + bundle + ": " + bundleManager); } } else { log.info(this + " already tracking " + bundle + ": " + existing); } }
public void testMbeans() throws MalformedObjectNameException, BundleException, InstanceNotFoundException, ReflectionException, MBeanException, AttributeNotFoundException { MBeanServer server = ManagementFactory.getPlatformMBeanServer(); ObjectName digraphName = new ObjectName(REGION_DOMAIN_PROP + ":type=RegionDigraph,*"); ObjectName regionNameAllQuery = new ObjectName(REGION_DOMAIN_PROP + ":type=Region,name=*,*"); Set<ObjectInstance> digraphs = server.queryMBeans(null, digraphName); assertEquals("Expected only one instance of digraph", 1, digraphs.size()); Set<ObjectInstance> regions = server.queryMBeans(null, regionNameAllQuery); assertEquals("Expected only one instance of region", 1, regions.size()); Region pp1Region = digraph.createRegion(PP1); Bundle pp1Bundle = bundleInstaller.installBundle(PP1, pp1Region); Region sp1Region = digraph.createRegion(SP1); Bundle sp1Bundle = bundleInstaller.installBundle(SP1, sp1Region); regions = server.queryMBeans(null, regionNameAllQuery); assertEquals("Wrong number of regions", 3, regions.size()); Set<ObjectInstance> pp1Query = server.queryMBeans(null, new ObjectName(REGION_DOMAIN_PROP + ":type=Region,name=" + PP1 + ",*")); assertEquals("Expected only one instance of: " + PP1, 1, pp1Query.size()); Set<ObjectInstance> sp1Query = server.queryMBeans(null, new ObjectName(REGION_DOMAIN_PROP + ":type=Region,name=" + SP1 + ",*")); assertEquals("Expected only one instance of: " + SP1, 1, sp1Query.size()); ObjectName pp1Name = (ObjectName) server.invoke(digraphs.iterator().next().getObjectName(), "getRegion", new Object[] {PP1}, new String[] {String.class.getName()}); assertEquals(PP1 + " regions not equal.", pp1Query.iterator().next().getObjectName(), pp1Name); ObjectName sp1Name = (ObjectName) server.invoke(digraphs.iterator().next().getObjectName(), "getRegion", new Object[] {SP1}, new String[] {String.class.getName()}); assertEquals(SP1 + " regions not equal.", sp1Query.iterator().next().getObjectName(), sp1Name); // test non existing region ObjectName shouldNotExistName = (ObjectName) server.invoke(digraphs.iterator().next().getObjectName(), "getRegion", new Object[] {"ShouldNotExist"}, new String[] {String.class.getName()}); assertNull("Should not exist", shouldNotExistName); long[] bundleIds = (long[]) server.getAttribute(pp1Name, "BundleIds"); assertEquals("Wrong number of bundles", 1, bundleIds.length); assertEquals("Wrong bundle", pp1Bundle.getBundleId(), bundleIds[0]); String name = (String) server.getAttribute(pp1Name, "Name"); assertEquals("Wrong name", PP1, name); bundleIds = (long[]) server.getAttribute(sp1Name, "BundleIds"); assertEquals("Wrong number of bundles", 1, bundleIds.length); assertEquals("Wrong bundle", sp1Bundle.getBundleId(), bundleIds[0]); name = (String) server.getAttribute(sp1Name, "Name"); assertEquals("Wrong name", SP1, name); regionBundle.stop(); // Now make sure we have no mbeans digraphs = server.queryMBeans(digraphName, null); assertEquals("Wrong number of digraphs", 0, digraphs.size()); regions = server.queryMBeans(null, regionNameAllQuery); assertEquals("Wrong number of regions", 0, regions.size()); }
public synchronized long install(InputStream stream) { try { Bundle b = m_framework.getBundleContext().installBundle("local", stream); m_installed.push(b.getBundleId()); LOG.debug("Installed bundle " + b.getSymbolicName() + " as Bundle ID " + b.getBundleId()); setBundleStartLevel(b.getBundleId(), Constants.START_LEVEL_TEST_BUNDLE); // stream.close(); b.start(); return b.getBundleId(); } catch (BundleException e) { e.printStackTrace(); } return -1; }
/** * You will get a list of bundles installed by default plus your testcase, wrapped into a bundle * called pax-exam-probe */ @Test public void listBundles() { for (Bundle b : bundleContext.getBundles()) { if (b.getState() != Bundle.ACTIVE && b.getState() != Bundle.RESOLVED) fail("Bundle should be active: " + b); Dictionary headers = b.getHeaders(); String ctxtPath = (String) headers.get(WEB_CONTEXT_PATH); if (ctxtPath != null) System.out.println( "Bundle " + b.getBundleId() + " : " + b.getSymbolicName() + " : " + ctxtPath); else System.out.println("Bundle " + b.getBundleId() + " : " + b.getSymbolicName()); } }
/* * (non-Javadoc) * * @see org.araqne.bundle.BundleManager#installBundle(org.araqne.pkg. * ProgressMonitor, java.lang.String, java.lang.String, java.lang.String) */ @Override public long installBundle( ProgressMonitor monitor, String groupId, String artifactId, String version) throws MavenResolveException { MavenResolver resolver = new MavenResolver( getLocalRepository(), config.getRepositories(), monitor, getKeyStoreManager()); Version v = (version != null) ? new Version(version) : null; MavenArtifact artifact = new MavenArtifact(groupId, artifactId, v); if (isBuiltinArtifact(artifact.getGroupId(), artifact.getArtifactId())) throw new IllegalStateException("provided in system bundle"); if (monitor != null) monitor.writeln( String.format("Resolving %s/%s", artifact.getGroupId(), artifact.getArtifactId()) + (artifact.getVersion() != null ? (" (" + artifact.getVersion() + ")") : "")); File file = resolver.resolve(artifact); if (!isBundleJar(file)) throw new IllegalStateException( "invalid OSGi bundle: " + groupId + "/" + artifactId + " (" + version + ")"); String filePath = file.getAbsolutePath(); try { Bundle newBundle = context.installBundle(getPrefix() + filePath.replace('\\', '/')); if (newBundle.getSymbolicName() == null) newBundle.uninstall(); return newBundle.getBundleId(); } catch (BundleException e) { throw new IllegalStateException(e); } }
private void initializeProperties(Dictionary<String, Object> dict) { // Create a case-insensitive map for the properties. Map<String, Object> props = new StringMap(); if (dict != null) { // Make sure there are no duplicate keys. Enumeration<String> keys = dict.keys(); while (keys.hasMoreElements()) { String key = keys.nextElement(); if (props.get(key) == null) { props.put(key, dict.get(key)); } else { throw new IllegalArgumentException("Duplicate service property: " + key); } } } // Add the framework assigned properties. props.put(Constants.OBJECTCLASS, m_classes); props.put(Constants.SERVICE_ID, m_serviceId); props.put(Constants.SERVICE_BUNDLEID, m_bundle.getBundleId()); if (m_factory != null) { props.put( Constants.SERVICE_SCOPE, (m_factory instanceof PrototypeServiceFactory ? Constants.SCOPE_PROTOTYPE : Constants.SCOPE_BUNDLE)); } else { props.put(Constants.SERVICE_SCOPE, Constants.SCOPE_SINGLETON); } // Update the service property map. m_propMap = props; }
private static ServiceReferenceDTO getServiceReferenceDTO(ServiceReference<?> ref) { if (ref == null) { return null; } Bundle b = ref.getBundle(); if (b == null) { // service has been unregistered return null; } ServiceReferenceDTO dto = new ServiceReferenceDTO(); dto.bundle = b.getBundleId(); String[] keys = ref.getPropertyKeys(); Map<String, Object> properties = newMap(keys.length); for (String k : keys) { Object v = ref.getProperty(k); if (Constants.SERVICE_ID.equals(k)) { dto.id = ((Long) v).longValue(); } properties.put(k, mapValue(v)); } dto.properties = properties; Bundle[] using = ref.getUsingBundles(); final int length = (using == null) ? 0 : using.length; long[] usingBundles = new long[length]; for (int i = 0; i < length; i++) { usingBundles[i] = using[i].getBundleId(); } dto.usingBundles = usingBundles; return dto; }
@SuppressWarnings("deprecation") public void testAllResolved() { assertNotNull("Expected a Bundle Context", context); StringBuilder sb = new StringBuilder(); for (Bundle b : context.getBundles()) { if (b.getState() == Bundle.INSTALLED && b.getHeaders().get(aQute.bnd.osgi.Constants.FRAGMENT_HOST) == null) { try { b.start(); } catch (BundleException e) { sb.append(b.getBundleId()) .append(" ") .append(b.getSymbolicName()) .append(";") .append(b.getVersion()) .append("\n"); sb.append(" ").append(e.getMessage()).append("\n\n"); System.err.println(e.getMessage()); } } } Matcher matcher = IP_P.matcher(sb); String out = matcher.replaceAll( "\n\n " + aQute.bnd.osgi.Constants.IMPORT_PACKAGE + ": $1;version=[$2,$3)\n"); assertTrue("Unresolved bundles\n" + out, sb.length() == 0); }
private String[] getStringProperty(String name, Object value) { // Don't log a warning if the value is null. The filter guarantees at least one of the necessary // properties // is there. If others are not, this method will get called with value equal to null. if (value == null) return new String[0]; if (value instanceof String) { return new String[] {(String) value}; } if (value instanceof String[]) { return (String[]) value; } Exception e = null; if (value instanceof Collection) { @SuppressWarnings("unchecked") Collection<String> temp = (Collection<String>) value; try { return temp.toArray(new String[temp.size()]); } catch (ArrayStoreException ase) { e = ase; } } log.log( LogService.LOG_WARNING, NLS.bind( MetaTypeMsg.INVALID_PID_METATYPE_PROVIDER_IGNORED, new Object[] {_bundle.getSymbolicName(), _bundle.getBundleId(), name, value}), e); return new String[0]; }
/** * Register namespaces defined in the bundle in the namespace table. * * @param bundle The bundle. */ private void registerNamespaces(Bundle bundle) { final String definition = (String) bundle.getHeaders().get(NAMESPACES_BUNDLE_HEADER); if (definition != null) { log.debug( "registerNamespaces: Bundle {} tries to register: {}", bundle.getSymbolicName(), definition); final StringTokenizer st = new StringTokenizer(definition, ","); final List<NamespaceEntry> entries = new ArrayList<NamespaceEntry>(); while (st.hasMoreTokens()) { final String token = st.nextToken().trim(); int pos = token.indexOf('='); if (pos == -1) { log.warn( "registerNamespaces: Bundle {} has an invalid namespace manifest header entry: {}", bundle.getSymbolicName(), token); } else { final String prefix = token.substring(0, pos).trim(); final String namespace = token.substring(pos + 1).trim(); entries.add(new NamespaceEntry(prefix, namespace)); } } if (entries.size() > 0) { this.namespaceTable.put( bundle.getBundleId(), entries.toArray(new NamespaceEntry[entries.size()])); } } }
@Override public int complete(String buffer, int cursor, List<CharSequence> candidates) { Bundle[] bundles = bundleContext.getBundles(); List<Long> bundleIds = new ArrayList<Long>(); for (Bundle b : bundles) { if (matcher.bundleMatches(b)) { bundleIds.add(b.getBundleId()); } } SortedSet<String> variants = new TreeSet<String>(); if (buffer.matches("^[0-9]+$")) { for (Long l : bundleIds) { variants.add(String.valueOf(l)); } } else { for (Long l : bundleIds) { variants.add(bundleContext.getBundle(l).getSymbolicName()); } } if (buffer.isEmpty()) { candidates.addAll(variants); } else { for (String match : variants.tailSet(buffer)) { if (!match.startsWith(buffer)) { break; } candidates.add(match.substring(buffer.length())); } } return candidates.isEmpty() ? -1 : buffer.length(); }
@Override public Object execute() throws Exception { List<Exception> exceptions = new ArrayList<Exception>(); List<Bundle> bundles = new ArrayList<Bundle>(); for (String url : urls) { try { bundles.add(bundleContext.installBundle(url, null)); } catch (Exception e) { exceptions.add(new Exception("Unable to install bundle " + url, e)); } } if (start) { for (Bundle bundle : bundles) { try { bundle.start(); } catch (Exception e) { exceptions.add(new Exception("Unable to start bundle " + bundle.getLocation(), e)); } } } if (bundles.size() == 1) { System.out.println("Bundle ID: " + bundles.get(0).getBundleId()); } else { StringBuffer sb = new StringBuffer("Bundle IDs: "); for (Bundle bundle : bundles) { if (sb.length() > 0) { sb.append(", "); } sb.append(bundle.getBundleId()); } System.out.println(sb); } MultiException.throwIf("Error installing bundles", exceptions); return null; }
public long installBundle(String location) { try { Bundle b = Activator.bc.installBundle(location); return b.getBundleId(); } catch (BundleException e) { throw new IllegalArgumentException("Failed to install location=" + location); } }
public int compareTo(Bundle other) { long thisBundleId = getBundleId(); long otherBundleId = other.getBundleId(); if (thisBundleId < otherBundleId) return -1; else if (thisBundleId == otherBundleId) return 0; else return 1; }
private StringBuffer printBundleHeaderLine(Bundle bundle, StringBuffer buffer) { buffer.append(Long.toString(bundle.getBundleId())).append(','); buffer.append(bundle.getHeaders().get(Constants.BUNDLE_SYMBOLICNAME)).append(','); buffer.append(bundle.getLocation()).append(','); buffer.append(printBundleState(bundle)); return buffer; }
private ConnectorEvent buildEvent(String topic, Bundle bundle, ConnectorKey connectorKey) { ConnectorEvent event = new ConnectorEvent(topic, connectorKey); event.getProperties().put(ConnectorEvent.BUNDLE_SYMBOLICNAME, bundle.getSymbolicName()); event.getProperties().put(ConnectorEvent.BUNDLE_ID, bundle.getBundleId()); event.getProperties().put(ConnectorEvent.BUNDLE, bundle); event.getProperties().put(ConnectorEvent.BUNDLE_VERSION, bundle.getVersion()); return event; }
public void removedBundle(Bundle bundle, BundleEvent event, Object object) { LOG.debug("Bundle stopped: {}", bundle.getSymbolicName()); List<BaseService> r = resolvers.remove(bundle.getBundleId()); if (r != null) { for (BaseService service : r) { service.unregister(); } } }
/** * @param b * @param sb */ private static void getBundleLabel(Bundle b, StringBuilder sb) { if (b == null) return; appendId(sb, b.getBundleId()); getBundleName(b, sb); sb.append(" ("); getBundleVersion(b, sb); sb.append(")"); }
public void setBundle(Bundle b) { try { MetaTypeInformation mtp = Activator.getMTP(b); jcmInfo.setProvider(mtp, b); } catch (Exception e) { e.printStackTrace(); Activator.log.error("Failed to get MetaTypeInformation from bundle " + b.getBundleId(), e); } }
@Override public void spool(Iterable<Bundle> bundles) { for (Bundle bundle : bundles) { this.bundles.getBundle(bundle.getBundleId()); if (bundle.getState() == Bundle.ACTIVE) { considerTracking(bundle); } } }
public synchronized void load(TypeConverterRegistry registry) throws TypeConverterLoaderException { // must be synchronized to ensure we don't load type converters concurrently // which cause Camel apps to fails in OSGi thereafter try { loader.load(registry); } catch (Exception e) { throw new TypeConverterLoaderException( "Cannot load type converters using OSGi bundle: " + bundle.getBundleId(), e); } }
public static BundleStartLevelDTO newBundleStartLevelDTO(Bundle b, BundleStartLevel bsl) { if (bsl == null) { return null; } BundleStartLevelDTO dto = new BundleStartLevelDTO(); dto.bundle = b.getBundleId(); dto.activationPolicyUsed = bsl.isActivationPolicyUsed(); dto.persistentlyStarted = bsl.isPersistentlyStarted(); dto.startLevel = bsl.getStartLevel(); return dto; }
public IWeavingAdaptor getHostBundleAdaptor(final long bundleID) { final Bundle bundle = this.bundleContext.getBundle(bundleID); if (bundle != null) { final Bundle host = adaptorFactory.getHost(bundle); if (host != null) { final long hostBundleID = host.getBundleId(); return this.adaptors.get(hostBundleID); } } return null; }
private void addSWTJars(List rtes) { if (fgSWTEntries == null) { fgSWTEntries = new ArrayList(); Bundle bundle = Platform.getBundle("org.eclipse.swt"); // $NON-NLS-1$ BundleDescription description = Platform.getPlatformAdmin().getState(false).getBundle(bundle.getBundleId()); BundleDescription[] fragments = description.getFragments(); for (int i = 0; i < fragments.length; i++) { Bundle fragmentBundle = Platform.getBundle(fragments[i].getName()); URL bundleURL; try { bundleURL = FileLocator.resolve(fragmentBundle.getEntry("/")); // $NON-NLS-1$ } catch (IOException e) { AntLaunching.log(e); continue; } String urlFileName = bundleURL.getFile(); if (urlFileName.startsWith("file:")) { // $NON-NLS-1$ try { urlFileName = new URL(urlFileName).getFile(); if (urlFileName.endsWith("!/")) { // $NON-NLS-1$ urlFileName = urlFileName.substring(0, urlFileName.length() - 2); } } catch (MalformedURLException e) { AntLaunching.log(e); continue; } } IPath fragmentPath = new Path(urlFileName); if (fragmentPath.getFileExtension() != null) { // JAR file fgSWTEntries.add(JavaRuntime.newArchiveRuntimeClasspathEntry(fragmentPath)); } else { // folder File bundleFolder = fragmentPath.toFile(); if (!bundleFolder.isDirectory()) { continue; } String[] names = bundleFolder.list( new FilenameFilter() { public boolean accept(File dir, String name) { return name.endsWith(".jar"); // $NON-NLS-1$ } }); for (int j = 0; j < names.length; j++) { String jarName = names[j]; fgSWTEntries.add( JavaRuntime.newArchiveRuntimeClasspathEntry(fragmentPath.append(jarName))); } } } } rtes.addAll(fgSWTEntries); }
@Test public void testOSGi() throws Exception { Assert.assertNotNull(bundleContext); Bundle bundle = bundleContext.getBundle(); System.out.println("symbolic name " + bundle.getSymbolicName()); System.out.println("vendor " + bundleContext.getProperty(Constants.FRAMEWORK_VENDOR)); for (Bundle b : bundleContext.getBundles()) { System.out.println(b.getSymbolicName() + " " + b.getBundleId()); } }