public void tstTaskExecutor() throws Exception {
    Dictionary headers = new Hashtable();
    headers.put(Constants.BUNDLE_NAME, "Extender mock bundle");
    final EntryLookupControllingMockBundle aBundle = new EntryLookupControllingMockBundle(headers);
    aBundle.setEntryReturnOnNextCallToGetEntry(
        new ClassPathResource("META-INF/spring/moved-extender.xml").getURL());

    MockBundleContext ctx =
        new MockBundleContext() {

          public Bundle getBundle() {
            return aBundle;
          }
        };

    this.listener.start(ctx);

    Dictionary hdrs = new Hashtable();
    hdrs.put(ConfigUtils.SPRING_CONTEXT_HEADER, "bla bla");
    MockBundle anotherBundle = new MockBundle(hdrs);
    anotherBundle.setBundleId(1);

    BundleEvent event = new BundleEvent(BundleEvent.STARTED, anotherBundle);

    BundleListener listener = (BundleListener) ctx.getBundleListeners().iterator().next();

    TestTaskExecutor.called = false;

    listener.bundleChanged(event);
    assertTrue(
        "task executor should have been called if configured properly", TestTaskExecutor.called);
  }
  @SuppressWarnings("rawtypes")
  public void updated(String pid, Dictionary properties) throws ConfigurationException {
    DataSourceEntry dsEntry = dataSources.get(pid);
    if (dsEntry != null) {
      dsEntry.getServiceRegistration().unregister();
      dataSources.remove(pid);
    }

    try {

      Properties dsProperties = filterDataSourceProperties(properties);
      DataSource ds = datasourceFactory.createDataSource(dsProperties);

      Dictionary<String, String> registrationProperties = new Hashtable<String, String>();
      String databaseName = (String) properties.get(DataSourceFactory.JDBC_DATABASE_NAME);
      String datasourceName = (String) properties.get(DataSourceFactory.JDBC_DATASOURCE_NAME);
      if (datasourceName != null)
        registrationProperties.put(DataSourceFactory.JDBC_DATASOURCE_NAME, datasourceName);
      registrationProperties.put(DataSourceFactory.JDBC_SERVER_NAME, databaseName);
      ServiceRegistration serviceRegistration =
          bundleContext.registerService(DataSource.class.getName(), ds, registrationProperties);
      dsEntry = new DataSourceEntry(ds, serviceRegistration);
      dataSources.put(pid, dsEntry);
    } catch (SQLException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
  protected void validate() {
    try {
      Dictionary<String, Object> fileSystemDictionary =
          getConfigurationDictionary(FileSystemStoreConfiguration.class);

      Dictionary<String, Object> advancedFileSystemDictionary =
          getConfigurationDictionary(AdvancedFileSystemStoreConfiguration.class);

      if ((fileSystemDictionary != null) && (advancedFileSystemDictionary != null)) {

        String fileSystemRootDir = (String) fileSystemDictionary.get("rootdir");

        String advancedFileSystemRootDir = (String) advancedFileSystemDictionary.get("rootdir");

        if (Validator.equals(fileSystemRootDir, advancedFileSystemRootDir)) {

          throw new IllegalArgumentException(
              "File system root directory and advanced file "
                  + "system root directory are identical",
              new FileSystemStoreRootDirException());
        }
      }
    } catch (IOException ioe) {
      throw new IllegalArgumentException(ioe);
    }
  }
Example #4
0
  public static <E, F> void addRange(Dictionary<E, F> destino, Dictionary<E, F> valores) {
    List<E> keys = Collections.list(valores.keys());

    for (E key : keys) {
      destino.put(key, valores.get(key));
    }
  }
Example #5
0
 private static StringBuffer printMapOrDict(
     StringBuffer out, java.util.Map map, java.util.Dictionary dict, Conf conf) {
   if (map != null && map.size() == 0) return out.append("{}");
   if (dict != null && dict.size() == 0) return out.append("{}");
   indent(out, conf);
   out.append('{');
   newline(out, conf);
   conf.currentIndent++;
   if (map != null)
     for (java.util.Iterator it = map.keySet().iterator(); it.hasNext(); ) {
       Object key = it.next();
       Object value = map.get(key);
       printKeyValue(out, key, value, conf);
     }
   else
     for (java.util.Enumeration en = dict.keys(); en.hasMoreElements(); ) {
       Object key = en.nextElement();
       Object value = dict.get(key);
       printKeyValue(out, key, value, conf);
     }
   conf.currentIndent--;
   indent(out, conf);
   out.append('}');
   return newline(out, conf);
 }
Example #6
0
 public void start(final BundleContext context) throws Exception {
   final Dictionary properties = new Hashtable();
   properties.put(
       NetworkChannelFactory.PROTOCOL_PROPERTY, MinaNetworkChannelFactory.PROTOCOL_SCHEME);
   context.registerService(
       NetworkChannelFactory.class.getName(), new MinaNetworkChannelFactory(), properties);
 }
  public void updated(String pid, Dictionary<String, ?> configuration)
      throws ConfigurationException {
    synchronized (m_updateLock) {
      if (m_log.doDebug()) {
        m_log.debug("Updated pid=" + pid);
      }

      if (!PID.equals(pid) && (null != m_services.get(PID))) {
        if (m_log.doDebug()) {
          m_log.debug("Overriding default instance with new pid " + pid);
        }

        deleted(PID);
      }

      SslServiceWrapper service = m_services.get(pid);
      if (service == null) {
        if (m_log.doDebug()) {
          m_log.debug("create pid=" + pid);
        }

        service = new SslServiceWrapper(m_bc, m_log);
        m_services.put(pid, service);
      }

      service.update(configuration);
    }
  }
 @SuppressWarnings("unchecked")
 public static Event createEvent(String user, String activityItemPath) {
   final Dictionary<String, String> map = new Hashtable(1);
   map.put(UserConstants.EVENT_PROP_USERID, user);
   map.put(ActivityConstants.EVENT_PROP_PATH, activityItemPath);
   return new Event(EVENT_TOPIC, (Dictionary) map);
 }
  /**
   * @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 testSendEvent() throws Exception {
    addHelloWorldRule();
    ContextCurrentService contextService = getOsgiService(ContextCurrentService.class);
    contextService.createContext("42");
    ContextHolder.get().setCurrentContextId("42");

    Dictionary<String, Object> properties = new Hashtable<String, Object>();
    String[] clazzes = new String[] {Domain.class.getName(), ExampleDomain.class.getName()};
    properties.put("id", "dummyLog");
    properties.put("location.42", new String[] {"example"});

    DummyLogDomain logService = new DummyLogDomain();
    getBundleContext().registerService(clazzes, logService, properties);

    LogEvent e = new LogEvent();
    e.setName("42");
    e.setLevel(LogLevel.INFO);

    ExampleDomainEvents exampleEvents = getOsgiService(ExampleDomainEvents.class);
    // this should be routed through the domain, which forwards it to the workflow service
    exampleEvents.raiseEvent(e);

    assertThat(logService.isWasCalled(), is(true));
  }
  protected void checkResourceBundles(
      BundleContext bundleContext,
      ClassLoader classLoader,
      com.liferay.portal.model.Portlet portletModel,
      ServiceRegistrations serviceRegistrations) {

    if (Validator.isBlank(portletModel.getResourceBundle())) {
      return;
    }

    for (Locale locale : LanguageUtil.getAvailableLocales()) {
      ResourceBundle resourceBundle =
          ResourceBundleUtil.getBundle(portletModel.getResourceBundle(), locale, classLoader);

      Dictionary<String, Object> properties = new HashMapDictionary<>();

      properties.put("javax.portlet.name", portletModel.getPortletId());
      properties.put("language.id", LocaleUtil.toLanguageId(locale));

      ServiceRegistration<ResourceBundle> serviceRegistration =
          bundleContext.registerService(ResourceBundle.class, resourceBundle, properties);

      serviceRegistrations.addServiceRegistration(serviceRegistration);
    }
  }
  private void registerFactoryService() {
    Dictionary<String, Object> properties = new Hashtable<String, Object>();
    properties.put(REMOTE_CONFIGS_SUPPORTED, SUPPORTED_CONFIGURATION_TYPES);
    properties.put(REMOTE_INTENTS_SUPPORTED, SUPPORTED_INTENTS);

    RemoteServiceAdminFactory factory = new RemoteServiceAdminFactory(m_dependencyManager);

    Component component =
        createComponent()
            .setInterface(RemoteServiceAdmin.class.getName(), properties)
            .setImplementation(factory)
            .add(createServiceDependency().setService(LogService.class).setRequired(false))
            .add(
                createServiceDependency()
                    .setService(RemoteServiceAdminListener.class)
                    .setCallbacks(factory.getEventsHandler(), "listenerAdded", "listenerRemoved")
                    .setRequired(false))
            .add(
                createServiceDependency()
                    .setService(EventAdmin.class)
                    .setCallbacks(
                        factory.getEventsHandler(), "eventAdminAdded", "eventAdminRemoved")
                    .setRequired(false))
            .add(
                createServiceDependency()
                    .setService(WiringSender.class)
                    .setRequired(false)
                    .setCallbacks("wiringSenderAdded", "wiringSenderRemoved"));

    m_factoryComponent = component;
    m_dependencyManager.add(component);
  }
  @Override
  protected void setUp() throws Exception {
    super.setUp();

    NMR nmr = OsgiSupport.getReference(bundleContext, NMR.class);
    assertNotNull(nmr);

    endpointService1 = ServiceMixSupport.createAndRegisterEndpoint(nmr, service1, null);
    endpointService2 =
        ServiceMixSupport.createAndRegisterEndpoint(
            nmr, service2, new ExchangeProcessorImpl(service2.toString()));

    mockInterceptor = new MockInterceptor();

    Dictionary<String, String> interceptorProps = new Hashtable<String, String>();
    interceptorProps.put("role", "consumer,provider");
    interceptorProps.put("scope", "request,response");

    addRegistrationToCancel(
        bundleContext.registerService(
            Interceptor.class.getCanonicalName(), mockInterceptor, interceptorProps));
    Thread.sleep(500);

    reset(resolverMock);
  }
  @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;
    }
  }
  protected void encodeObject(
      org.w3c.dom.Document document,
      org.w3c.dom.Element node,
      edu.cmu.cs.stage3.io.DirectoryTreeStorer storer,
      edu.cmu.cs.stage3.alice.core.ReferenceGenerator referenceGenerator)
      throws java.io.IOException {
    java.util.Dictionary dict = getDictionaryValue();
    if (dict != null) {
      java.util.Enumeration enum0 = dict.keys();
      while (enum0.hasMoreElements()) {
        Object key = enum0.nextElement();
        Object value = dict.get(key);

        org.w3c.dom.Element entryNode = document.createElement("entry");

        org.w3c.dom.Element keyNode = document.createElement("key");
        keyNode.setAttribute("class", key.getClass().getName());
        keyNode.appendChild(createNodeForString(document, key.toString()));

        org.w3c.dom.Element valueNode = document.createElement("value");
        valueNode.setAttribute("class", value.getClass().getName());
        valueNode.appendChild(createNodeForString(document, value.toString()));

        entryNode.appendChild(keyNode);
        entryNode.appendChild(valueNode);
        node.appendChild(entryNode);
      }
    }
  }
  public static int getScrollY(AbsListView lv) {
    View c = lv.getChildAt(0);
    if (c == null) {
      return 0;
    }

    int firstVisiblePosition = lv.getFirstVisiblePosition();
    int scrollY = -(c.getTop());
    //        int scrollY = 0;

    sListViewItemHeights.put(lv.getFirstVisiblePosition(), c.getHeight());

    //        if(scrollY>0)
    //            Log.d("QuickReturnUtils", "getScrollY() : -(c.getTop()) - "+ -(c.getTop()));
    //        else
    //            Log.i("QuickReturnUtils", "getScrollY() : -(c.getTop()) - "+ -(c.getTop()));

    if (scrollY < 0) scrollY = 0;

    for (int i = 0; i < firstVisiblePosition; ++i) {
      //            Log.d("QuickReturnUtils", "getScrollY() : i - "+i);

      //            Log.d("QuickReturnUtils", "getScrollY() : sListViewItemHeights.get(i) -
      // "+sListViewItemHeights.get(i));

      if (sListViewItemHeights.get(i) != null) // (this is a sanity check)
      scrollY += sListViewItemHeights.get(i); // add all heights of the views that are gone
    }

    //        Log.d("QuickReturnUtils", "getScrollY() : scrollY - "+scrollY);

    return scrollY;
  }
Example #17
0
  public void register() {
    HashSet<String> profiles = new HashSet<String>();
    HashSet<String> rawClustersIds = new HashSet<String>();

    Enumeration<String> keys = clusters.keys();
    String[] clusterIDs = new String[clusters.size()];
    int i = 0;
    while (keys.hasMoreElements()) {
      String key = (String) keys.nextElement();
      clusterIDs[i++] = key;

      String[] parts = key.split(":");
      if (parts.length == 2) {
        profiles.add(parts[PROFILE_ID_IDX]);
        rawClustersIds.add(parts[CLUSTER_ID_IDX]);
      } else {
        log.warn(
            "Using cluster key {}, that does not belong to the standard format <profileId>:<clusterId>, "
                + "so unable to populate automatically the profile id set and cluster raw id set. "
                + "The cluster {} will be ignored.",
            key,
            clusters.get(key));
      }
    }
    dictionary.put(Cluster.PROFILE_CLUSTER_IDS, clusterIDs);
    dictionary.put(Cluster.BELONGING_PROFILES, profiles.toArray(new String[] {}));
    dictionary.put(Cluster.RAW_CLUSTER_IDS, rawClustersIds.toArray(new String[] {}));
    registration = ctx.registerService(ClusterFactory.class.getName(), this, dictionary);
  }
Example #18
0
  /** @param aProperties the updated properties. */
  @SuppressWarnings("rawtypes")
  final void setProperties(final Dictionary aProperties) {
    final Map<String, String> newProps = new HashMap<String, String>();

    Enumeration keys = aProperties.keys();
    while (keys.hasMoreElements()) {
      final String key = (String) keys.nextElement();
      if (!KNOWN_KEYS.contains(key) && !IGNORED_KEYS.contains(key)) {
        LOG.log(Level.WARNING, "Unknown/unsupported profile key: " + key);
        continue;
      }

      final String value = aProperties.get(key).toString();
      newProps.put(key, value.trim());
    }

    // Verify whether all known keys are defined...
    final List<String> checkedKeys = new ArrayList<String>(KNOWN_KEYS);
    checkedKeys.removeAll(newProps.keySet());
    if (!checkedKeys.isEmpty()) {
      throw new IllegalArgumentException(
          "Profile settings not complete! Missing keys are: " + checkedKeys.toString());
    }

    this.properties.putAll(newProps);

    LOG.log(
        Level.INFO,
        "New device profile settings applied for {1} ({0}) ...", //
        new Object[] {getType(), getDescription()});
  }
  @Before
  public void setUp() throws BundleException, InterruptedException {

    Dictionary<String, String> initParams = new Hashtable<String, String>();
    initParams.put("alias", "/");
    service = bundleContext.registerService(Servlet.class, new WhiteboardServlet("/"), initParams);
  }
  public static Map<String, Object> dictionaryToMap(
      Dictionary<String, Object> dictionary, OCD ocd) {
    if (dictionary == null) {
      return null;
    }

    Map<String, AD> ads = new HashMap<String, AD>();
    if (ocd != null) {
      for (AD ad : ocd.getAD()) {
        ads.put(ad.getId(), ad);
      }
    }
    Map<String, Object> map = new HashMap<String, Object>();
    Enumeration<String> keys = dictionary.keys();
    while (keys.hasMoreElements()) {

      String key = keys.nextElement();
      Object value = dictionary.get(key);
      AD ad = ads.get(key);
      if (ad != null && ad.getType() != null && Scalar.PASSWORD.equals(ad.getType())) {
        if (value instanceof char[]) {
          map.put(key, new Password((char[]) value));
        } else {
          map.put(key, new Password(value.toString()));
        }
      } else {
        map.put(key, value);
      }
    }
    return map;
  }
  private void initializeProperties(Dictionary<String, Object> dict) {
    // Create a case-insensitive map for the properties.
    Map<String, Object> props = new StringMap();

    if (dict != null) {
      // Make sure there are no duplicate keys.
      Enumeration<String> keys = dict.keys();
      while (keys.hasMoreElements()) {
        String key = keys.nextElement();
        if (props.get(key) == null) {
          props.put(key, dict.get(key));
        } else {
          throw new IllegalArgumentException("Duplicate service property: " + key);
        }
      }
    }

    // Add the framework assigned properties.
    props.put(Constants.OBJECTCLASS, m_classes);
    props.put(Constants.SERVICE_ID, m_serviceId);
    props.put(Constants.SERVICE_BUNDLEID, m_bundle.getBundleId());
    if (m_factory != null) {
      props.put(
          Constants.SERVICE_SCOPE,
          (m_factory instanceof PrototypeServiceFactory
              ? Constants.SCOPE_PROTOTYPE
              : Constants.SCOPE_BUNDLE));
    } else {
      props.put(Constants.SERVICE_SCOPE, Constants.SCOPE_SINGLETON);
    }

    // Update the service property map.
    m_propMap = props;
  }
  public static Dictionary<String, Object> mapToDictionary(Map<String, Object> map) {
    if (map == null) {
      return null;
    }

    Dictionary<String, Object> dictionary = new Hashtable<String, Object>();
    Iterator<String> keys = map.keySet().iterator();
    while (keys.hasNext()) {
      String key = keys.next();
      Object value = map.get(key);
      if (value != null) {
        if (value
            instanceof
            Password) { // TODO: this should be removed in next version. Password values should be
                        // kept as they are and not mapped to String objects. This was originally
                        // done due to Password class not in APIs, but this is not the condition
                        // anymore. This change would cause third party code to receive Password
                        // objects instead of strings. At the other side, managing everything with
                        // Password objects would make everything more logic and consistent.
          dictionary.put(key, value.toString());
        } else {
          dictionary.put(key, value);
        }
      }
    }
    return dictionary;
  }
  /**
   * Set the values of an OSGi configuration for a given PID.
   *
   * @param pid The PID of the OSGi component to update
   * @param properties The properties and values of the config to update
   * @return true if the properties were updated successfully
   */
  public boolean setProperties(final String pid, final Map<String, Object> properties) {
    try {
      Configuration conf = configAdmin.getConfiguration(pid);

      @SuppressWarnings("unchecked")
      Dictionary<String, Object> props = conf.getProperties();

      if (props == null) {
        props = new Hashtable<String, Object>();
      }

      /* props is of type org.apache.felix.cm.impl.CaseInsensitiveDictionary which
       * contains an internal HashTable and doesn't contain a putAll(Map) method.
       * Iterate over the map and put the values into the Dictionary individually.
       * Remove null values from HashMap as HashTable doesn't support them. */
      for (Map.Entry<String, Object> entry : properties.entrySet()) {
        String key = entry.getKey();
        Object value = entry.getValue();

        props.put(key, value != null ? value : StringUtils.EMPTY);
      }

      conf.update(props);
    } catch (IOException e) {
      LOGGER.error("Could not set property", e);
      return false;
    }

    return true;
  }
Example #24
0
  /** @{inheritDoc */
  @Override
  public void updated(Dictionary<String, ?> config) throws ConfigurationException {
    // logger.debug("updated() is called!");

    setProperlyConfigured(false);

    if (config != null) {

      String refreshIntervalString = (String) config.get("refresh");
      if (StringUtils.isNotBlank(refreshIntervalString)) {
        refreshInterval = Long.parseLong(refreshIntervalString);
      }

      String ip = (String) config.get("ip"); // $NON-NLS-1$
      if (StringUtils.isBlank(ip)) {
        throw new ConfigurationException("ip", "The ip address must not be empty.");
      }
      this.ip = ip;

      String username = (String) config.get("username"); // $NON-NLS-1$
      if (StringUtils.isBlank(username)) {
        throw new ConfigurationException("username", "The username must not be empty.");
      }
      this.username = username;

      String password = (String) config.get("password"); // $NON-NLS-1$
      if (StringUtils.isBlank(password)) {
        throw new ConfigurationException("password", "The password must not be empty.");
      }
      this.password = password;

      setProperlyConfigured(true);
    }
  }
Example #25
0
  AD localize(Dictionary<?, ?> dict) {
    final AD localized = (AD) this.clone();

    if (name != null && name.startsWith("%")) {
      String sub;
      if ((sub = (String) dict.get(name.substring(1))) != null) {
        localized.name = sub;
      }
    }

    if (desc != null && desc.startsWith("%")) {
      String sub;
      if ((sub = (String) dict.get(desc.substring(1))) != null) {
        localized.desc = sub;
      }
    }

    if (optLabels != null) {
      for (int i = 0; i < optLabels.length; i++) {
        if (optLabels[i].startsWith("%")) {
          String sub;
          if ((sub = (String) dict.get(optLabels[i].substring(1))) != null) {
            localized.optLabels[i] = sub;
          }
        }
      }
    }

    return localized;
  }
  public Dictionary<String, Object> getProperties() {
    Dictionary<String, Object> properties = new Hashtable<>();

    AttributeDefinition[] attributeDefinitions =
        _configurationModel.getAttributeDefinitions(ConfigurationModel.ALL);

    for (AttributeDefinition attributeDefinition : attributeDefinitions) {
      Object value = null;

      List<DDMFormFieldValue> ddmFormFieldValues =
          _ddmFormFieldValuesMap.get(attributeDefinition.getID());

      if (attributeDefinition.getCardinality() == 0) {
        value = toSimpleValue(ddmFormFieldValues.get(0));
      } else if (attributeDefinition.getCardinality() > 0) {
        value = toArrayValue(ddmFormFieldValues);
      } else if (attributeDefinition.getCardinality() < 0) {
        value = toVectorValue(ddmFormFieldValues);
      }

      properties.put(attributeDefinition.getID(), value);
    }

    return properties;
  }
 @Test(expected = IllegalStateException.class)
 public void testNoDomainProviderAvailableForType_shouldThrowIllegalArgumentException()
     throws Exception {
   DefaultOsgiUtilsService defaultOsgiUtilsService = new DefaultOsgiUtilsService();
   defaultOsgiUtilsService.setBundleContext(bundleContextMock);
   ConnectorRegistrationManagerImpl connectorRegistrationManagerImpl =
       new ConnectorRegistrationManagerImpl();
   connectorRegistrationManagerImpl.setBundleContext(bundleContextMock);
   connectorRegistrationManagerImpl.setServiceUtils(defaultOsgiUtilsService);
   ConnectorInstanceFactory connectorInstanceFactoryMock = mock(ConnectorInstanceFactory.class);
   Dictionary<String, Object> props = new Hashtable<String, Object>();
   props.put("connector", "a");
   props.put("domain", "a");
   registerService(connectorInstanceFactoryMock, props, ConnectorInstanceFactory.class);
   DomainProvider domainProviderMock = mock(DomainProvider.class);
   when(domainProviderMock.getDomainInterface())
       .thenAnswer(
           new Answer<Class<? extends Domain>>() {
             @Override
             public Class<? extends Domain> answer(InvocationOnMock invocation) throws Throwable {
               return NullDomainImpl.class;
             }
           });
   Dictionary<String, Object> propsDomainProvider = new Hashtable<String, Object>();
   propsDomainProvider.put("domain", "a");
   registerService(domainProviderMock, propsDomainProvider, DomainProvider.class);
   ConnectorId connectorId = new ConnectorId("a", "a", "a");
   connectorRegistrationManagerImpl.updateRegistration(
       connectorId,
       new ConnectorDescription(new HashMap<String, String>(), new HashMap<String, Object>()));
 }
 @Activate
 private void activate(ComponentContext componentContext) {
   Dictionary config = componentContext.getProperties();
   requestThreadLocal =
       PropertiesUtil.toBoolean(
           config.get(PARAM_REQUEST_THREAD_LOCAL), PARAM_REQUEST_THREAD_LOCAL_DEFAULT);
 }
Example #29
0
  public void execute(Session session, String line, PrintStream out, PrintStream err) {
    // Parse command line.
    StringTokenizer st = new StringTokenizer(line, " ");

    // Ignore the command name.
    st.nextToken();

    // Check for optional argument.
    String property = null;
    if (st.countTokens() >= 1) {
      property = st.nextToken().trim();
    }

    try {
      if (session.getAttribute(Activator.CURRENT) == null) {
        throw new Exception("No configuration open currently");
      }
      Dictionary dict = (Dictionary) session.getAttribute(Activator.EDITED);
      if (dict == null) {
        Configuration cfg = (Configuration) session.getAttribute(Activator.CURRENT);
        dict = cfg.getProperties();
        session.setAttribute(Activator.EDITED, dict);
      }
      Object oldValue = dict.remove(property);
      if (oldValue == null) {
        throw new Exception("No property named " + property + " in current configuration.");
      }
    } catch (Exception e) {
      out.println("Unset failed. Details:");
      String reason = e.getMessage();
      out.println(reason == null ? "<unknown>: " + e.toString() : reason);
    }
  }
  /**
   * Implements the <tt>ListCellRenderer</tt> method. Returns this panel that has been configured to
   * display bundle name, version and description.
   *
   * @param table the parent table
   * @param value the value of the rendered cell
   * @param isSelected indicates if the rendered cell is selected
   * @param hasFocus indicates if the rendered cell has the focus
   * @param rowIndex the row index of the rendered cell
   * @param vColIndex the column index of the rendered cell
   * @return the rendering component
   */
  public Component getTableCellRendererComponent(
      JTable table,
      Object value,
      boolean isSelected,
      boolean hasFocus,
      int rowIndex,
      int vColIndex) {
    Bundle bundle = (Bundle) value;

    Dictionary<?, ?> headers = bundle.getHeaders();
    Object bundleName = headers.get(Constants.BUNDLE_NAME);
    Object bundleVersion = headers.get(Constants.BUNDLE_VERSION);
    Object bundleDescription = headers.get(Constants.BUNDLE_DESCRIPTION);

    Icon stateIcon = getStateIcon(bundle.getState());

    if (bundleName != null) this.nameLabel.setText(bundleName.toString());
    else this.nameLabel.setText("unknown");

    if (bundleVersion != null) this.versionLabel.setText(bundleVersion.toString());
    else this.versionLabel.setText("");

    if (bundleDescription != null) this.descriptionLabel.setText(bundleDescription.toString());
    else this.descriptionLabel.setText("");

    if (stateIcon != null) this.stateLabel.setIcon(stateIcon);

    this.nameVersionPanel.remove(systemLabel);

    if (PluginManagerActivator.isSystemBundle(bundle)) this.nameVersionPanel.add(systemLabel);

    this.isSelected = isSelected;

    return this;
  }