@Test
  public void testOwnerCannotSeeServiceClass() throws Exception {
    final Bundle bundleA = installBundle(getBundleArchiveA());
    final Bundle bundleB = installBundle(getBundleArchiveB());
    try {
      bundleA.start();
      bundleB.start();

      BundleContext contextA = bundleA.getBundleContext();
      BundleContext contextB = bundleB.getBundleContext();

      final CountDownLatch latch = new CountDownLatch(1);
      ServiceListener listener =
          new ServiceListener() {
            public void serviceChanged(ServiceEvent event) {
              latch.countDown();
            }
          };
      contextB.addServiceListener(listener);

      Object service = bundleB.loadClass(B.class.getName()).newInstance();
      ServiceRegistration reg = contextA.registerService(B.class.getName(), service, null);

      ServiceReference ref = reg.getReference();
      assertTrue(ref.isAssignableTo(bundleA, B.class.getName()));
      assertTrue(ref.isAssignableTo(bundleB, B.class.getName()));

      if (latch.await(5, TimeUnit.SECONDS) == false) throw new TimeoutException();

    } finally {
      bundleA.uninstall();
      bundleB.uninstall();
    }
  }
 public void postConstruct() {
   logger.debug("postConstruct {" + bundleContext.getBundle() + "}");
   loadPredefinedSegments(bundleContext);
   loadPredefinedScorings(bundleContext);
   for (Bundle bundle : bundleContext.getBundles()) {
     if (bundle.getBundleContext() != null) {
       loadPredefinedSegments(bundle.getBundleContext());
       loadPredefinedScorings(bundle.getBundleContext());
     }
   }
   bundleContext.addBundleListener(this);
   initializeTimer();
 }
	public void testBasic() throws BundleException, InvalidSyntaxException, InterruptedException {
		// get the system region
		Region systemRegion = digraph.getRegion(0);
		// create a disconnected test region
		Region testRegion = digraph.createRegion(getName());
		List<Bundle> bundles = new ArrayList<Bundle>();
		// Install all test bundles
		Bundle pp1, cp2, sc1;
		bundles.add(pp1 = bundleInstaller.installBundle(PP1, testRegion));
		// should be able to start pp1 because it depends on nothing
		pp1.start();
		// do a sanity check that we have no services available in the isolated region
		assertNull("Found some services.", pp1.getBundleContext().getAllServiceReferences(null, null));
		assertEquals("Found extra bundles in region", 1, pp1.getBundleContext().getBundles().length);
		pp1.stop();

		bundles.add(bundleInstaller.installBundle(SP1, testRegion));
		bundles.add(bundleInstaller.installBundle(CP1, testRegion));
		bundles.add(bundleInstaller.installBundle(PP2, testRegion));
		bundles.add(bundleInstaller.installBundle(SP2, testRegion));
		bundles.add(cp2 = bundleInstaller.installBundle(CP2, testRegion));
		bundles.add(bundleInstaller.installBundle(PC1, testRegion));
		bundles.add(bundleInstaller.installBundle(BC1, testRegion));
		bundles.add(sc1 = bundleInstaller.installBundle(SC1, testRegion));
		bundles.add(bundleInstaller.installBundle(CC1, testRegion));

		// Import the system bundle from the systemRegion
		digraph.connect(testRegion, digraph.createRegionFilterBuilder().allow(RegionFilter.VISIBLE_BUNDLE_NAMESPACE, "(id=0)").build(), systemRegion);
		// must import Boolean services into systemRegion to test
		digraph.connect(systemRegion, digraph.createRegionFilterBuilder().allow(RegionFilter.VISIBLE_SERVICE_NAMESPACE, "(objectClass=java.lang.Boolean)").build(), testRegion);

		bundleInstaller.resolveBundles(bundles.toArray(new Bundle[bundles.size()]));
		for (Bundle bundle : bundles) {
			assertEquals("Bundle did not resolve: " + bundle.getSymbolicName(), Bundle.RESOLVED, bundle.getState());
			bundle.start();
		}
		BundleContext context = getContext();
		ServiceTracker<Boolean, Boolean> cp2Tracker = new ServiceTracker<Boolean, Boolean>(context, context.createFilter("(&(objectClass=java.lang.Boolean)(bundle.id=" + cp2.getBundleId() + "))"), null);
		ServiceTracker<Boolean, Boolean> sc1Tracker = new ServiceTracker<Boolean, Boolean>(context, context.createFilter("(&(objectClass=java.lang.Boolean)(bundle.id=" + sc1.getBundleId() + "))"), null);

		cp2Tracker.open();
		sc1Tracker.open();

		assertNotNull("The cp2 bundle never found the service.", cp2Tracker.waitForService(2000));
		assertNotNull("The sc1 bundle never found the service.", sc1Tracker.waitForService(2000));
		cp2Tracker.close();
		sc1Tracker.close();
	}
  /**
   * @param bundle
   * @return
   */
  private static String getHeader(final Bundle bundle, String... keys) {
    // Look in the bundle...
    Dictionary headers = bundle.getHeaders();
    for (String key : keys) {
      String value = (String) headers.get(key);
      if (value != null) {
        return value;
      }
    }

    // Next, look in the bundle's fragments.
    Bundle[] bundles = bundle.getBundleContext().getBundles();
    for (Bundle fragment : bundles) {
      // only fragments are in resolved state
      if (fragment.getState() != bundle.RESOLVED) continue;

      // A fragment must also have the FRAGMENT_HOST header and the FRAGMENT_HOST header
      // must be equal to the bundle symbolic name
      String fragmentHost = (String) fragment.getHeaders().get(Constants.FRAGMENT_HOST);
      if ((fragmentHost == null) || (!fragmentHost.equals(bundle.getSymbolicName()))) {
        continue;
      }
      headers = fragment.getHeaders();
      for (String key : keys) {
        String value = (String) headers.get(key);
        if (value != null) {
          return value;
        }
      }
    }
    return null;
  }
  @Test
  public void testFrameworkListener() throws Exception {
    Bundle bundle = installBundle(getBundleArchiveA());
    try {
      bundle.start();
      BundleContext bundleContext = bundle.getBundleContext();
      assertNotNull(bundleContext);

      try {
        bundleContext.addFrameworkListener(null);
        fail("Should not be here!");
      } catch (IllegalArgumentException t) {
        // expected
      }

      try {
        bundleContext.removeFrameworkListener(null);
        fail("Should not be here!");
      } catch (IllegalArgumentException t) {
        // expected
      }

      // todo test events
    } finally {
      bundle.uninstall();
    }
  }
  @Test
  public void testStopedBundleContext() throws Exception {
    Bundle bundle = installBundle(getBundleArchiveA());
    try {
      bundle.start();
      BundleContext bundleContext = bundle.getBundleContext();
      assertNotNull(bundleContext);

      // The context should be illegal to use.
      bundle.stop();
      try {
        bundleContext.getProperty(getClass().getName());
        fail("Should not be here!");
      } catch (IllegalStateException t) {
        // expected
      }

      // The context should not become reusable after we restart the bundle
      bundle.start();
      try {
        bundleContext.getProperty(getClass().getName());
        fail("Should not be here!");
      } catch (IllegalStateException t) {
        // expected
      }
    } finally {
      bundle.uninstall();
    }
  }
  @Test
  public void testServiceReferenceFromListener() throws Exception {
    Bundle bundle = installBundle(getBundleArchiveA());
    try {
      bundle.start();

      final BundleContext context = bundle.getBundleContext();
      final AtomicInteger counter = new AtomicInteger();
      ServiceListener listener =
          new ServiceListener() {
            @Override
            public void serviceChanged(ServiceEvent event) {
              if (ServiceEvent.REGISTERED == event.getType()) {
                ServiceReference sref = context.getServiceReference(BundleContext.class.getName());
                if (context.getService(sref) != null) counter.incrementAndGet();
              }
            }
          };
      context.addServiceListener(listener);
      context.registerService(BundleContext.class.getName(), context, null);
      Assert.assertEquals(1, counter.get());

    } finally {
      bundle.uninstall();
    }
  }
  @Test
  public void testSetPropertiesAfterStop() throws Exception {
    Bundle bundle = installBundle(getBundleArchiveA());
    try {
      bundle.start();
      BundleContext bundleContext = bundle.getBundleContext();
      assertNotNull(bundleContext);

      ServiceRegistration registration =
          bundleContext.registerService(BundleContext.class.getName(), bundleContext, null);
      assertNotNull(registration);

      bundle.stop();

      try {
        registration.setProperties(new Hashtable<String, Object>());
        fail("Should not be here!");
      } catch (IllegalStateException t) {
        // expected
      }
      assertNoServiceEvent();
    } finally {
      bundle.uninstall();
    }
  }
  private void runJava(PrintStream out, PrintStream err) {
    Binding.out = out;
    Binding.err = err;
    Binding.ctx = bundle.getBundleContext();

    try {
      Callable<?> callable =
          javacService.compileJavaSnippet(code, classLoaderContext, err).orElse(ERROR);

      if (callable != ERROR) {
        Object result = callable.call();

        if (result != null) {
          out.println(result);
        }

        code.commit();
      } else {
        code.abort();
      }
    } catch (Throwable e) {
      code.abort();
      e.printStackTrace(err);
    }
  }
  /**
   * Forcing the registry of the HttpService, usually need it when the felix framework is reloaded
   * and we need to update the bundle context of our already registered services.
   *
   * @param context
   */
  private void forceHttpServiceLoading(BundleContext context) throws Exception {

    try {
      // Working with the http bridge
      if (OSGIProxyServlet.servletConfig
          != null) { // If it is null probably the servlet wasn't even been loaded...

        try {
          OSGIProxyServlet.bundleContext.getBundle();
        } catch (IllegalStateException e) {

          Bundle[] bundles = context.getBundles();
          for (Bundle bundle : bundles) {
            if (bundle.getSymbolicName().equals(OSGIUtil.BUNDLE_HTTP_BRIDGE_SYMBOLIC_NAME)) {
              // If we are here is because we have an invalid bundle context, so we need to provide
              // a new one
              BundleContext httpBundle = bundle.getBundleContext();
              OSGIProxyServlet.tracker =
                  new DispatcherTracker(httpBundle, null, OSGIProxyServlet.servletConfig);
              OSGIProxyServlet.tracker.open();
              OSGIProxyServlet.bundleContext = httpBundle;
            }
          }
        }
      }
    } catch (Exception e) {
      Logger.error(this, "Error loading HttpService.", e);
      throw e;
    }
  }
Beispiel #11
0
 protected BundleContext getContext() {
   Bundle cxfBundle = FrameworkUtil.getBundle(ApplicationServiceBean.class);
   if (cxfBundle != null) {
     return cxfBundle.getBundleContext();
   }
   return null;
 }
Beispiel #12
0
 protected Class<?> getClass(String name) {
   BundleContext bundleContext = null;
   Bundle currentBundle = FrameworkUtil.getBundle(getClass());
   if (currentBundle != null) {
     bundleContext = currentBundle.getBundleContext();
   }
   if (bundleContext != null) {
     Bundle[] bundles = bundleContext.getBundles();
     for (Bundle bundle : bundles) {
       if (bundle.getState() >= Bundle.RESOLVED) {
         try {
           return bundle.loadClass(name);
         } catch (ClassNotFoundException e) {
           // Ignore
         }
       }
     }
   } else {
     try {
       return Class.forName(name);
     } catch (ClassNotFoundException e) {
       LOG.warn("Failed to find class for {}", name);
       throw new RuntimeException(e);
     }
   }
   LOG.warn("Failed to find class for {}", name);
   throw new RuntimeException(new ClassNotFoundException(name));
 }
 /**
  * Used to get Full form of URL from the Given Short Page URL
  *
  * @param pageFullPath
  * @return {@link String}
  * @throws Exception
  */
 public static String getFullURLPath(String shortUrlPath) throws Exception {
   ResourceResolver resourceResolver = null;
   try {
     Bundle bndl = FrameworkUtil.getBundle(ResourceResolverFactory.class);
     BundleContext bundleContext = bndl.getBundleContext();
     ServiceReference ref =
         bundleContext.getServiceReference(ResourceResolverFactory.class.getName());
     ResourceResolverFactory resolverFactory =
         (ResourceResolverFactory) bundleContext.getService(ref);
     resourceResolver = resolverFactory.getAdministrativeResourceResolver(null);
     Resource resource = resourceResolver.resolve(shortUrlPath);
     if (null != resource) {
       return java.net.URLDecoder.decode(resource.getPath(), "UTF-8");
     } else {
       if (LOGGER.isDebugEnabled()) {
         LOGGER.debug("Resource doesn't exists..." + shortUrlPath);
       }
     }
   } catch (Exception e) {
     LOGGER.error(
         " Error while getting Full URL for the path :"
             + shortUrlPath
             + " and the error message is :",
         e);
   } finally {
     resourceResolver.close();
   }
   return shortUrlPath;
 }
 public void _testPrintNotLoaded() {
   Bundle bundle = Platform.getBundle("org.eclipse.jdt.text.tests");
   Bundle[] bundles = bundle.getBundleContext().getBundles();
   for (int i = 0; i < bundles.length; i++) {
     if (bundles[i].getState() != Bundle.ACTIVE) System.out.println(bundles[i].getSymbolicName());
   }
 }
  public DDMFormFieldValueRendererRegistryImpl() {
    Class<?> clazz = getClass();

    Bundle bundle = FrameworkUtil.getBundle(clazz);

    _bundleContext = bundle.getBundleContext();

    Filter filter = null;

    try {
      filter =
          FrameworkUtil.createFilter(
              "(&(objectClass="
                  + DDMFormFieldValueRenderer.class.getName()
                  + ")(!(objectClass="
                  + clazz.getName()
                  + ")))");
    } catch (InvalidSyntaxException ise) {
      ReflectionUtil.throwException(ise);
    }

    _serviceTracker =
        new ServiceTracker<>(
            _bundleContext, filter, new DDMFormFieldValueRendererServiceTrackerCustomizer());

    _serviceTracker.open();
  }
  @Test
  public void testProperties() throws Exception {
    Bundle bundle = installBundle(getBundleArchiveA());
    try {
      bundle.start();
      BundleContext bundleContext = bundle.getBundleContext();
      assertNotNull(bundleContext);
      assertEquals("1.5", bundleContext.getProperty(Constants.FRAMEWORK_VERSION));
      assertEquals("jboss.org", bundleContext.getProperty(Constants.FRAMEWORK_VENDOR));
      assertEquals(
          Locale.getDefault().getLanguage(),
          bundleContext.getProperty(Constants.FRAMEWORK_LANGUAGE));
      assertSystemProperty(bundleContext, "os.name", Constants.FRAMEWORK_OS_NAME);
      String fwOSVersion = bundleContext.getProperty(Constants.FRAMEWORK_OS_VERSION);
      assertTrue(fwOSVersion.length() > 0);
      assertTrue(System.getProperty("os.version").startsWith(fwOSVersion));
      assertSystemProperty(bundleContext, "os.arch", Constants.FRAMEWORK_PROCESSOR);

      assertNull(bundleContext.getProperty(getClass().getName()));
      System.setProperty(getClass().getName(), "test");
      assertEquals("test", bundleContext.getProperty(getClass().getName()));

      bundle.stop();
      try {
        bundleContext.getProperty(getClass().getName());
        fail("Should not be here!");
      } catch (IllegalStateException t) {
        // expected
      }
    } finally {
      bundle.uninstall();
    }
  }
    @Override
    public void frameworkEvent(FrameworkEvent frameworkEvent) {
      if (frameworkEvent.getType() != FrameworkEvent.PACKAGES_REFRESHED) {
        return;
      }

      for (Bundle bundle : _startBundles) {
        try {
          startBundle(bundle, 0, false);
        } catch (Exception e) {
          _log.error(e, e);
        }
      }

      for (Bundle bundle : _lazyActivationBundles) {
        try {
          startBundle(bundle, Bundle.START_ACTIVATION_POLICY, false);
        } catch (Exception e) {
          _log.error(e, e);
        }
      }

      try {
        Bundle bundle = frameworkEvent.getBundle();

        BundleContext bundleContext = bundle.getBundleContext();

        bundleContext.removeFrameworkListener(this);
      } catch (Exception e) {
        _log.error(e, e);
      }
    }
  public void execute(@Observes(precedence = Integer.MAX_VALUE) EventContext<BeforeSuite> event)
      throws Exception {

    Bundle bundle = FrameworkUtil.getBundle(getClass());

    BundleContext bundleContext = bundle.getBundleContext();

    Filter filter =
        FrameworkUtil.createFilter(
            "(&(objectClass=org.springframework.context.ApplicationContext)"
                + "(org.springframework.context.service.name="
                + bundleContext.getBundle().getSymbolicName()
                + "))");

    ServiceTracker<ApplicationContext, ApplicationContext> serviceTracker =
        new ServiceTracker<>(bundleContext, filter, null);

    serviceTracker.open();

    try {
      serviceTracker.waitForService(30 * 1000L);
    } catch (InterruptedException e) {
      throw new RuntimeException(e);
    }

    serviceTracker.close();

    event.proceed();
  }
  @Test
  public void testRegBundleIsRefBundle() throws Exception {
    Bundle bundle = installBundle(getBundleArchiveA());
    try {
      bundle.start();

      final CountDownLatch latch = new CountDownLatch(1);
      ServiceListener listener =
          new ServiceListener() {
            public void serviceChanged(ServiceEvent event) {
              latch.countDown();
            }
          };
      BundleContext context = bundle.getBundleContext();
      context.addServiceListener(listener);

      Object service = bundle.loadClass(A.class.getName()).newInstance();
      ServiceRegistration reg = context.registerService(A.class.getName(), service, null);

      ServiceReference ref = reg.getReference();
      assertTrue(ref.isAssignableTo(bundle, A.class.getName()));

      if (latch.await(5, TimeUnit.SECONDS) == false) throw new TimeoutException();

    } finally {
      bundle.uninstall();
    }
  }
  @Test
  public void testObjectClassFilter() throws Exception {
    Bundle bundle = installBundle(getBundleArchiveA());
    try {
      bundle.start();
      BundleContext context = bundle.getBundleContext();
      assertNotNull(context);
      assertNoServiceEvent();

      String filter = "(" + Constants.OBJECTCLASS + "=" + BundleContext.class.getName() + ")";
      context.addServiceListener(this, filter);

      ServiceRegistration sreg =
          context.registerService(BundleContext.class.getName(), context, null);
      ServiceReference sref = sreg.getReference();

      assertServiceEvent(ServiceEvent.REGISTERED, sref);

      sreg.unregister();
      assertServiceEvent(ServiceEvent.UNREGISTERING, sref);

      filter = "(objectClass=dummy)";
      context.addServiceListener(this, filter);

      sreg = context.registerService(BundleContext.class.getName(), context, null);
      assertNoServiceEvent();

      sreg.unregister();
      assertNoServiceEvent();
    } finally {
      bundle.uninstall();
    }
  }
Beispiel #21
0
 public void addStrategy(ServiceReference<FilterStrategy> filterStrategyRef) {
   Bundle bundle = FrameworkUtil.getBundle(FilterPlugin.class);
   if (bundle != null) {
     FilterStrategy filterStrategy = bundle.getBundleContext().getService(filterStrategyRef);
     filterStrategies.put(filterStrategyRef, filterStrategy);
   }
 }
  @Test
  public void testRegValueIsServiceFactory() throws Exception {
    final Bundle bundleA = installBundle(getBundleArchiveA());
    final Bundle bundleB = installBundle(getBundleArchiveB());
    try {
      bundleA.start();
      bundleB.start();

      BundleContext contextA = bundleA.getBundleContext();
      BundleContext contextB = bundleB.getBundleContext();

      final CountDownLatch latch = new CountDownLatch(1);
      ServiceListener listener =
          new ServiceListener() {
            public void serviceChanged(ServiceEvent event) {
              latch.countDown();
            }
          };
      contextB.addServiceListener(listener);

      Object service =
          new ServiceFactory() {
            public Object getService(Bundle bundle, ServiceRegistration registration) {
              try {
                return bundleA.loadClass(A.class.getName()).newInstance();
              } catch (Exception e) {
                throw new IllegalStateException(e);
              }
            }

            public void ungetService(
                Bundle bundle, ServiceRegistration registration, Object service) {}
          };
      ServiceRegistration reg = contextA.registerService(A.class.getName(), service, null);

      ServiceReference ref = reg.getReference();
      assertTrue(ref.isAssignableTo(bundleA, A.class.getName()));
      assertTrue(ref.isAssignableTo(bundleB, A.class.getName()));

      if (latch.await(5, TimeUnit.SECONDS) == false) throw new TimeoutException();

    } finally {
      bundleA.uninstall();
      bundleB.uninstall();
    }
  }
Beispiel #23
0
 private BundleContext getBundleContext() {
   BundleContext bundleContext = null;
   Bundle currentBundle = FrameworkUtil.getBundle(getClass());
   if (currentBundle != null) {
     bundleContext = currentBundle.getBundleContext();
   }
   return bundleContext;
 }
  @Test
  public void testFragmentBundleContext() throws Exception {

    Bundle fragA = installBundle(getFragmentA());
    Bundle hostA = installBundle(getHostA());

    hostA.start();
    assertNotNull("Host context not null", hostA.getBundleContext());
    assertNull("Fragment context null", fragA.getBundleContext());

    hostA.stop();
    assertNull("Host context null", hostA.getBundleContext());
    assertNull("Fragment context null", fragA.getBundleContext());

    fragA.uninstall();
    hostA.uninstall();
  }
 public static BundleContext getBundleContextByBundleId(long bundleId) {
   Bundle bundle = bundleContext.getBundle(bundleId);
   if (bundle != null) {
     return bundle.getBundleContext();
   } else {
     return null;
   }
 }
  static {
    Bundle bundle = FrameworkUtil.getBundle(ShoppingOrderItemLocalServiceUtil.class);

    _serviceTracker =
        new ServiceTracker<ShoppingOrderItemLocalService, ShoppingOrderItemLocalService>(
            bundle.getBundleContext(), ShoppingOrderItemLocalService.class, null);

    _serviceTracker.open();
  }
 @Before
 public void mockIt() {
   when(contextModelMock.getContextName()).thenReturn(KNOWN_CONTEXT_NAME);
   when(contextModelMock.getHttpContext()).thenReturn(httpContextMock);
   when(contextModelMock.getBundle()).thenReturn(bundleMock);
   when(bundleMock.getHeaders()).thenReturn(new Hashtable<String, String>());
   when(bundleMock.getSymbolicName()).thenReturn(BUNDLE_SYMBOLIC_NAME);
   when(bundleMock.getBundleContext()).thenReturn(bundleContextMock);
 }
  static {
    Bundle bundle = FrameworkUtil.getBundle(MDRRuleGroupServiceUtil.class);

    _serviceTracker =
        new ServiceTracker<MDRRuleGroupService, MDRRuleGroupService>(
            bundle.getBundleContext(), MDRRuleGroupService.class, null);

    _serviceTracker.open();
  }
  static {
    Bundle bundle = FrameworkUtil.getBundle(ShoppingCouponUtil.class);

    _serviceTracker =
        new ServiceTracker<ShoppingCouponPersistence, ShoppingCouponPersistence>(
            bundle.getBundleContext(), ShoppingCouponPersistence.class, null);

    _serviceTracker.open();
  }
  static {
    Bundle bundle = FrameworkUtil.getBundle(KaleoTaskInstanceTokenLocalServiceUtil.class);

    _serviceTracker =
        new ServiceTracker<KaleoTaskInstanceTokenLocalService, KaleoTaskInstanceTokenLocalService>(
            bundle.getBundleContext(), KaleoTaskInstanceTokenLocalService.class, null);

    _serviceTracker.open();
  }