Java Code Examples for org.osgi.framework.Bundle#getLocation()

The following examples show how to use org.osgi.framework.Bundle#getLocation() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: Util.java    From knopflerfish.org with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public static String shortName(Bundle b) {
  if(b == null) {
    return "";
  }

  String s = b.getLocation();
  int ix = s.lastIndexOf("/");
  if(ix == -1) ix = s.lastIndexOf("\\");
  if(ix != -1) {
    s = s.substring(ix + 1);
  }
  if(s.endsWith(".jar")) {
    s = s.substring(0, s.length() - 4);
  }
  return s;
}
 
Example 2
Source File: ClassLoaderUtilsTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Test
public void testLoadClassInOsgiCore() throws Exception {
    Class<?> clazz = BasicEntity.class;
    String classname = clazz.getName();
    
    mgmt = LocalManagementContextForTests.builder(true).enableOsgiReusable().build();
    Bundle bundle = getBundle(mgmt, "org.apache.brooklyn.core");
    String url = bundle.getLocation();
    // NB: the above will be a system:file: url when running tests against target/classes/ -- but
    // OSGi manager will accept that if running in dev mode
    Entity entity = createSimpleEntity(url, clazz);
    
    ClassLoaderUtils cluMgmt = new ClassLoaderUtils(getClass(), mgmt);
    ClassLoaderUtils cluClass = new ClassLoaderUtils(clazz);
    ClassLoaderUtils cluNone = new ClassLoaderUtils(getClass());
    ClassLoaderUtils cluEntity = new ClassLoaderUtils(getClass(), entity);
    
    assertLoadSucceeds(classname, clazz, cluMgmt, cluClass, cluNone, cluEntity);
    assertLoadSucceeds(classname, clazz, cluMgmt, cluClass, cluNone, cluEntity);
    assertLoadSucceeds(bundle.getSymbolicName() + ":" + classname, clazz, cluMgmt, cluClass, cluNone, cluEntity);
    assertLoadSucceeds(bundle.getSymbolicName() + ":" + bundle.getVersion() + ":" + classname, clazz, cluMgmt, cluClass, cluNone, cluEntity);
}
 
Example 3
Source File: ConfigurationAdminFactory.java    From knopflerfish.org with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
private Set<String> removeFromLocationToPids(ServiceReference<?> sr)
{
  HashSet<String> res = new HashSet<String>();
  if (sr != null) {
    Bundle bundle = sr.getBundle();
    final String bundleLocation = bundle.getLocation();
    final Hashtable<String, TreeSet<ServiceReference<?>>> pidsForLocation =
      locationToPids.get(bundleLocation);
    for (final Iterator<Entry<String, TreeSet<ServiceReference<?>>>> it =
      pidsForLocation.entrySet().iterator(); it.hasNext();) {
      final Entry<String, TreeSet<ServiceReference<?>>> entry = it.next();
      TreeSet<ServiceReference<?>> ssrs = entry.getValue();
      if (ssrs.remove(sr)) {
        res.add(entry.getKey());
        if (ssrs.isEmpty()) {
          it.remove();
        }
      }
    }
    if (pidsForLocation.isEmpty()) {
      locationToPids.remove(bundleLocation);
    }
  }
  return res;
}
 
Example 4
Source File: Util.java    From knopflerfish.org with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public static String shortName(Bundle b) {
  String s = b.getLocation();
  if (null==s) {
    // Remote, uninstalled bundle may give null location.
    return String.valueOf(b.getBundleId());
  }
  int ix = s.lastIndexOf("/");
  if(ix == -1) {
    ix = s.lastIndexOf("\\");
  }
  if(ix != -1) {
    s = s.substring(ix + 1);
  }
  if(s.endsWith(".jar")) {
    s = s.substring(0, s.length() - 4);
  }
  return s;
}
 
Example 5
Source File: TargetPanel.java    From knopflerfish.org with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Update this panel to show configurations for another PID and bundle.
 *
 * @param pid
 *          The (non-targeted) PID to show in this panel.
 * @param bundle
 *          The bundle to do targeted PIDs.
 * @param isFactoryPid
 *          Set to {@code true} to indicate that the specified PID is a
 *          factory PID.
 */
void updateTargeted(final String pid,
                    final Bundle bundle,
                    boolean isFactoryPid)
{
  targetedPids[0] = pid;
  this.isFactoryPid = isFactoryPid;

  if (bundle != null) {
    targetedPids[1] = targetedPids[0] + "|" + bundle.getSymbolicName();
    targetedPids[2] = targetedPids[1] + "|" + bundle.getVersion().toString();
    targetedPids[3] = targetedPids[2] + "|" + bundle.getLocation();
  } else {
    targetedPids[1] = null;
    targetedPids[2] = null;
    targetedPids[3] = null;
  }

  // No target selection for the system bundle or the CM bundle when handling
  // a non-factory PID.
  targetSelectionBox.setVisible(!CMDisplayer.isCmBundle(bundle)
                                && !CMDisplayer.isSystemBundle(bundle));

  updateSelection();
}
 
Example 6
Source File: Util.java    From knopflerfish.org with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Get short name of specified bundle. First, try to get the BUNDLE-NAME
 * header. If it fails use the location of the bundle with all characters upto
 * and including the last '/' or '\' and any trailing ".jar" stripped off.
 *
 * @param bundle
 *          the bundle
 * @return The bundles shortname or null if input was null
 */
public static String shortName(Bundle bundle)
{
  if (bundle == null) {
    return null;
  }
  String n = bundle.getHeaders().get("Bundle-Name");
  if (n == null) {
    n = bundle.getLocation();
    int x = n.lastIndexOf('/');
    final int y = n.lastIndexOf('\\');
    if (y > x) {
      x = y;
    }
    if (x != -1) {
      n = n.substring(x + 1);
    }
    if (n.endsWith(".jar")) {
      n = n.substring(0, n.length() - 4);
    }
  }
  return n;
}
 
Example 7
Source File: LogConfigCommandGroup.java    From knopflerfish.org with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
private void setValidBundles(LogConfig configuration,
                             String[] givenBundles,
                             int level)
{
  String location = null;
  for (int i = givenBundles.length - 1; i >= 0; i--) {
    location = givenBundles[i].trim();
    try {
      final long id = Long.parseLong(location);
      final Bundle bundle = LogCommands.bc.getBundle(id);
      if (null != bundle) {
        location = Util.symbolicName(bundle);
        if (null == location || 0 == location.length()) {
          location = bundle.getLocation();
        }
      } else {
        location = null;
      }
    } catch (final NumberFormatException nfe) {
    }
    if (location != null && location.length() > 0) {
      configuration.setFilter(location, level);
    }
  }
}
 
Example 8
Source File: ReadyMarkerUtils.java    From openhab-core with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Provides a string to debug bundle information.
 *
 * @param bundle the bundle
 * @return a debug string
 */
public static String debugString(final Bundle bundle) {
    return "Bundle [getState()=" + bundle.getState() + ", getHeaders()=" + bundle.getHeaders() + ", getBundleId()="
            + bundle.getBundleId() + ", getLocation()=" + bundle.getLocation() + ", getRegisteredServices()="
            + Arrays.toString(bundle.getRegisteredServices()) + ", getServicesInUse()="
            + Arrays.toString(bundle.getServicesInUse()) + ", getSymbolicName()=" + bundle.getSymbolicName()
            + ", getLastModified()=" + bundle.getLastModified() + ", getBundleContext()="
            + bundle.getBundleContext() + ", getVersion()=" + bundle.getVersion() + "]";
}
 
Example 9
Source File: AppDeployerUtils.java    From micro-integrator with Apache License 2.0 5 votes vote down vote up
/**
 * Computes the application artifact file path when the bundle is given
 *
 * @param b - App artifact as an OSGi bundle
 * @return - App file path
 */
public static String getArchivePathFromBundle(Bundle b) {
    //compute app file path
    String bundlePath = b.getLocation();
    bundlePath = formatPath(bundlePath);
    return MicroIntegratorBaseUtils.getComponentsRepo() + File.separator +
            bundlePath.substring(bundlePath.lastIndexOf('/') + 1);
}
 
Example 10
Source File: Util.java    From knopflerfish.org with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public static String getBundleName(Bundle b)
{
  if (b == null) {
    return "null";
  }
  String s = getHeader(b, "Bundle-Name", "");
  if (s == null || "".equals(s) || s.startsWith("%")) {
    final String loc = b.getLocation();
    if (loc != null) {
      s = shortLocation(b.getLocation());
    }
  }

  return s;
}
 
Example 11
Source File: Spin.java    From knopflerfish.org with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public static String shortName(Bundle b) {
  String s = b.getLocation();
  int ix = s.lastIndexOf("/");
  if(ix == -1) ix = s.lastIndexOf("\\");
  if(ix != -1) {
    s = s.substring(ix + 1);
  }
  if(s.endsWith(".jar")) s = s.substring(0, s.length() - 4);
  return s;
}
 
Example 12
Source File: NetigsoLoader.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
public String toString() {
    Bundle b = bundle;
    if (b == null) {
        return "uninitialized";
    }
    return b.getLocation();
}
 
Example 13
Source File: Netigso.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private static Set<String> toActivate(Framework f, Collection<? extends Module> allModules) {
    ServiceReference sr = f.getBundleContext().getServiceReference("org.osgi.service.packageadmin.PackageAdmin"); // NOI18N
    if (sr == null) {
        return null;
    }
    PackageAdmin pkgAdm = (PackageAdmin)f.getBundleContext().getService(sr);
    if (pkgAdm == null) {
        return null;
    }
    Set<String> allCnbs = new HashSet<String>(allModules.size() * 2);
    for (ModuleInfo m : allModules) {
        allCnbs.add(m.getCodeNameBase());
    }
    
    Set<String> needEnablement = new HashSet<String>();
    for (Bundle b : f.getBundleContext().getBundles()) {
        String loc = b.getLocation();
        if (loc.startsWith("netigso://")) {
            loc = loc.substring("netigso://".length());
        } else {
            continue;
        }
        RequiredBundle[] arr = pkgAdm.getRequiredBundles(loc);
        if (arr != null) for (RequiredBundle rb : arr) {
            for (Bundle n : rb.getRequiringBundles()) {
                if (allCnbs.contains(n.getSymbolicName().replace('-', '_'))) {
                    needEnablement.add(loc);
                }
            }
        }
    }
    return needEnablement;
}
 
Example 14
Source File: Shell.java    From concierge with Eclipse Public License 1.0 4 votes vote down vote up
private String nameOrLocation(final Bundle b) {
	final Object name = b.getHeaders().get("Bundle-Name");
	return name != null ? name.toString() : b.getLocation();
}
 
Example 15
Source File: OsgiSwaggerUiResolver.java    From cxf with Apache License 2.0 4 votes vote down vote up
@Override
public String findSwaggerUiRootInternal(String swaggerUiMavenGroupAndArtifact,
                                           String swaggerUiVersion) {
    try {
        Bundle bundle = FrameworkUtil.getBundle(annotationBundle);
        if (bundle == null) {
            return null;
        }
        if (bundle.getState() != Bundle.ACTIVE) {
            bundle.start();
        }
        String[] locations = swaggerUiMavenGroupAndArtifact == null ? DEFAULT_LOCATIONS
            : new String[]{"mvn:" + swaggerUiMavenGroupAndArtifact + "/",
                           "wrap:mvn:" + swaggerUiMavenGroupAndArtifact + "/"};
        
        for (Bundle b : bundle.getBundleContext().getBundles()) {
            String location = b.getLocation();

            for (String pattern: locations) {
                if (swaggerUiVersion != null) {
                    if (location.equals(pattern + swaggerUiVersion)) {
                        return getSwaggerUiRoot(b, swaggerUiVersion);
                    }
                } else if (location.startsWith(pattern)) {
                    int dollarIndex = location.indexOf('$');
                    swaggerUiVersion = location.substring(pattern.length(),
                            dollarIndex > pattern.length() ? dollarIndex : location.length());
                    return getSwaggerUiRoot(b, swaggerUiVersion);
                }
            }
            if (swaggerUiMavenGroupAndArtifact == null) {
                String rootCandidate = getSwaggerUiRoot(b, swaggerUiVersion);
                if (rootCandidate != null) {
                    return rootCandidate;
                }
            }
        }
    } catch (Throwable ex) {
        // ignore
    }
    return null;
}
 
Example 16
Source File: ConfigurationAdminFactory.java    From knopflerfish.org with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
ConfigurationAdminImpl(final Bundle callingBundle)
{
  this.callingBundle = callingBundle;
  this.callingBundleLocation = callingBundle.getLocation();
}
 
Example 17
Source File: ComponentTestSuite.java    From knopflerfish.org with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
/**
 * Test that SCR handles factory CM pids with target filters.
 * 
 */

public void runTest() {
  Bundle b1 = null;
  ServiceTracker<ConfigurationAdmin, ConfigurationAdmin> cmt = null;
  try {
    b1 = Util.installBundle(bc, "componentC_test-1.0.0.jar");
    b1.start();
    final String b1loc = b1.getLocation();

    cmt = new ServiceTracker<ConfigurationAdmin,ConfigurationAdmin>(bc, ConfigurationAdmin.class.getName(), null);
    cmt.open();
    
    Thread.sleep(SLEEP_TIME);

    ServiceReference<?> ref = bc.getServiceReference("org.knopflerfish.service.componentC_test.ComponentU");
    assertNull("Should not get serviceRef U", ref);

    ConfigurationAdmin ca = cmt.getService();
    Configuration c = ca.createFactoryConfiguration("componentC_test.U", b1loc);

    Dictionary<String, Object> props = new Hashtable<String, Object>();
    props.put("vRef.target", "(vnum=v0)");
    c.update(props);
    
    Thread.sleep(SLEEP_TIME);

    ref = bc.getServiceReference("org.knopflerfish.service.componentC_test.ComponentU");
    assertNull("Should not get serviceRef U", ref);

    props.put("vRef.target", "(vnum=v1)");
    c.update(props);
    
    Thread.sleep(SLEEP_TIME);

    ServiceReference<?> [] refs = bc.getServiceReferences("org.knopflerfish.service.componentC_test.ComponentU", null);
    assertTrue("Should get one serviceRef to ComponentU", refs != null && refs.length == 1);

    Configuration c2 = ca.createFactoryConfiguration("componentC_test.U", b1loc);
    props = new Hashtable<String, Object>();
    props.put("vRef.target", "(vnum=v2)");
    c2.update(props);
    
    Thread.sleep(SLEEP_TIME);

    refs = bc.getServiceReferences("org.knopflerfish.service.componentC_test.ComponentU", null);
    assertTrue("Should get two serviceRef to ComponentU", refs != null && refs.length == 2);

    refs = bc.getServiceReferences("org.knopflerfish.service.componentC_test.ComponentU", "(vRef.target=\\(vnum=v1\\))");
    assertTrue("Should get one serviceRef to ComponentU with ref v1", refs != null && refs.length == 1);
    org.knopflerfish.service.componentC_test.ComponentU u =
        (org.knopflerfish.service.componentC_test.ComponentU)bc.getService(refs[0]);
    assertEquals("Should get v1 version", "v1", u.getV());

    refs = bc.getServiceReferences("org.knopflerfish.service.componentC_test.ComponentU", "(vRef.target=\\(vnum=v2\\))");
    assertTrue("Should get one serviceRef to ComponentU with ref v2", refs != null && refs.length == 1);
    org.knopflerfish.service.componentC_test.ComponentU u2 =
        (org.knopflerfish.service.componentC_test.ComponentU)bc.getService(refs[0]);
    assertNotSame("Services should differ", u, u2);
    assertEquals("Should get v2 version", "v2", u2.getV());
  } catch (Exception e) {
    e.printStackTrace();
    fail("Test11: got unexpected exception " + e);
  } finally {
    if (b1 != null) {
      try {
        if (cmt != null) {
          deleteConfig(cmt.getService(), b1.getLocation());
          cmt.close();
        }
        b1.uninstall();
      } catch (Exception be) {
        be.printStackTrace();
        fail("Test11: got uninstall exception " + be);
      }
    }
  }
}
 
Example 18
Source File: DelegateResources.java    From ACDD with MIT License 4 votes vote down vote up
@Override
public int getIdentifier(String name, String defType, String defPackage) {
    int identifier = super.getIdentifier(name, defType, defPackage);
    if (identifier != 0) {
        return identifier;
    }
    if (VERSION.SDK_INT <= 19) {
        return 0;
    }
    if (defType == null && defPackage == null) {
        String substring = name.substring(name.indexOf("/") + 1);
        defType = name.substring(name.indexOf(":") + 1, name.indexOf("/"));
        name = substring;
    }
    if (TextUtils.isEmpty(name) || TextUtils.isEmpty(defType)) {
        return 0;
    }
    List<?> bundles = Framework.getBundles();
    if (!(bundles == null || bundles.isEmpty())) {
        for (Bundle bundle : Framework.getBundles()) {
            String location = bundle.getLocation();
            String nameWithPkg = location + ":" + name;
            if (!this.resIdentifierMap.isEmpty() && this.resIdentifierMap.containsKey(nameWithPkg)) {
                int intValue = this.resIdentifierMap.get(nameWithPkg).intValue();
                if (intValue != 0) {
                    return intValue;
                }
            }
            BundleImpl bundleImpl = (BundleImpl) bundle;
            if (bundleImpl.getArchive().isDexOpted()) {
                ClassLoader classLoader = bundleImpl.getClassLoader();
                if (classLoader != null) {
                    try {
                        StringBuilder stringBuilder = new StringBuilder(location);
                        stringBuilder.append(".R$");
                        stringBuilder.append(defType);
                        identifier = getFieldValueOfR(classLoader.loadClass(stringBuilder.toString()), name);
                        if (identifier != 0) {
                            this.resIdentifierMap.put(nameWithPkg, Integer.valueOf(identifier));
                            return identifier;
                        }
                    } catch (ClassNotFoundException e) {
                    }
                } else {
                    continue;
                }
            }
        }
    }
    return 0;
}
 
Example 19
Source File: DelegateResources.java    From AtlasForAndroid with MIT License 4 votes vote down vote up
public int getIdentifier(String str, String str2, String str3) {
    int identifier = super.getIdentifier(str, str2, str3);
    if (identifier != 0) {
        return identifier;
    }
    if (str2 == null && str3 == null) {
        str = str.substring(str.indexOf(FilePathGenerator.ANDROID_DIR_SEP) + 1);
        str2 = str.substring(str.indexOf(":") + 1, str.indexOf(FilePathGenerator.ANDROID_DIR_SEP));
    }
    if (TextUtils.isEmpty(str) || TextUtils.isEmpty(str2)) {
        return 0;
    }
    List bundles = Framework.getBundles();
    if (!(bundles == null || bundles.isEmpty())) {
        for (Bundle bundle : Framework.getBundles()) {
            String location = bundle.getLocation();
            String str4 = location + ":" + str;
            if (!this.resIdentifierMap.isEmpty() && this.resIdentifierMap.containsKey(str4)) {
                int intValue = ((Integer) this.resIdentifierMap.get(str4)).intValue();
                if (intValue != 0) {
                    return intValue;
                }
            }
            BundleImpl bundleImpl = (BundleImpl) bundle;
            if (bundleImpl.getArchive().isDexOpted()) {
                ClassLoader classLoader = bundleImpl.getClassLoader();
                if (classLoader != null) {
                    try {
                        StringBuilder stringBuilder = new StringBuilder(location);
                        stringBuilder.append(".R$");
                        stringBuilder.append(str2);
                        identifier = getFieldValueOfR(classLoader.loadClass(stringBuilder.toString()), str);
                        if (identifier != 0) {
                            this.resIdentifierMap.put(str4, Integer.valueOf(identifier));
                            return identifier;
                        }
                    } catch (ClassNotFoundException e) {
                    }
                } else {
                    continue;
                }
            }
        }
    }
    return 0;
}
 
Example 20
Source File: EmbeddedFelixFramework.java    From brooklyn-server with Apache License 2.0 4 votes vote down vote up
public static boolean isExtensionBundle(Bundle bundle) {
    String location = bundle.getLocation();
    return location != null && 
            EXTENSION_PROTOCOL.equals(Urls.getProtocol(location));
}