/** {@inheritDoc} */
  public ProxyTarget locateProxyTarget(long timeout, TimeUnit unit)
      throws InterruptedException, TimeoutException {
    String filter = filterString;
    if (filter == null) {
      filter = String.format("(%s=%s)", Constants.OBJECTCLASS, serviceInterface);
    } else {
      filter = String.format("(&(%s=%s)%s)", Constants.OBJECTCLASS, serviceInterface, filter);
    }
    try {
      final ServiceTracker<Object, Object> tracker =
          new ServiceTracker<Object, Object>(
              bundleContext, bundleContext.createFilter(filter), null);
      tracker.open();
      final Object service = tracker.waitForService(unit.toMillis(timeout));
      if (service == null) {
        throw new TimeoutException("no service for filter = " + filter + " was avaiable in time");
      }
      return new ReleasableProxyTarget() {

        public Object getTarget() {
          return service;
        }

        public ProxyTarget releaseTarget() {
          tracker.close();
          return null;
        }
      };
    } catch (InvalidSyntaxException e) {
      throw new RuntimeException("filter creation failed", e);
    }
  }
  public void start(BundleContext context) throws Exception {

    this.context = context;

    // Detecting the log service
    System.out.print("Starting OSGiBroker TCP Service ...");

    String filterString =
        "(|"
            + "("
            + Constants.OBJECTCLASS
            + "="
            + DBManagerIF.class.getName()
            + ")"
            + "(|"
            + "("
            + Constants.OBJECTCLASS
            + "="
            + PublisherIF.class.getName()
            + ")"
            + "("
            + Constants.OBJECTCLASS
            + "="
            + RemotePublisherIF.class.getName()
            + ")))";

    Filter serviceFilter = context.createFilter(filterString);

    tracker = new ServiceTracker(context, serviceFilter, new TCPServiceCustomizer());
    tracker.open();
    System.out.println("[DONE]");
  }
 /** Handle the system notifying that it's ready to install configs. */
 public void checkReady() throws BootstrapFailure {
   if (requireRepository) {
     ServiceTracker repoTracker = null;
     try {
       if (repo == null) {
         Filter filter =
             ctx.createFilter(
                 "(" + Constants.OBJECTCLASS + "=" + RepoBootService.class.getName() + ")");
         repoTracker = new ServiceTracker(ctx, filter, null);
         repoTracker.open();
         logger.debug("Bootstrapping repository");
         RepoBootService rawRepo = (RepoBootService) repoTracker.waitForService(5000);
         if (rawRepo != null) {
           logger.debug("Bootstrap obtained repository");
           repo = rawRepo;
         } else {
           logger.info("Failed to bootstrap repo, returned null");
         }
       }
     } catch (InterruptedException ex) {
       logger.warn("Failed to bootstrap repo " + ex.getMessage(), ex);
     } catch (InvalidSyntaxException ex) {
       logger.warn("Failed to bootstrap repo " + ex.getMessage(), ex);
     } finally {
       if (repoTracker != null) {
         repoTracker.close();
       }
     }
     if (repo == null) {
       throw new BootstrapFailure(
           "Failed to acquire the bootstrap repository service to access configuration persistence.");
     }
   }
 }
  private void initServices() {
    BundleContext context = Activator.getContext();
    if (context == null) {
      RuntimeLog.log(
          new Status(
              IStatus.ERROR,
              RegistryMessages.OWNER_NAME,
              0,
              RegistryMessages.bundle_not_activated,
              null));
      return;
    }

    debugTracker = new ServiceTracker(context, DebugOptions.class.getName(), null);
    debugTracker.open();

    bundleTracker = new ServiceTracker(context, PackageAdmin.class.getName(), null);
    bundleTracker.open();

    // locations
    final String FILTER_PREFIX =
        "(&(objectClass=org.eclipse.osgi.service.datalocation.Location)(type="; //$NON-NLS-1$
    Filter filter = null;
    try {
      filter = context.createFilter(FILTER_PREFIX + PROP_CONFIG_AREA + "))"); // $NON-NLS-1$
    } catch (InvalidSyntaxException e) {
      // ignore this.  It should never happen as we have tested the above format.
    }
    configurationLocationTracker = new ServiceTracker(context, filter, null);
    configurationLocationTracker.open();
  }
  private List /* <Configuration> */ getConfigurations(
      String filterString, String callingBundleLocation, boolean checkLocation)
      throws IOException, InvalidSyntaxException {
    Filter filter = (filterString != null) ? context.createFilter(filterString) : null;
    Iterator /* <String> */ pids = configurationDictionaryManager.listPids();
    List /* <Configuration> */ matchingConfigurations = new ArrayList();
    while (pids.hasNext()) {

      String pid = (String) pids.next();
      ConfigurationDictionary config = configurationDictionaryManager.load(pid);
      if (filter == null) {
        matchingConfigurations.add(new ConfigurationImpl(this, config));
      } else {
        if (filter.matchCase(config.toSearchableProperties())) {
          if (!checkLocation) {
            matchingConfigurations.add(new ConfigurationImpl(this, config));
          } else {
            if (callingBundleLocation.equals(config.getLocation())) {
              matchingConfigurations.add(new ConfigurationImpl(this, config));
            }
          }
        }
      }
    }
    return matchingConfigurations;
  }
 @Before
 public void setUp() throws InvalidSyntaxException {
   Activator original = new Activator();
   activator = spy(original);
   doReturn(jerseyServer).when(activator).getJerseyAPIBundle();
   Filter filter = mock(Filter.class);
   when(context.createFilter(anyString())).thenReturn(filter);
   when(context.registerService(anyString(), anyObject(), any(Dictionary.class)))
       .thenReturn(registration);
 }
Exemple #7
0
 private <T> Filter createRemoteFilter(Class<T> clazz) throws InvalidSyntaxException {
   return context.createFilter(
       "(&("
           + org.osgi.framework.Constants.OBJECTCLASS
           + "="
           + clazz.getName()
           + ")("
           + IDistributionConstants.SERVICE_IMPORTED
           + "=*))");
 }
 public static boolean matchesCurrentEnvironment(IMonitorModelBase model) {
   BundleContext context = MDECore.getDefault().getBundleContext();
   Dictionary environment = getTargetEnvironment();
   BundleDescription bundle = model.getBundleDescription();
   String filterSpec = bundle != null ? bundle.getPlatformFilter() : null;
   try {
     return filterSpec == null || context.createFilter(filterSpec).match(environment);
   } catch (InvalidSyntaxException e) {
     return false;
   }
 }
  public static <S, T> ServiceTracker<S, T> create(
      BundleContext bundleContext, String filterString) {

    try {
      return new ServiceTracker<>(bundleContext, bundleContext.createFilter(filterString), null);
    } catch (InvalidSyntaxException ise) {
      throwException(ise);

      return null;
    }
  }
Exemple #10
0
 private Filter buildHttpServiceFilter(BundleContext pBundleContext) {
   String customFilter = getConfiguration(ConfigKey.HTTP_SERVICE_FILTER);
   String filter =
       customFilter.trim().length() > 0
           ? "(&" + HTTP_SERVICE_FILTER_BASE + customFilter + ")"
           : HTTP_SERVICE_FILTER_BASE;
   try {
     return pBundleContext.createFilter(filter);
   } catch (InvalidSyntaxException e) {
     throw new IllegalArgumentException("Unable to parse filter " + filter, e);
   }
 }
Exemple #11
0
 /** mapping rule: LDAP filter --> output value the more specific filters should be given first. */
 public void initialize(BundleContext ctx, String[][] mappingRules) {
   filters = new Filter[mappingRules.length];
   outputStrings = new String[mappingRules.length];
   for (int i = 0; i < mappingRules.length; i++) {
     try {
       filters[i] = ctx.createFilter(mappingRules[i][0]);
       outputStrings[i] = mappingRules[i][1];
     } catch (InvalidSyntaxException e) {
       // TODO Neeed to process this
       e.printStackTrace();
     }
   }
 }
 /** Returns the platform instance location. */
 public Location getInstanceLocation() {
   if (instanceLocationTracker == null) {
     Filter filter;
     try {
       filter = bundleContext.createFilter(Location.INSTANCE_FILTER);
     } catch (InvalidSyntaxException e) {
       LogHelper.log(e);
       return null;
     }
     instanceLocationTracker = new ServiceTracker<Location, Location>(bundleContext, filter, null);
     instanceLocationTracker.open();
   }
   return instanceLocationTracker.getService();
 }
 public Location getInstanceLocation() {
   if (locationTracker == null) {
     Filter filter = null;
     try {
       filter = context.createFilter(Location.INSTANCE_FILTER);
     } catch (InvalidSyntaxException e) {
       // ignore this. It should never happen as we have tested the
       // above format.
     }
     locationTracker = new ServiceTracker(context, filter, null);
     locationTracker.open();
   }
   return (Location) locationTracker.getService();
 }
 public URL getConfigURL() {
   Filter filter = null;
   if (configTracker == null) {
     try {
       filter = bundleContext.createFilter(Location.CONFIGURATION_FILTER);
     } catch (InvalidSyntaxException e) {
       // should never happen
     }
     configTracker = new ServiceTracker(bundleContext, filter, null);
     configTracker.open();
   }
   Location location = (Location) configTracker.getService();
   if (location == null) return null;
   return location.getURL();
 }
Exemple #15
0
  public void activate() throws RESTException {
    /*
     * server opstarten
     */
    servicesByID = new HashMap<String, Object>();
    methodsByString = new HashMap<String, Method>();
    clientsByString = new HashMap<String, ClientResource>();

    component = new Component();
    Server server = component.getServers().add(Protocol.HTTP, 8080);
    try {
      server.start();
    } catch (Exception e1) {
      throw new RESTException("Error starting the server", e1);
    }

    /*
     * ServiceListener that automatically exports services with exported interfaces
     * as defined by the Remote Services specification
     */
    try {
      ServiceTracker serviceTracker =
          new ServiceTracker(
              context,
              context.createFilter("(service.exported.interfaces=*)"),
              new ServiceTrackerCustomizer() {

                @Override
                public Object addingService(ServiceReference ref) {
                  Collection<ExportRegistration> regs = exportService(ref, null);
                  return regs;
                }

                @Override
                public void modifiedService(ServiceReference ref, Object regs) {}

                @Override
                public void removedService(ServiceReference ref, Object regs) {
                  for (ExportRegistration r : (Collection<ExportRegistration>) regs) {
                    r.close();
                  }
                }
              });
      serviceTracker.open();
    } catch (InvalidSyntaxException e) {
    }
  }
Exemple #16
0
  private RepositoryAdminImpl createRepositoryAdmin() throws Exception {
    BundleContext bundleContext = (BundleContext) EasyMock.createMock(BundleContext.class);
    Bundle systemBundle = (Bundle) EasyMock.createMock(Bundle.class);

    Activator.setContext(bundleContext);
    EasyMock.expect(bundleContext.getProperty(RepositoryAdminImpl.REPOSITORY_URL_PROP))
        .andReturn(getClass().getResource("/referred.xml").toExternalForm());
    EasyMock.expect(bundleContext.getProperty((String) EasyMock.anyObject()))
        .andReturn(null)
        .anyTimes();
    EasyMock.expect(bundleContext.getBundle(0)).andReturn(systemBundle);
    EasyMock.expect(systemBundle.getHeaders()).andReturn(new Hashtable());
    EasyMock.expect(systemBundle.getRegisteredServices()).andReturn(null);
    EasyMock.expect(new Long(systemBundle.getBundleId())).andReturn(new Long(0)).anyTimes();
    EasyMock.expect(systemBundle.getBundleContext()).andReturn(bundleContext);
    bundleContext.addBundleListener((BundleListener) EasyMock.anyObject());
    bundleContext.addServiceListener((ServiceListener) EasyMock.anyObject());
    EasyMock.expect(bundleContext.getBundles()).andReturn(new Bundle[] {systemBundle});
    final Capture c = new Capture();
    EasyMock.expect(bundleContext.createFilter((String) capture(c)))
        .andAnswer(
            new IAnswer() {
              public Object answer() throws Throwable {
                return FilterImpl.newInstance((String) c.getValue());
              }
            })
        .anyTimes();
    EasyMock.replay(new Object[] {bundleContext, systemBundle});

    RepositoryAdminImpl repoAdmin =
        new RepositoryAdminImpl(bundleContext, new Logger(bundleContext));

    // force initialization && remove all initial repositories
    Repository[] repos = repoAdmin.listRepositories();
    for (int i = 0; repos != null && i < repos.length; i++) {
      repoAdmin.removeRepository(repos[i].getURI());
    }

    return repoAdmin;
  }
  /**
   * Constructor.
   *
   * @param context The context of the bundle that is used to track the services.
   * @param referenceType The type of the reference
   * @param requirements The requirements that need to be satisfied to satisfy the collector. The
   *     filter of each requirement must match a {@link ServiceReference}.
   * @param capabilityConsumer The consumer must be implemented by the programmer using this class
   *     to get notified about the events of the collector.
   * @param trackAllServices If {@code true}, then this {@code collector} will track all matching
   *     services regardless of class loader accessibility. If {@code false}, then this {@code
   *     collector} will only track matching services which are class loader accessible to the
   *     bundle whose {@code BundleContext} is used by this {@code collector}.
   */
  public ServiceReferenceCollector(
      final BundleContext context,
      final Class<S> referenceType,
      final RequirementDefinition<ServiceReference<S>>[] requirements,
      final CapabilityConsumer<ServiceReference<S>> capabilityConsumer,
      final boolean trackAllServices) {
    super(requirements, capabilityConsumer);

    this.trackAllServices = trackAllServices;
    if (referenceType == null) {
      try {
        tracker =
            new ServiceTracker<S, ServiceReference<S>>(
                context, context.createFilter("(service.id=*)"), new ReferenceTrackerCustomizer());
      } catch (InvalidSyntaxException e) {
        throw new RuntimeException(e);
      }
    } else {
      tracker =
          new ServiceTracker<S, ServiceReference<S>>(
              context, referenceType, new ReferenceTrackerCustomizer());
    }
  }
 /**
  * Creates an OSGi filter for the classes.
  *
  * @param bundleContext a bundle context
  * @param classes array of tracked classes
  * @return osgi filter
  */
 private static Filter createFilter(final BundleContext bundleContext, final Class... classes) {
   final StringBuilder filter = new StringBuilder();
   if (classes != null) {
     if (classes.length > 1) {
       filter.append("(|");
     }
     for (Class clazz : classes) {
       filter
           .append("(")
           .append(Constants.OBJECTCLASS)
           .append("=")
           .append(clazz.getName())
           .append(")");
     }
     if (classes.length > 1) {
       filter.append(")");
     }
   }
   try {
     return bundleContext.createFilter(filter.toString());
   } catch (InvalidSyntaxException e) {
     throw new IllegalArgumentException("Unexpected InvalidSyntaxException: " + e.getMessage());
   }
 }
Exemple #19
0
  /** {@inheritDoc} */
  public void start(BundleContext bc) {

    setBundleContext(bc);

    VideoScreen s = new VideoScreen();

    // Check for a properties file for video categories...
    File conf = new File("conf");
    if ((conf.exists()) && (conf.isDirectory())) {

      File props = new File(conf, "videoscreen.properties");
      if ((props.exists()) && (props.isFile())) {

        Properties p = Util.findProperties(props);
        if (p != null) {

          int count = Util.str2int(p.getProperty("categoryCount"), 0);
          if (count > 0) {

            ArrayList<String> l = new ArrayList<String>();
            for (int i = 0; i < count; i++) {

              String tmp = p.getProperty("category" + i);
              if (tmp != null) {

                l.add(tmp);
              }
            }

            if (l.size() > 0) {

              String[] array = l.toArray(new String[l.size()]);
              s.setParameters(array);
            }
          }
        }
      }
    }

    // Now we listen for command events.
    String[] topics = new String[] {"org/jflicks/rc/COMMAND"};

    Hashtable<String, String[]> h = new Hashtable<String, String[]>();
    h.put(EventConstants.EVENT_TOPIC, topics);
    bc.registerService(EventHandler.class.getName(), s, h);

    RCTracker rct = new RCTracker(bc, s);
    setRCTracker(rct);
    rct.open();

    ImageCacheTracker ict = new ImageCacheTracker(bc, s);
    setImageCacheTracker(ict);
    ict.open();
    try {

      Filter filter = bc.createFilter("(Player-Handle=" + Player.PLAYER_VIDEO + ")");
      ServiceTracker st = new ServiceTracker(bc, filter, null);
      setServiceTracker(st);
      st.open();
      s.setPlayerServiceTracker(st);

    } catch (InvalidSyntaxException ex) {
    }

    Hashtable<String, String> dict = new Hashtable<String, String>();
    dict.put(Screen.TITLE_PROPERTY, s.getTitle());

    bc.registerService(Screen.class.getName(), s, dict);
  }
 public Filter createFilter(String filter) throws InvalidSyntaxException {
   return delegate.createFilter(filter);
 }
	private void doCyclicRegions(int numLevels) throws BundleException, InvalidSyntaxException, InterruptedException {
		String regionName1 = getName() + "_1";
		String regionName2 = getName() + "_2";
		// get the system region
		Region systemRegion = digraph.getRegion(0);
		// create two regions to hold the bundles
		Region testRegion1 = digraph.createRegion(regionName1);
		Region testRegion2 = digraph.createRegion(regionName2);
		// connect to the system bundle
		testRegion1.connectRegion(systemRegion, digraph.createRegionFilterBuilder().allow(RegionFilter.VISIBLE_BUNDLE_NAMESPACE, "(id=0)").build());
		testRegion2.connectRegion(systemRegion, digraph.createRegionFilterBuilder().allow(RegionFilter.VISIBLE_BUNDLE_NAMESPACE, "(id=0)").build());
		// must import Boolean services into systemRegion to test
		systemRegion.connectRegion(testRegion1, digraph.createRegionFilterBuilder().allow(RegionFilter.VISIBLE_SERVICE_NAMESPACE, "(objectClass=java.lang.Boolean)").build());
		systemRegion.connectRegion(testRegion2, digraph.createRegionFilterBuilder().allow(RegionFilter.VISIBLE_SERVICE_NAMESPACE, "(objectClass=java.lang.Boolean)").build());

		Map<String, Bundle> bundles = new HashMap<String, Bundle>();
		// add bundles to region1
		bundles.put(PP1, bundleInstaller.installBundle(PP1, testRegion1));
		bundles.put(SP2, bundleInstaller.installBundle(SP2, testRegion1));
		bundles.put(CP2, bundleInstaller.installBundle(CP2, testRegion1));
		bundles.put(PC1, bundleInstaller.installBundle(PC1, testRegion1));
		bundles.put(BC1, bundleInstaller.installBundle(BC1, testRegion1));

		// add bundles to region2
		bundles.put(SP1, bundleInstaller.installBundle(SP1, testRegion2));
		bundles.put(CP1, bundleInstaller.installBundle(CP1, testRegion2));
		bundles.put(PP2, bundleInstaller.installBundle(PP2, testRegion2));
		bundles.put(SC1, bundleInstaller.installBundle(SC1, testRegion2));
		bundles.put(CC1, bundleInstaller.installBundle(CC1, testRegion2));

		RegionFilterBuilder testRegionFilter1 = digraph.createRegionFilterBuilder();
		// SP2 -> PP2
		testRegionFilter1.allow(RegionFilter.VISIBLE_PACKAGE_NAMESPACE, "(" + RegionFilter.VISIBLE_PACKAGE_NAMESPACE + "=pkg2.*)");
		// CP2 -> SP1
		testRegionFilter1.allow(RegionFilter.VISIBLE_SERVICE_NAMESPACE, "(" + Constants.OBJECTCLASS + "=pkg1.*)");
		// PC1 -> PP2
		// this is not needed because we already import pkg2.* above
		//testRegionFilter1.allow(RegionFilter.VISIBLE_PACKAGE_NAMESPACE, "(" + RegionFilter.VISIBLE_PACKAGE_NAMESPACE + "=pkg2.*)");
		// BC1 -> PP2
		testRegionFilter1.allow(RegionFilter.VISIBLE_REQUIRE_NAMESPACE, "(" + RegionFilter.VISIBLE_REQUIRE_NAMESPACE + "=" + PP2 + ")");

		RegionFilterBuilder testRegionFilter2 = digraph.createRegionFilterBuilder();
		//SP1 -> PP1
		testRegionFilter2.allow(RegionFilter.VISIBLE_PACKAGE_NAMESPACE, "(" + RegionFilter.VISIBLE_PACKAGE_NAMESPACE + "=pkg1.*)");
		//SC1 -> SP2
		testRegionFilter2.allow(RegionFilter.VISIBLE_SERVICE_NAMESPACE, "(" + Constants.OBJECTCLASS + "=pkg2.*)");
		//CC1 -> CP2
		testRegionFilter2.allow(CP2, "(name=" + CP2 + ")");

		Region r1, r2 = null;
		for (int i = 0; i <= numLevels; i++) {
			r1 = (i > 0) ? r2 : testRegion1;
			r2 = (i < numLevels) ? digraph.createRegion(getName() + "_level_" + i) : testRegion2;
			r1.connectRegion(r2, testRegionFilter1.build());
			r2.connectRegion(r1, testRegionFilter2.build());
		}

		bundleInstaller.resolveBundles(bundles.values().toArray(new Bundle[bundles.size()]));
		for (Bundle bundle : bundles.values()) {
			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=" + bundles.get(CP2).getBundleId() + "))"), null);
		ServiceTracker<Boolean, Boolean> sc1Tracker = new ServiceTracker<Boolean, Boolean>(context, context.createFilter("(&(objectClass=java.lang.Boolean)(bundle.id=" + bundles.get(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();
	}
	public void testSingleBundleRegions() throws BundleException, InvalidSyntaxException, InterruptedException {
		// get the system region
		Region systemRegion = digraph.getRegion(0);
		Map<String, Bundle> bundles = new HashMap<String, Bundle>();
		// create a disconnected test region for each test bundle
		for (String location : ALL) {
			Region testRegion = digraph.createRegion(location);
			bundles.put(location, bundleInstaller.installBundle(location, 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.values().toArray(new Bundle[bundles.size()]));
		assertEquals(PP1, Bundle.RESOLVED, bundles.get(PP1).getState());
		assertEquals(SP1, Bundle.INSTALLED, bundles.get(SP1).getState());
		assertEquals(CP1, Bundle.RESOLVED, bundles.get(CP1).getState());
		assertEquals(PP2, Bundle.INSTALLED, bundles.get(PP2).getState());
		assertEquals(SP2, Bundle.INSTALLED, bundles.get(SP2).getState());
		assertEquals(CP2, Bundle.INSTALLED, bundles.get(CP2).getState());
		assertEquals(BC1, Bundle.INSTALLED, bundles.get(BC1).getState());
		assertEquals(SC1, Bundle.INSTALLED, bundles.get(SC1).getState());
		assertEquals(CC1, Bundle.INSTALLED, bundles.get(CC1).getState());

		// now make the necessary connections
		// SP1
		digraph.connect(digraph.getRegion(SP1), digraph.createRegionFilterBuilder().allow(RegionFilter.VISIBLE_PACKAGE_NAMESPACE, "(" + RegionFilter.VISIBLE_PACKAGE_NAMESPACE + "=pkg1.*)").build(), digraph.getRegion(PP1));
		// PP2
		digraph.connect(digraph.getRegion(PP2), digraph.createRegionFilterBuilder().allow(CP1, "(name=" + CP1 + ")").build(), digraph.getRegion(CP1));
		// SP2
		digraph.connect(digraph.getRegion(SP2), digraph.createRegionFilterBuilder().allow(RegionFilter.VISIBLE_PACKAGE_NAMESPACE, "(" + RegionFilter.VISIBLE_PACKAGE_NAMESPACE + "=pkg2.*)").build(), digraph.getRegion(PP2));
		// CP2
		digraph.connect(digraph.getRegion(CP2), digraph.createRegionFilterBuilder().allow(RegionFilter.VISIBLE_PACKAGE_NAMESPACE, "(" + RegionFilter.VISIBLE_PACKAGE_NAMESPACE + "=pkg1.*)").build(), digraph.getRegion(PP1));
		digraph.connect(digraph.getRegion(CP2), digraph.createRegionFilterBuilder().allow(RegionFilter.VISIBLE_SERVICE_NAMESPACE, "(" + Constants.OBJECTCLASS + "=pkg1.*)").build(), digraph.getRegion(SP1));
		// PC1
		digraph.connect(digraph.getRegion(PC1), digraph.createRegionFilterBuilder().allow(RegionFilter.VISIBLE_PACKAGE_NAMESPACE, "(" + RegionFilter.VISIBLE_PACKAGE_NAMESPACE + "=pkg2.*)").build(), digraph.getRegion(PP2));
		// BC1
		digraph.connect(digraph.getRegion(BC1), digraph.createRegionFilterBuilder().allow(RegionFilter.VISIBLE_REQUIRE_NAMESPACE, "(" + RegionFilter.VISIBLE_REQUIRE_NAMESPACE + "=" + PP2 + ")").build(), digraph.getRegion(PP2));
		// SC1
		digraph.connect(digraph.getRegion(SC1), digraph.createRegionFilterBuilder().allow(RegionFilter.VISIBLE_PACKAGE_NAMESPACE, "(" + RegionFilter.VISIBLE_PACKAGE_NAMESPACE + "=pkg2.*)").build(), digraph.getRegion(PP2));
		digraph.connect(digraph.getRegion(SC1), digraph.createRegionFilterBuilder().allow(RegionFilter.VISIBLE_SERVICE_NAMESPACE, "(" + Constants.OBJECTCLASS + "=pkg2.*)").build(), digraph.getRegion(SP2));
		// CC1
		digraph.connect(digraph.getRegion(CC1), digraph.createRegionFilterBuilder().allow(CP2, "(name=" + CP2 + ")").build(), digraph.getRegion(CP2));

		bundleInstaller.resolveBundles(bundles.values().toArray(new Bundle[bundles.size()]));
		for (Bundle bundle : bundles.values()) {
			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=" + bundles.get(CP2).getBundleId() + "))"), null);
		ServiceTracker<Boolean, Boolean> sc1Tracker = new ServiceTracker<Boolean, Boolean>(context, context.createFilter("(&(objectClass=java.lang.Boolean)(bundle.id=" + bundles.get(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();
	}
Exemple #23
0
  private void setupTrackers(final BundleContext context) throws IOException {

    // initialize service trackers
    eventAdminTracker = new ServiceTracker(context, EventAdmin.class.getName(), null);
    eventAdminTracker.open();
    if (eventAdminTracker.getTrackingCount() == 0 && log != null) {
      log.log(
          LogService.LOG_WARNING,
          "NO EVENT ADMIN FOUND. REMOTE EVENT DELIVERY TEMPORARILY DISABLED."); //$NON-NLS-1$
    }

    try {
      eventHandlerTracker =
          new ServiceTracker(
              context,
              context.createFilter(
                  "(&("
                      + Constants.OBJECTCLASS
                      + "=" //$NON-NLS-1$ //$NON-NLS-2$
                      + EventHandler.class.getName()
                      + ")(!(" //$NON-NLS-1$
                      + R_OSGi_INTERNAL
                      + "=*)))"), //$NON-NLS-1$
              new ServiceTrackerCustomizer() {

                public Object addingService(final ServiceReference reference) {
                  final String[] theTopics =
                      (String[]) reference.getProperty(EventConstants.EVENT_TOPIC);
                  final LeaseUpdateMessage lu = new LeaseUpdateMessage();
                  lu.setType(LeaseUpdateMessage.TOPIC_UPDATE);
                  lu.setServiceID(""); // $NON-NLS-1$
                  lu.setPayload(new Object[] {theTopics, null});
                  updateLeases(lu);

                  return Arrays.asList(theTopics);
                }

                public void modifiedService(
                    final ServiceReference reference, final Object oldTopics) {

                  final List oldTopicList = (List) oldTopics;
                  final List newTopicList =
                      Arrays.asList((String[]) reference.getProperty(EventConstants.EVENT_TOPIC));
                  final Collection removed =
                      CollectionUtils.rightDifference(newTopicList, oldTopicList);
                  final Collection added =
                      CollectionUtils.leftDifference(newTopicList, oldTopicList);
                  final String[] addedTopics = (String[]) added.toArray(new String[removed.size()]);
                  final String[] removedTopics = (String[]) removed.toArray(addedTopics);
                  oldTopicList.removeAll(removed);
                  oldTopicList.addAll(added);
                  final LeaseUpdateMessage lu = new LeaseUpdateMessage();
                  lu.setType(LeaseUpdateMessage.TOPIC_UPDATE);
                  lu.setServiceID(""); // $NON-NLS-1$
                  lu.setPayload(new Object[] {addedTopics, removedTopics});
                  updateLeases(lu);
                }

                public void removedService(
                    final ServiceReference reference, final Object oldTopics) {
                  final List oldTopicsList = (List) oldTopics;
                  final String[] removedTopics =
                      (String[]) oldTopicsList.toArray(new String[oldTopicsList.size()]);
                  final LeaseUpdateMessage lu = new LeaseUpdateMessage();
                  lu.setType(LeaseUpdateMessage.TOPIC_UPDATE);
                  lu.setServiceID(""); // $NON-NLS-1$
                  lu.setPayload(new Object[] {null, removedTopics});
                  updateLeases(lu);
                }
              });
      eventHandlerTracker.open();

      if (DEBUG) {
        log.log(
            LogService.LOG_DEBUG,
            "Local topic space " //$NON-NLS-1$
                + Arrays.asList(getTopics()));
      }

      remoteServiceListenerTracker =
          new ServiceTracker(context, RemoteServiceListener.class.getName(), null);
      remoteServiceListenerTracker.open();

      serviceDiscoveryHandlerTracker =
          new ServiceTracker(
              context,
              ServiceDiscoveryHandler.class.getName(),
              new ServiceTrackerCustomizer() {

                public Object addingService(final ServiceReference reference) {
                  // register all known services for discovery
                  final ServiceDiscoveryHandler handler =
                      (ServiceDiscoveryHandler) context.getService(reference);

                  final RemoteServiceRegistration[] regs =
                      (RemoteServiceRegistration[])
                          serviceRegistrations
                              .values()
                              .toArray(new RemoteServiceRegistration[serviceRegistrations.size()]);

                  for (int i = 0; i < regs.length; i++) {
                    handler.registerService(
                        regs[i].getReference(),
                        regs[i].getProperties(),
                        URI.create(
                            "r-osgi://" //$NON-NLS-1$
                                + RemoteOSGiServiceImpl.MY_ADDRESS
                                + ":" //$NON-NLS-1$
                                + RemoteOSGiServiceImpl.R_OSGI_PORT
                                + "#" //$NON-NLS-1$
                                + regs[i].getServiceID()));
                  }
                  return handler;
                }

                public void modifiedService(
                    final ServiceReference reference, final Object service) {}

                public void removedService(
                    final ServiceReference reference, final Object service) {}
              });
      serviceDiscoveryHandlerTracker.open();

      remoteServiceTracker =
          new ServiceTracker(
              context,
              context.createFilter(
                  "(" //$NON-NLS-1$
                      + RemoteOSGiService.R_OSGi_REGISTRATION
                      + "=*)"),
              new ServiceTrackerCustomizer() { //$NON-NLS-1$

                public Object addingService(final ServiceReference reference) {

                  // FIXME: Surrogates have to be monitored
                  // separately!!!
                  final ServiceReference service =
                      Arrays.asList((String[]) reference.getProperty(Constants.OBJECTCLASS))
                              .contains(SurrogateRegistration.class.getName())
                          ? (ServiceReference)
                              reference.getProperty(SurrogateRegistration.SERVICE_REFERENCE)
                          : reference;

                  try {
                    final RemoteServiceRegistration reg =
                        new RemoteServiceRegistration(reference, service);

                    if (log != null) {
                      log.log(
                          LogService.LOG_INFO,
                          "REGISTERING " //$NON-NLS-1$
                              + reference
                              + " AS PROXIED SERVICES"); //$NON-NLS-1$
                    }

                    serviceRegistrations.put(service, reg);

                    registerWithServiceDiscovery(reg);

                    final LeaseUpdateMessage lu = new LeaseUpdateMessage();
                    lu.setType(LeaseUpdateMessage.SERVICE_ADDED);
                    lu.setServiceID(String.valueOf(reg.getServiceID()));
                    lu.setPayload(new Object[] {reg.getInterfaceNames(), reg.getProperties()});
                    updateLeases(lu);
                    return service;
                  } catch (final ClassNotFoundException e) {
                    e.printStackTrace();
                    throw new RemoteOSGiException("Cannot find class " + service, e); // $NON-NLS-1$
                  }
                }

                public void modifiedService(
                    final ServiceReference reference, final Object service) {
                  if (reference.getProperty(R_OSGi_REGISTRATION) == null) {
                    removedService(reference, service);
                    return;
                  }
                  final RemoteServiceRegistration reg =
                      (RemoteServiceRegistration) serviceRegistrations.get(reference);

                  unregisterFromServiceDiscovery(reg);
                  registerWithServiceDiscovery(reg);

                  final LeaseUpdateMessage lu = new LeaseUpdateMessage();
                  lu.setType(LeaseUpdateMessage.SERVICE_MODIFIED);
                  lu.setServiceID(String.valueOf(reg.getServiceID()));
                  lu.setPayload(new Object[] {null, reg.getProperties()});
                  updateLeases(lu);
                }

                public void removedService(final ServiceReference reference, final Object service) {

                  final ServiceReference sref =
                      Arrays.asList((String[]) reference.getProperty(Constants.OBJECTCLASS))
                              .contains(SurrogateRegistration.class.getName())
                          ? (ServiceReference)
                              reference.getProperty(SurrogateRegistration.SERVICE_REFERENCE)
                          : reference;

                  final RemoteServiceRegistration reg =
                      (RemoteServiceRegistration) serviceRegistrations.remove(sref);

                  unregisterFromServiceDiscovery(reg);

                  final LeaseUpdateMessage lu = new LeaseUpdateMessage();
                  lu.setType(LeaseUpdateMessage.SERVICE_REMOVED);
                  lu.setServiceID(String.valueOf(reg.getServiceID()));
                  lu.setPayload(new Object[] {null, null});
                  updateLeases(lu);
                }
              });
      remoteServiceTracker.open();

      networkChannelFactoryTracker =
          new ServiceTracker(
              context,
              context.createFilter(
                  "("
                      + Constants.OBJECTCLASS
                      + "=" //$NON-NLS-1$ //$NON-NLS-2$
                      + NetworkChannelFactory.class.getName()
                      + ")"),
              new ServiceTrackerCustomizer() { //$NON-NLS-1$

                public Object addingService(final ServiceReference reference) {
                  final NetworkChannelFactory factory =
                      (NetworkChannelFactory) context.getService(reference);
                  try {
                    factory.activate(RemoteOSGiServiceImpl.this);
                  } catch (final IOException ioe) {
                    if (log != null) {
                      log.log(LogService.LOG_ERROR, ioe.getMessage(), ioe);
                    }
                  }
                  return factory;
                }

                public void modifiedService(
                    final ServiceReference reference, final Object factory) {}

                public void removedService(
                    final ServiceReference reference, final Object factory) {}
              });
      networkChannelFactoryTracker.open();

    } catch (final InvalidSyntaxException ise) {
      ise.printStackTrace();
    }
  }
	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();
	}
  @Test
  public void testServiceNotificationListenerWithFilterServiceTracker() throws Exception {
    UserAgent userAgent = SLP.newUserAgent(newSettings());
    ServiceAgent serviceAgent = SLP.newServiceAgent(newSettings());
    final AtomicInteger counter = new AtomicInteger();

    userAgent.start();
    serviceAgent.start();

    ServiceNotificationListenerServiceTracker tracker =
        new ServiceNotificationListenerServiceTracker(
            bundleContext, bundleContext.createFilter("(&(foo=bar)(car=cdr))"), userAgent);
    tracker.open();

    Dictionary<String, String> dictionary = new Hashtable<String, String>();
    dictionary.put("foo", "bar");
    dictionary.put("car", "cdr");
    ServiceRegistration serviceRegistration =
        bundleContext.registerService(
            ServiceNotificationListener.class.getName(),
            new ServiceNotificationListener() {
              public void serviceRegistered(ServiceNotificationEvent event) {
                if ("service:jmx:rmi:///jndi/jmxrmi"
                    .equals(event.getService().getServiceURL().getURL())) {
                  counter.incrementAndGet();
                }
              }

              public void serviceDeregistered(ServiceNotificationEvent event) {
                if ("service:jmx:rmi:///jndi/jmxrmi"
                    .equals(event.getService().getServiceURL().getURL())) {
                  counter.decrementAndGet();
                }
              }
            },
            dictionary);

    ServiceURL serviceURL = new ServiceURL("service:jmx:rmi:///jndi/jmxrmi");
    ServiceInfo service =
        new ServiceInfo(
            serviceURL,
            Locale.ENGLISH.getLanguage(),
            Scopes.DEFAULT,
            Attributes.from("(a=1,2),(b=true),(c=string),(d=\\FF\\00),e"));

    serviceAgent.register(service);

    Thread.sleep(1000);

    Assert.assertEquals(1, tracker.size());
    Assert.assertEquals(1, counter.get());

    serviceAgent.deregister(service.getServiceURL(), service.getLanguage());

    Thread.sleep(1000);

    Assert.assertEquals(1, tracker.size());
    Assert.assertEquals(0, counter.get());

    serviceRegistration.unregister();

    Thread.sleep(500);

    Assert.assertEquals(0, tracker.size());
    Assert.assertEquals(0, counter.get());

    dictionary.put("foo", "bad-value");
    serviceRegistration =
        bundleContext.registerService(
            ServiceNotificationListener.class.getName(),
            new ServiceNotificationListener() {
              public void serviceRegistered(ServiceNotificationEvent event) {
                if ("service:jmx:rmi:///jndi/jmxrmi"
                    .equals(event.getService().getServiceURL().getURL())) {
                  counter.incrementAndGet();
                }
              }

              public void serviceDeregistered(ServiceNotificationEvent event) {
                if ("service:jmx:rmi:///jndi/jmxrmi"
                    .equals(event.getService().getServiceURL().getURL())) {
                  counter.decrementAndGet();
                }
              }
            },
            dictionary);

    serviceAgent.register(service);

    Thread.sleep(1000);

    Assert.assertEquals(0, tracker.size());
    Assert.assertEquals(0, counter.get());

    serviceAgent.deregister(service.getServiceURL(), service.getLanguage());

    Thread.sleep(1000);

    Assert.assertEquals(0, tracker.size());
    Assert.assertEquals(0, counter.get());

    serviceRegistration.unregister();

    Thread.sleep(500);

    Assert.assertEquals(0, tracker.size());
    Assert.assertEquals(0, counter.get());

    tracker.close();

    serviceAgent.stop();
    userAgent.stop();
  }
  @Test
  public void testDirectoryAgentListenerWithFilterServiceTracker() throws Exception {
    UserAgent userAgent = SLP.newUserAgent(newSettings());
    StandardDirectoryAgentServer directoryAgentServer =
        StandardDirectoryAgentServer.newInstance(newSettings());
    final AtomicInteger counter = new AtomicInteger();

    userAgent.start();

    DirectoryAgentListenerServiceTracker tracker =
        new DirectoryAgentListenerServiceTracker(
            bundleContext, bundleContext.createFilter("(&(foo=bar)(car=cdr))"), userAgent);
    tracker.open();

    Dictionary<String, String> dictionary = new Hashtable<String, String>();
    dictionary.put("foo", "bar");
    dictionary.put("car", "cdr");
    ServiceRegistration serviceRegistration =
        bundleContext.registerService(
            DirectoryAgentListener.class.getName(),
            new DirectoryAgentListener() {
              public void directoryAgentBorn(DirectoryAgentEvent event) {
                counter.incrementAndGet();
              }

              public void directoryAgentDied(DirectoryAgentEvent event) {
                counter.decrementAndGet();
              }
            },
            dictionary);

    directoryAgentServer.start();

    Thread.sleep(1000);

    Assert.assertEquals(1, tracker.size());
    Assert.assertEquals(1, counter.get());

    directoryAgentServer.stop();

    Thread.sleep(1000);

    Assert.assertEquals(1, tracker.size());
    Assert.assertEquals(0, counter.get());

    serviceRegistration.unregister();

    Thread.sleep(500);

    Assert.assertEquals(0, tracker.size());
    Assert.assertEquals(0, counter.get());

    dictionary.put("foo", "bad-value");
    serviceRegistration =
        bundleContext.registerService(
            DirectoryAgentListener.class.getName(),
            new DirectoryAgentListener() {
              public void directoryAgentBorn(DirectoryAgentEvent event) {
                counter.incrementAndGet();
              }

              public void directoryAgentDied(DirectoryAgentEvent event) {
                counter.decrementAndGet();
              }
            },
            dictionary);

    directoryAgentServer.start();

    Thread.sleep(1000);

    Assert.assertEquals(0, tracker.size());
    Assert.assertEquals(0, counter.get());

    directoryAgentServer.stop();

    Thread.sleep(1000);

    Assert.assertEquals(0, tracker.size());
    Assert.assertEquals(0, counter.get());

    serviceRegistration.unregister();

    Thread.sleep(500);

    Assert.assertEquals(0, tracker.size());
    Assert.assertEquals(0, counter.get());

    tracker.close();

    directoryAgentServer.stop();
    userAgent.stop();
  }
  /*
   Parses a
   <reference name="<name>" interface="<interface>"
       [bind="<bind-method>"] [unbind="<bind-method>"]
       [cardinality="<cardinality>"] [policy="<policy>"]/>


  */
  private static void setReference(Config compConf, XmlPullParser parser, Bundle declaringBundle)
      throws IllegalXMLException, XmlPullParserException, IOException {

    String name = null;
    String interfaceName = null;
    String target = null;
    String bind = null;
    String unbind = null;
    boolean optional = false; // default value
    boolean multiple = false; // default value
    boolean dynamic = false; // default value

    for (int i = 0; i < parser.getAttributeCount(); i++) {

      if (parser.getAttributeName(i).equals("name")) {
        if (checkNMToken(parser.getAttributeValue(i))) {
          name = parser.getAttributeValue(i);

        } else {
          throw new IllegalXMLException(
              "Attribute \"" + parser.getAttributeName(i) + "\" in reference-tag is invalid.");
        }
      } else if (parser.getAttributeName(i).equals("interface")) {
        if (checkToken(parser.getAttributeValue(i))) {
          interfaceName = parser.getAttributeValue(i);

        } else {
          throw new IllegalXMLException(
              "Attribute \"" + parser.getAttributeName(i) + "\" in reference-tag is invalid");
        }
      } else if (parser.getAttributeName(i).equals("cardinality")) {
        String val = parser.getAttributeValue(i);

        if ("1..1".equals(val)) {
          multiple = optional = false;
        } else if ("0..1".equals(val)) {
          optional = true;
          multiple = false;
        } else if ("1..n".equals(val)) {
          optional = false;
          multiple = true;
        } else if ("0..n".equals(val)) {
          multiple = optional = true;
        } else {
          invalidValue(
              parser,
              new String[] {
                "1..1", "0..1",
                "1..n", "0..n"
              },
              i);
        }

      } else if (parser.getAttributeName(i).equals("policy")) {
        String val = parser.getAttributeValue(i);

        if ("static".equals(val)) {
          dynamic = false;
        } else if ("dynamic".equals(val)) {
          dynamic = true;
        } else {
          invalidValue(parser, new String[] {"static", "dynamic"}, i);
        }

      } else if (parser.getAttributeName(i).equals("target")) {
        target = parser.getAttributeValue(i);

      } else if (parser.getAttributeName(i).equals("bind")) {
        bind = parser.getAttributeValue(i);

      } else if (parser.getAttributeName(i).equals("unbind")) {
        unbind = parser.getAttributeValue(i);

      } else {
        unrecognizedAttr(parser, i);
      }
    }

    skip(parser);

    if (name == null) missingAttr(parser, "name");

    if (interfaceName == null) missingAttr(parser, "interface");

    BundleContext bc = Backdoor.getBundleContext(declaringBundle);

    try {
      Filter filter;
      if (target != null) {
        filter =
            bc.createFilter(
                "(&(" + Constants.OBJECTCLASS + "=" + interfaceName + ")" + target + ")");
      } else {
        filter = bc.createFilter("(" + Constants.OBJECTCLASS + "=" + interfaceName + ")");
      }

      Reference ref =
          new Reference(name, filter, interfaceName, optional, multiple, dynamic, bind, unbind, bc);

      compConf.addReference(ref);
    } catch (InvalidSyntaxException e) {
      throw new IllegalXMLException("Couldn't create filter for reference \"" + name + "\"", e);
    }
  }
  @Override
  public void start(final BundleContext context) throws Exception {
    logger.debug("ConfigPersister starting");
    autoCloseables = new ArrayList<>();
    PropertiesProviderBaseImpl propertiesProvider = new PropertiesProviderBaseImpl(context);

    final PersisterAggregator persisterAggregator =
        PersisterAggregator.createFromProperties(propertiesProvider);
    autoCloseables.add(persisterAggregator);
    final long maxWaitForCapabilitiesMillis = getMaxWaitForCapabilitiesMillis(propertiesProvider);
    final List<ConfigSnapshotHolder> configs = persisterAggregator.loadLastConfigs();
    final long conflictingVersionTimeoutMillis =
        getConflictingVersionTimeoutMillis(propertiesProvider);
    logger.trace("Following configs will be pushed: {}", configs);
    ServiceTrackerCustomizer<NetconfOperationServiceFactory, NetconfOperationServiceFactory>
        configNetconfCustomizer =
            new ServiceTrackerCustomizer<
                NetconfOperationServiceFactory, NetconfOperationServiceFactory>() {
              @Override
              public NetconfOperationServiceFactory addingService(
                  ServiceReference<NetconfOperationServiceFactory> reference) {
                NetconfOperationServiceFactory service =
                    reference.getBundle().getBundleContext().getService(reference);
                final ConfigPusher configPusher =
                    new ConfigPusher(
                        service, maxWaitForCapabilitiesMillis, conflictingVersionTimeoutMillis);
                logger.debug("Configuration Persister got %s", service);
                final Thread pushingThread =
                    new Thread(
                        new Runnable() {
                          @Override
                          public void run() {
                            configPusher.pushConfigs(configs);
                            logger.info("Configuration Persister initialization completed.");
                            ConfigPersisterNotificationHandler jmxNotificationHandler =
                                new ConfigPersisterNotificationHandler(
                                    platformMBeanServer, persisterAggregator);
                            synchronized (ConfigPersisterActivator.this) {
                              autoCloseables.add(jmxNotificationHandler);
                            }
                          }
                        },
                        "config-pusher");
                synchronized (ConfigPersisterActivator.this) {
                  autoCloseables.add(
                      new AutoCloseable() {
                        @Override
                        public void close() throws Exception {
                          pushingThread.interrupt();
                        }
                      });
                }
                pushingThread.start();
                return service;
              }

              @Override
              public void modifiedService(
                  ServiceReference<NetconfOperationServiceFactory> reference,
                  NetconfOperationServiceFactory service) {}

              @Override
              public void removedService(
                  ServiceReference<NetconfOperationServiceFactory> reference,
                  NetconfOperationServiceFactory service) {}
            };

    Filter filter = context.createFilter(getFilterString());

    ServiceTracker<NetconfOperationServiceFactory, NetconfOperationServiceFactory> tracker =
        new ServiceTracker<>(context, filter, configNetconfCustomizer);
    tracker.open();
  }
Exemple #29
0
  @SuppressWarnings({"rawtypes", "unchecked"})
  @Override
  public void start(final BundleContext bc) throws Exception {
    ruleEngine = new RuleEngine(bc);

    Hashtable props = new Hashtable(11);
    props.put(Constants.SERVICE_PID, "smarthome.rule.configuration");
    configReg = bc.registerService(ManagedService.class.getName(), ruleEngine, props);

    this.tManager = new TemplateManager(bc, ruleEngine);
    ruleEngine.setTemplateManager(tManager);
    mtManager = new ModuleTypeManager(bc, ruleEngine);
    ruleEngine.setModuleTypeManager(mtManager);
    ruleEngine.setCompositeModuleFactory(
        new CompositeModuleHandlerFactory(bc, mtManager, ruleEngine));
    ConnectionValidator.setManager(mtManager);

    templateRegistry = new TemplateRegistryImpl(tManager);
    templateRegistryReg =
        bc.registerService(TemplateRegistry.class.getName(), templateRegistry, null);
    moduleTypeRegistry = new ModuleTypeRegistryImpl(mtManager);
    moduleTypeRegistryReg =
        bc.registerService(ModuleTypeRegistry.class.getName(), moduleTypeRegistry, null);
    ruleEventFactory = new RuleEventFactory();
    ruleEventFactoryReg = bc.registerService(EventFactory.class.getName(), ruleEventFactory, null);

    ruleRegistry = new RuleRegistryImpl(ruleEngine);

    Filter filter =
        bc.createFilter(
            "(|("
                + Constants.OBJECTCLASS
                + "="
                + StorageService.class.getName()
                + ")("
                + Constants.OBJECTCLASS
                + "="
                + RuleProvider.class.getName()
                + ")("
                + Constants.OBJECTCLASS
                + "="
                + EventPublisher.class.getName()
                + "))");

    serviceTracker =
        new ServiceTracker(
            bc,
            filter,
            new ServiceTrackerCustomizer() {

              @Override
              public Object addingService(ServiceReference reference) {
                Object service = bc.getService(reference);
                if (service instanceof StorageService) {
                  StorageService storage = (StorageService) service;
                  if (storage != null) {
                    Storage<Boolean> storageDisabledRules =
                        storage.getStorage(
                            "automation_rules_disabled", this.getClass().getClassLoader());
                    ruleRegistry.setDisabledRuleStorage(storageDisabledRules);
                    final ManagedRuleProvider managedRuleProvider =
                        new ManagedRuleProvider(storage);
                    ruleEngine.setManagedRuleProvider(managedRuleProvider);
                    ruleRegistry.setManagedProvider(managedRuleProvider);
                    managedRuleProviderReg =
                        bc.registerService(RuleProvider.class.getName(), managedRuleProvider, null);
                    return storage;
                  }
                } else if (service instanceof RuleProvider) {
                  RuleProvider rp = (RuleProvider) service;
                  ruleRegistry.addProvider(rp);
                  if (rp instanceof ManagedRuleProvider) {
                    ruleRegistryReg =
                        bc.registerService(RuleRegistry.class.getName(), ruleRegistry, null);
                  }
                  return rp;
                } else if (service instanceof EventPublisher) {
                  EventPublisher ep = (EventPublisher) service;
                  ruleRegistry.setEventPublisher(ep);
                  return ep;
                }
                return null;
              }

              @Override
              public void modifiedService(ServiceReference reference, Object service) {}

              @Override
              public void removedService(ServiceReference reference, Object service) {
                if (service instanceof StorageService) {
                  if (managedRuleProviderReg != null) {
                    managedRuleProviderReg.unregister();
                    managedRuleProviderReg = null;
                  }
                } else if (service instanceof EventPublisher) {
                  if (ruleRegistry != null) {
                    ruleRegistry.unsetEventPublisher((EventPublisher) service);
                  }
                } else if (service instanceof RuleProvider) {
                  if (ruleRegistry != null) {
                    RuleProvider rp = (RuleProvider) service;
                    if (rp instanceof ManagedRuleProvider) {
                      ruleRegistry.removeManagedProvider((ManagedProvider<Rule, String>) rp);
                    } else {
                      ruleRegistry.removeProvider(rp);
                    }
                  }
                }
              }
            });
    serviceTracker.open();
  }