Example #1
0
  public void activate() {
    try {
      // we need to call the activator ourselves as this bundle is included in the lib folder
      com.sun.jersey.core.osgi.Activator jerseyActivator = new com.sun.jersey.core.osgi.Activator();
      BundleContext bundleContext = FrameworkUtil.getBundle(this.getClass()).getBundleContext();
      try {
        jerseyActivator.start(bundleContext);
      } catch (Exception e) {
        logger.error("Could not start Jersey framework", e);
      }

      httpPort = Integer.parseInt(bundleContext.getProperty("jetty.port"));
      httpSSLPort = Integer.parseInt(bundleContext.getProperty("jetty.port.ssl"));

      httpService.registerServlet(
          CV_SERVLET_ALIAS, new AtmosphereServlet(), getJerseyServletParams(), createHttpContext());

      logger.info("Started Cometvisu API at " + CV_SERVLET_ALIAS);

      if (discoveryService != null) {
        discoveryService.registerService(getDefaultServiceDescription());
        discoveryService.registerService(getSSLServiceDescription());
      }
    } catch (ServletException se) {
      throw new RuntimeException(se);
    } catch (NamespaceException se) {
      throw new RuntimeException(se);
    }
  }
  @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();
    }
  }
Example #3
0
  /**
   * creates a new RemoteOSGiServiceImpl instance.
   *
   * @throws IOException in case of IO problems.
   */
  RemoteOSGiServiceImpl() throws IOException {
    // find out own IP address
    try {
      MY_ADDRESS =
          InetAddress.getAllByName(InetAddress.getLocalHost().getHostName())[0].getHostAddress();
    } catch (final Throwable t) {
      MY_ADDRESS =
          System.getProperty(
              "ch.ethz.iks.r_osgi.ip", //$NON-NLS-1$
              "127.0.0.1"); //$NON-NLS-1$
    }

    // set the debug switches
    final BundleContext context = RemoteOSGiActivator.getActivator().getContext();
    String prop = context.getProperty(PROXY_DEBUG_PROPERTY);
    PROXY_DEBUG = prop != null ? Boolean.valueOf(prop).booleanValue() : false;
    prop = context.getProperty(MSG_DEBUG_PROPERTY);
    MSG_DEBUG = prop != null ? Boolean.valueOf(prop).booleanValue() : false;
    prop = context.getProperty(DEBUG_PROPERTY);
    DEBUG = prop != null ? Boolean.valueOf(prop).booleanValue() : false;

    if (log != null) {
      if (PROXY_DEBUG) {
        log.log(LogService.LOG_INFO, "PROXY DEBUG OUTPUTS ENABLED"); // $NON-NLS-1$
      }
      if (MSG_DEBUG) {
        log.log(LogService.LOG_INFO, "MESSAGE DEBUG OUTPUTS ENABLED"); // $NON-NLS-1$
      }
      if (DEBUG) {
        log.log(LogService.LOG_INFO, "INTERNAL DEBUG OUTPUTS ENABLED"); // $NON-NLS-1$
      }
    } else {
      if (PROXY_DEBUG || MSG_DEBUG || DEBUG) {
        System.err.println(
            "WARNING: NO LOG SERVICE PRESENT, DEBUG PROPERTIES HAVE NO EFFECT ..."); //$NON-NLS-1$
        PROXY_DEBUG = false;
        MSG_DEBUG = false;
        DEBUG = false;
      }
    }

    // set port
    prop = context.getProperty(R_OSGi_PORT_PROPERTY);
    R_OSGI_PORT = prop != null ? Integer.parseInt(prop) : 9278;

    // initialize the transactionID with a random value
    nextXid = (short) Math.round(Math.random() * Short.MAX_VALUE);

    // get the package admin
    final ServiceReference ref = context.getServiceReference(PackageAdmin.class.getName());
    if (ref == null) {
      // TODO: handle this more gracefully
      throw new RuntimeException(
          "No package admin service available, R-OSGi terminates."); //$NON-NLS-1$
    }
    pkgAdmin = (PackageAdmin) context.getService(ref);

    setupTrackers(context);
  }
 @Override
 public Trigger getObject() throws Exception {
   return newTrigger()
       .withIdentity(name, bundleContext.getProperty(Constants.BUNDLE_NAME))
       .withDescription(bundleContext.getProperty(Constants.BUNDLE_DESCRIPTION))
       .startNow()
       .withSchedule(simpleSchedule().withIntervalInSeconds(30).repeatForever())
       .forJob(getJobDetail())
       .build();
 }
Example #5
0
 public static String getUUID(BundleContext bundleContext) {
   String uuid = bundleContext.getProperty(FRAMEWORK_UUID);
   if (uuid == null) {
     synchronized (FRAMEWORK_UUID) {
       uuid = bundleContext.getProperty(FRAMEWORK_UUID);
       if (uuid == null) {
         uuid = UuidGenerator.getUUID();
         System.setProperty(FRAMEWORK_UUID, uuid);
       }
     }
   }
   return uuid;
 }
Example #6
0
  /**
   * Gets the default logger level. The property is searched inside the framework properties, the
   * system properties, and in the manifest from the given bundle context. By default, set the level
   * to {@link Logger#WARNING}.
   *
   * @param context the bundle context.
   * @return the default log level.
   */
  private static int getDefaultLevel(BundleContext context) {
    // First check in the framework and in the system properties
    String level = context.getProperty(IPOJO_LOG_LEVEL_PROP);

    // If null, look in the bundle manifest
    if (level == null) {
      String key = IPOJO_LOG_LEVEL_PROP.replace('.', '-');
      level = (String) context.getBundle().getHeaders().get(key);
    }

    // if still null try the second header
    if (level == null) {
      level = (String) context.getBundle().getHeaders().get(IPOJO_LOG_LEVEL_HEADER);
    }

    if (level != null) {
      if (level.equalsIgnoreCase("info")) {
        return INFO;
      } else if (level.equalsIgnoreCase("debug")) {
        return DEBUG;
      } else if (level.equalsIgnoreCase("warning")) {
        return WARNING;
      } else if (level.equalsIgnoreCase("error")) {
        return ERROR;
      }
    }

    // Either l is null, either the specified log level was unknown
    // Set the default to WARNING
    return WARNING;
  }
  @Activate
  protected void activate(ComponentContext componentContext) throws Exception {
    LOG.info("Starting Activation of AMQ Broker ");
    try {
      Dictionary<?, ?> properties = componentContext.getProperties();
      BundleContext bundleContext = componentContext.getBundleContext();
      String brokerUrl = (String) properties.get(ACTIVEMQ_BROKER_URL);

      broker = new BrokerService();

      // generate a full path
      String slingHome = bundleContext.getProperty("sling.home");
      String dataPath = slingHome + "/activemq-data";
      LOG.info("Setting Data Path to  [{}] [{}] ", new Object[] {slingHome, dataPath});
      broker.setDataDirectory(dataPath);

      String federatedBrokerUrl = (String) properties.get(ACTIVEMQ_FEDERATED_BROKER_URL);

      if (federatedBrokerUrl != null && federatedBrokerUrl.length() > 0) {
        LOG.info("Federating ActiveMQ  [" + federatedBrokerUrl + "]");
        NetworkConnector connector = broker.addNetworkConnector(federatedBrokerUrl);
        connector.setDuplex(true);
      }

      // configure the broker
      LOG.info("Adding ActiveMQ connector [" + brokerUrl + "]");
      broker.addConnector(brokerUrl);

      broker.start();
    } catch (Exception e) {
      LOG.info(e.getMessage(), e);
      throw e;
    }
  }
 public OSGiRuntimeService(OSGiRuntimeContext runtimeContext, BundleContext context) {
   super(runtimeContext);
   bundleContext = context;
   bundles = new ConcurrentHashMap<String, Bundle>();
   contexts = new ConcurrentHashMap<String, RuntimeContext>();
   String bindAddress = context.getProperty(PROP_NUXEO_BIND_ADDRESS);
   if (bindAddress != null) {
     properties.put(PROP_NUXEO_BIND_ADDRESS, bindAddress);
   }
   String homeDir = getProperty(PROP_HOME_DIR);
   log.debug("Home directory: " + homeDir);
   if (homeDir != null) {
     workingDir = new File(homeDir);
   } else {
     workingDir = bundleContext.getDataFile("/");
   }
   // environment may not be set by some bootstrappers (like tests) - we
   // create it now if not yet created
   Environment env = Environment.getDefault();
   if (env == null) {
     Environment.setDefault(new Environment(workingDir));
   }
   workingDir.mkdirs();
   persistence = new ComponentPersistence(this);
   log.debug("Working directory: " + workingDir);
 }
  @Activate
  public void activate(BundleContext context) throws Exception {
    String f = context.getProperty("be.iminds.iot.dianne.dataset.chars.location");
    if (f != null) {
      this.file = f;
    }

    try {
      byte[] encoded = Files.readAllBytes(Paths.get(file));
      data = new String(encoded, Charset.defaultCharset());

      data.chars()
          .forEach(
              c -> {
                if (!chars.contains("" + (char) c)) {
                  chars += "" + (char) c;
                }
              });

      labels = new String[chars.length()];
      for (int i = 0; i < labels.length; i++) {
        labels[i] = "" + chars.charAt(i);
      }

    } catch (Exception e) {
      System.err.println("Failed to load char sequence dataset ... ");
      throw e;
    }
  }
  private void startInternal(BundleContext bundleContext) {
    // register the LogReaderService
    LogReaderServiceImpl logReader = new LogReaderServiceImpl(100);
    String readerServiceName = LogReaderService.class.getName();
    m_registrationLogReaderService =
        bundleContext.registerService(readerServiceName, logReader, null);

    // Tracking for the EventAdmin
    try {
      m_eventAdmin = new EventAdminTracker(bundleContext);
    } catch (NoClassDefFoundError e) {
      // If we hit a NoClassDefFoundError, this means the event admin package is not available,
      // so use a dummy poster
      m_eventAdmin =
          new EventAdminPoster() {
            public void postEvent(
                Bundle bundle,
                int level,
                LogEntry entry,
                String message,
                Throwable exception,
                ServiceReference sr,
                Map context) {}

            public void destroy() {}
          };
    }

    // register the Pax Logging service
    m_paxLogging =
        new PaxLoggingServiceImpl(bundleContext, logReader.getAccessDelegate(), m_eventAdmin);
    Hashtable<String, String> serviceProperties = new Hashtable<String, String>();
    serviceProperties.put(Constants.SERVICE_ID, "org.ops4j.pax.logging.configuration");
    serviceProperties.put(Constants.SERVICE_PID, CONFIGURATION_PID);
    m_RegistrationPaxLogging =
        bundleContext.registerService(LOG_SERVICE_INTERFACE_NAMES, m_paxLogging, serviceProperties);

    // Add a global handler for all JDK Logging (java.util.logging).
    if (!Boolean.valueOf(bundleContext.getProperty("org.ops4j.pax.logging.skipJUL"))) {
      LogManager manager = LogManager.getLogManager();
      manager.reset();

      // clear out old handlers
      Logger rootLogger = manager.getLogger("");
      Handler[] handlers = rootLogger.getHandlers();
      for (Handler handler : handlers) {
        rootLogger.removeHandler(handler);
      }

      rootLogger.setFilter(null);

      m_JdkHandler = new JdkHandler(m_paxLogging);
      rootLogger.addHandler(m_JdkHandler);
    }
    m_frameworkHandler = new FrameworkHandler(m_paxLogging);
    bundleContext.addBundleListener(m_frameworkHandler);
    bundleContext.addFrameworkListener(m_frameworkHandler);
    bundleContext.addServiceListener(m_frameworkHandler);
  }
Example #11
0
 private String getConfiguration(ConfigKey pKey) {
   // TODO: Use fragments and/or configuration service if available.
   String value = bundleContext.getProperty(CONFIG_PREFIX + "." + pKey.getKeyValue());
   if (value == null) {
     value = pKey.getDefaultValue();
   }
   return value;
 }
Example #12
0
 private int getMaxConnections(BundleContext context) {
   String maxConnectionsProperty = context.getProperty("org.foo.shell.connection.max");
   int maxConnections = 4;
   if (maxConnectionsProperty != null) {
     maxConnections = Integer.parseInt(maxConnectionsProperty);
   }
   return maxConnections;
 }
Example #13
0
 private int getPort(BundleContext context) {
   String portProperty = context.getProperty("org.foo.shell.port");
   int port = 7070;
   if (portProperty != null) {
     port = Integer.parseInt(portProperty);
   }
   return port;
 }
  @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();
    }
  }
Example #15
0
  /** Called whenever the OSGi framework starts our bundle */
  public void start(BundleContext bc) throws Exception {
    for (String key : propertyKeys) {
      HibernateUtil.properties.put(key, bc.getProperty(key));
    }

    Manager.setStorageInstance(new HibernateStorage());

    tracker = new ApplicationTracker(bc);
    tracker.open();
  }
  @Test
  public void checkDefaultBehavior() throws DeploymentException, IOException {
    DeploymentAdmin admin =
        (DeploymentAdmin)
            context.getService(context.getServiceReference(DeploymentAdmin.class.getName()));
    Assert.assertNotNull(admin);

    URL d = new URL((String) context.getProperty("dp1"));
    DeploymentPackage dp = admin.installDeploymentPackage(d.openStream());

    Bundle b1 = getBundleByName(context, "org.apache.felix.log");
    Assert.assertNull(b1);

    Bundle b2 = getBundleByName(context, "org.apache.felix.bundlerepository");
    Assert.assertNotNull(b2);

    Assert.assertEquals(Bundle.ACTIVE, b2.getState());

    URL d1 = new URL((String) context.getProperty("dp2"));
    DeploymentPackage dp2 = admin.installDeploymentPackage(d1.openStream());

    b1 = getBundleByName(context, "org.apache.felix.log");
    Assert.assertNotNull(b1);

    b2 = getBundleByName(context, "org.apache.felix.bundlerepository");
    Assert.assertNotNull(b2);

    Assert.assertEquals(Bundle.ACTIVE, b1.getState());
    Assert.assertEquals(Bundle.ACTIVE, b2.getState());

    dp.uninstall();

    // Bundle Repository uninstalled.
    b1 = getBundleByName(context, "org.apache.felix.log");
    Assert.assertNotNull(b1);

    b2 = getBundleByName(context, "org.apache.felix.bundlerepository");
    Assert.assertNull(b2);

    dp2.uninstall();
    b1 = getBundleByName(context, "org.apache.felix.log");
    Assert.assertNull(b1);
  }
  @Test
  public void testOSGi() throws Exception {
    Assert.assertNotNull(bundleContext);

    Bundle bundle = bundleContext.getBundle();
    System.out.println("symbolic name " + bundle.getSymbolicName());
    System.out.println("vendor " + bundleContext.getProperty(Constants.FRAMEWORK_VENDOR));

    for (Bundle b : bundleContext.getBundles()) {
      System.out.println(b.getSymbolicName() + " " + b.getBundleId());
    }
  }
Example #18
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;
  }
 @Override
 public String lookup(String key) {
   if ("solr-data-dir".equals(key)) {
     return core.getDataDir();
   } else if ("solr-index-dir".equals(key)) {
     return core.getIndexDir();
   } else if ("solr-server-name".equals(key)) {
     return indexRef.getServer();
   } else if ("solr-core-name".equals(key)) {
     return core.getName();
   } else {
     return bc.getProperty(key);
   }
 }
Example #20
0
  /** Called whenever the OSGi framework stops our bundle */
  public void stop(BundleContext bc) throws Exception {
    tracker.close();

    if ("org.h2.Driver".equals(bc.getProperty("headsup.db.driver"))) {
      try {
        ((HibernateStorage) Manager.getStorageInstance())
            .getHibernateSession()
            .createSQLQuery("SHUTDOWN")
            .executeUpdate();
      } catch (Exception e) {
        Manager.getLogger("StorageActivator").info("Unable to shut down DB - " + e.getMessage());
      }
    }
    HibernateUtil.shutdown();
  }
 /**
  * Calculates whether the job plugin should set worker threads to be daemon threads. When workers
  * are daemon threads, the job plugin does not need to be explicitly shut down because the VM can
  * exit while workers are still alive.
  *
  * @return <code>true</code> if all worker threads should be daemon threads, and <code>false
  *     </code> otherwise.
  */
 boolean useDaemonThreads() {
   BundleContext context = JobActivator.getContext();
   if (context == null) {
     // we are running stand-alone, so consult global system property
     String value = System.getProperty(IJobManager.PROP_USE_DAEMON_THREADS);
     // default to use daemon threads if property is absent
     if (value == null) return true;
     return "true".equalsIgnoreCase(value); // $NON-NLS-1$
   }
   // only use daemon threads if the property is defined
   final String value = context.getProperty(IJobManager.PROP_USE_DAEMON_THREADS);
   // if value is absent, don't use daemon threads to maintain legacy behaviour
   if (value == null) return false;
   return "true".equalsIgnoreCase(value); // $NON-NLS-1$
 }
 /** Overrides the default method to be able to include OSGi properties. */
 @Override
 public String getProperty(String name, String defValue) {
   String value = properties.getProperty(name);
   if (value == null) {
     value = bundleContext.getProperty(name);
     if (value == null) {
       return defValue == null ? null : expandVars(defValue);
     }
   }
   if (value.startsWith("$") && value.equals("${" + name + "}")) {
     // avoid loop, don't expand
     return value;
   }
   return expandVars(value);
 }
Example #23
0
  /** 初始化单一实例,从ConfigurationAdmin服务获取配置信息 */
  private RepositoryConfig() {

    BundleContext bc = FrameworkUtil.getBundle(this.getClass()).getBundleContext();
    ServiceReference configurationAdminReference =
        bc.getServiceReference(ConfigurationAdmin.class.getName());
    sofaContainerHome = bc.getProperty(Constains.SOFA_CONTAINER_HOME_KEY);
    if (configurationAdminReference != null) {
      ConfigurationAdmin configAdmin =
          (ConfigurationAdmin) bc.getService(configurationAdminReference);
      Configuration config;
      try {
        config = configAdmin.getConfiguration(Constains.CONFIG_SERVICES_PID);
      } catch (IOException e) {
        throw new RuntimeException(e.getMessage());
      }
      properties = config.getProperties();
    }
  }
Example #24
0
  private void warDeployerInternalInit(BundleContext bundleContext) {
    String kernelHome = System.getProperty("org.eclipse.virgo.kernel.home");
    if (kernelHome != null) {
      this.kernelHomeFile = new File(kernelHome);
      if (this.kernelHomeFile.exists()) {
        File bundlesInfoFile =
            new File(
                kernelHomeFile,
                "configuration/org.eclipse.equinox.simpleconfigurator/bundles.info");
        this.pickupDir = new File(kernelHomeFile, PICKUP_DIR);
        this.webAppsDir = new File(kernelHomeFile, WEBAPPS_DIR);
        this.bundleContext = bundleContext;
        this.bundleInfosUpdaterUtil = new BundleInfosUpdater(bundlesInfoFile, kernelHomeFile);
      } else {
        throw new IllegalStateException(
            "Required location '"
                + this.kernelHomeFile.getAbsolutePath()
                + "' does not exist. Check the value of the '"
                + KERNEL_HOME_PROP
                + "' propery");
      }
    } else {
      throw new IllegalStateException(
          "Missing value for required property '" + KERNEL_HOME_PROP + "'");
    }

    if (bundleContext == null) {
      TIMEOUT = DEFAULT_TIMEOUT;
      return;
    }

    String timeout = bundleContext.getProperty(UPDATE_TIMEOUT_PROP);
    if (timeout == null) {
      TIMEOUT = DEFAULT_TIMEOUT;
    } else {
      try {
        TIMEOUT = Long.parseLong(timeout);
      } catch (NumberFormatException e) {
        TIMEOUT = DEFAULT_TIMEOUT;
      }
    }

    registerWebContainerEventsHandler(bundleContext);
  }
  @Before
  public void setUp() throws UserTrackingException {
    SecurityService security = EasyMock.createMock(SecurityService.class);
    EasyMock.expect(security.getUser())
        .andReturn(new User(MOCK_USER, "mh_default", new String[] {"ROLE_USER"}))
        .anyTimes();

    BundleContext bc = EasyMock.createMock(BundleContext.class);
    EasyMock.expect(bc.getProperty("org.opencastproject.server.url"))
        .andReturn("http://www.example.org:8080")
        .anyTimes();

    @SuppressWarnings("rawtypes")
    Dictionary dict = EasyMock.createMock(Dictionary.class);
    EasyMock.expect(dict.get(RestConstants.SERVICE_PATH_PROPERTY))
        .andReturn("/usertracking")
        .anyTimes();

    ComponentContext context = EasyMock.createMock(ComponentContext.class);
    EasyMock.expect(context.getBundleContext()).andReturn(bc).anyTimes();
    EasyMock.expect(context.getProperties()).andReturn(dict).anyTimes();

    UserActionImpl ua = EasyMock.createMock(UserActionImpl.class);
    EasyMock.expect(ua.getId()).andReturn(4L).anyTimes();

    UserTrackingService usertracking = EasyMock.createMock(UserTrackingService.class);
    EasyMock.expect(usertracking.addUserFootprint(EasyMock.isA(UserAction.class)))
        .andReturn(ua)
        .anyTimes();

    EasyMock.replay(security, bc, dict, context, ua, usertracking);

    service = new UserTrackingRestService();
    service.setSecurityService(security);
    service.setService(usertracking);
    service.activate(context);
  }
 private void assertSystemProperty(
     BundleContext bundleContext, String property, String osgiProperty) {
   String expected = System.getProperty(property);
   assertNotNull(expected);
   assertEquals(expected, bundleContext.getProperty(osgiProperty));
 }
  protected void loadConfig() throws Exception {
    Environment env = Environment.getDefault();
    if (env != null) {
      log.info("Configuration: host application: " + env.getHostApplicationName());
    } else {
      log.warn("Configuration: no host application");
    }

    File blacklistFile = new File(env.getConfig(), "blacklist");
    if (blacklistFile.isFile()) {
      List<String> lines = FileUtils.readLines(blacklistFile);
      Set<String> blacklist = new HashSet<String>();
      for (String line : lines) {
        line = line.trim();
        if (line.length() > 0) {
          blacklist.add(line);
        }
      }
      manager.setBlacklist(new HashSet<String>(lines));
    }

    String configDir = bundleContext.getProperty(PROP_CONFIG_DIR);
    if (configDir != null && configDir.contains(":/")) { // an url of a
      // config file
      log.debug("Configuration: " + configDir);
      URL url = new URL(configDir);
      log.debug("Configuration:   loading properties url: " + configDir);
      loadProperties(url);
      return;
    }

    if (env == null) {
      return;
    }

    // TODO: in JBoss there is a deployer that will deploy nuxeo
    // configuration files ..
    boolean isNotJBoss4 = !isJBoss4(env);

    File dir = env.getConfig();
    // File dir = new File(configDir);
    String[] names = dir.list();
    if (names != null) {
      Arrays.sort(
          names,
          new Comparator<String>() {
            @Override
            public int compare(String o1, String o2) {
              return o1.compareToIgnoreCase(o2);
            }
          });
      for (String name : names) {
        if (name.endsWith("-config.xml") || name.endsWith("-bundle.xml")) {
          // TODO
          // because of some dep bugs (regarding the deployment of
          // demo-ds.xml)
          // we cannot let the runtime deploy config dir at
          // beginning...
          // until fixing this we deploy config dir from
          // NuxeoDeployer
          if (isNotJBoss4) {
            File file = new File(dir, name);
            log.debug("Configuration: deploy config component: " + name);
            context.deploy(file.toURI().toURL());
          }
        } else if (name.endsWith(".config")
            || name.endsWith(".ini")
            || name.endsWith(".properties")) {
          File file = new File(dir, name);
          log.debug("Configuration: loading properties: " + name);
          loadProperties(file);
        } else {
          log.debug("Configuration: ignoring: " + name);
        }
      }
    } else if (dir.isFile()) { // a file - load it
      log.debug("Configuration: loading properties: " + dir);
      loadProperties(dir);
    } else {
      log.debug("Configuration: no configuration file found");
    }

    loadDefaultConfig();
  }
Example #28
0
 // called by Felix DM
 protected final void start() throws Exception {
   m_logReader.addLogListener(this);
   m_frameworkUUID = m_context.getProperty(Constants.FRAMEWORK_UUID);
 }
Example #29
0
 @Activate
 public void activate(BundleContext context) {
   this.frameworkId = context.getProperty(Constants.FRAMEWORK_UUID);
 }
Example #30
0
  @Override
  public void start(BundleContext context) throws Exception {
    String val = context.getProperty(SERVICE_OVERRIDE_PROP);
    if (val == null || Boolean.parseBoolean(val)) {
      Dictionary<String, Object> props = new Hashtable<>();
      String ranking = context.getProperty(SERVICE_RANKING_PROP);
      if (ranking == null) {
        props.put(Constants.SERVICE_RANKING, DEFAULT_RANKING);
      } else {
        props.put(Constants.SERVICE_RANKING, Integer.valueOf(ranking));
      }
      TamayaConfigAdminImpl cm = new TamayaConfigAdminImpl(context);
      registration = context.registerService(ConfigurationAdmin.class, cm, props);
    }

    // register injection mechanisms, if not configured otherwise
    val = context.getProperty(SERVICE_INJECT_PROP);
    if (val == null || Boolean.parseBoolean(val)) {
      injectionTracker =
          new ServiceTracker<Object, Object>(context, Object.class, null) {
            @Override
            public Object addingService(ServiceReference<Object> reference) {
              Object service = context.getService(reference);
              Object pidObj = reference.getProperty(Constants.SERVICE_PID);
              if (pidObj instanceof String) {
                String pid = (String) pidObj;
                ConfigurationAdmin configAdmin = null;
                ServiceReference<ConfigurationAdmin> adminRef =
                    context.getServiceReference(ConfigurationAdmin.class);
                if (adminRef != null) {
                  configAdmin = context.getService(adminRef);
                }
                try {
                  Configuration targetConfig = null;
                  if (configAdmin != null) {
                    org.osgi.service.cm.Configuration osgiConfig =
                        configAdmin.getConfiguration(pid);
                    if (osgiConfig != null) {
                      targetConfig = new OSGIEnhancedConfiguration(osgiConfig);
                    }
                  }
                  if (targetConfig == null) {
                    targetConfig = ConfigurationProvider.getConfiguration();
                  }
                  ConfigurationInjection.getConfigurationInjector()
                      .configure(service, targetConfig);
                } catch (Exception e) {
                  LOG.log(Level.WARNING, "Error configuring Service: " + service, e);
                }
              } else {
                LOG.log(Level.SEVERE, "Unsupported pid: " + pidObj);
              }
              return service;
            }

            @Override
            public void removedService(ServiceReference<Object> reference, Object service) {
              context.ungetService(reference);
            }
          };
      injectionTracker.open();
    }
  }