@Test
  public void testAddsApplicationConfigurationsOnStart() {
    BundleContext context = mock(BundleContext.class);
    ServiceContainer container = new ServiceContainer(context);
    ServiceReference reference = mock(ServiceReference.class);
    ApplicationConfiguration appConfig = mock(ApplicationConfiguration.class);
    Map<String, Object> map = new HashMap<>();
    map.put("foo", "bar");
    when(appConfig.getProperties()).thenReturn(map);
    Set<Object> set = new HashSet<Object>();
    set.add("test");
    when(appConfig.getSingletons()).thenReturn(set);
    when(context.getService(reference)).thenReturn(appConfig);
    container.add(reference);
    Configuration configuration = createConfiguration("/test", false, 23L);
    ServletConfiguration servletConfigurationService = mock(ServletConfiguration.class);

    JerseyContext jerseyContext =
        new JerseyContext(httpService, configuration, servletConfigurationService, container);

    Map<String, Object> properties = jerseyContext.getRootApplication().getProperties();
    assertEquals(properties.get("foo"), "bar");
    Set<Object> singletons = jerseyContext.getRootApplication().getSingletons();
    assertEquals(singletons.contains("test"), true);
  }
  /** Test of compare method, of class ServiceConnectionComparator. */
  @Test
  public void testCompare() {

    ServiceContainer container1 = mock(ServiceContainer.class);
    ServiceContainer container2 = mock(ServiceContainer.class);
    when(container1.id()).thenReturn(new UUID(0, 1));
    when(container2.id()).thenReturn(new UUID(0, 2));

    ServiceConnection[] conn = {
      createConnection(container1, 3),
      createConnection(container1, 2),
      createConnection(container1, 1),
      createConnection(container2, 3),
      createConnection(container2, 2),
      createConnection(container2, 1),
    };

    ServiceConnectionComparator instance = new ServiceConnectionComparator();
    for (int i = 0; i < conn.length; i++) {
      ServiceConnection x = conn[i];
      for (int j = 0; j < conn.length; j++) {
        ServiceConnection y = conn[j];
        int actual = instance.compare(x, y);
        if (i == j) {
          assertThat(actual, is(0));
        } else if (i < j) {
          assertThat(actual, is(lessThan(0)));
        } else {
          assertThat(actual, is(greaterThan(0)));
        }
      }
    }
  }
  @Test
  public void testUpdateAppConfiguration() {
    BundleContext context = mock(BundleContext.class);
    ServiceContainer container = new ServiceContainer(context);
    ServiceReference reference = mock(ServiceReference.class);
    ApplicationConfiguration appConfig = mock(ApplicationConfiguration.class);
    Map<String, Object> map = new HashMap<>();
    map.put("foo", "bar");
    when(appConfig.getProperties()).thenReturn(map);
    when(context.getService(reference)).thenReturn(appConfig);
    container.add(reference);

    jerseyContext.updateAppConfiguration(container);

    verify(rootApplication).addProperties(map);
  }
  /**
   * Checks whether Jenkins is enabled
   *
   * @return true if jenkins is enabled, else return false
   */
  private boolean isJenkinsEnabled() {

    String[] definedCIDriverNames =
        ServiceContainer.getAppFactoryConfiguration()
            .getProperties(JenkinsCIConstants.CONTINUOUS_INTEGRATION_PROVIDER_CONFIG_SELECTOR);
    boolean defined = false;
    for (String driverName : definedCIDriverNames) {
      if ("jenkins".equalsIgnoreCase(driverName)) {
        defined = true;
        break;
      }
    }
    return defined;
  }
 private static void assertState(
     final ServiceContainer serviceContainer,
     final ServiceName serviceName,
     final ServiceController.State state) {
   assertEquals(state, serviceContainer.getService(serviceName).getState());
 }
  @SuppressWarnings("UnusedDeclaration")
  protected void activate(ComponentContext context) {

    if (log.isDebugEnabled()) {
      log.debug("Jenkins build service bundle is activated");
    }
    try {

      if (isJenkinsEnabled()) {

        String authenticate =
            ServiceContainer.getAppFactoryConfiguration()
                .getFirstProperty(JenkinsCIConstants.AUTHENTICATE_CONFIG_SELECTOR);

        String userName =
            ServiceContainer.getAppFactoryConfiguration()
                .getFirstProperty(AppFactoryConstants.SERVER_ADMIN_NAME);

        String password =
            ServiceContainer.getAppFactoryConfiguration()
                .getFirstProperty(AppFactoryConstants.SERVER_ADMIN_PASSWORD);

        String jenkinsUrl =
            ServiceContainer.getAppFactoryConfiguration()
                .getFirstProperty(JenkinsCIConstants.BASE_URL_CONFIG_SELECTOR);

        String jenkinsDefaultGlobalRoles =
            ServiceContainer.getAppFactoryConfiguration()
                .getFirstProperty(JenkinsCIConstants.DEFAULT_GLOBAL_ROLES_CONFIG_SELECTOR);

        String listenerPriority =
            ServiceContainer.getAppFactoryConfiguration()
                .getFirstProperty(JenkinsCIConstants.LISTENER_PRIORITY_CONFIG_SELECTOR);

        if (log.isDebugEnabled()) {
          log.debug(String.format("Authenticate : %s", authenticate));
          log.debug(String.format("Jenkins user name : %s", userName));
          log.debug(String.format("Jenkins api key : %s", password));
          log.debug(String.format("Jenkins url : %s", jenkinsUrl));
          log.debug(String.format("Default Global Roles : %s", jenkinsDefaultGlobalRoles));
          log.debug(String.format("Listener Priority : %s", listenerPriority));
        }

        RestBasedJenkinsCIConnector connector =
            new RestBasedJenkinsCIConnector(
                jenkinsUrl, Boolean.parseBoolean(authenticate), userName, password);
        String[] globalRoles = jenkinsDefaultGlobalRoles.split(",");
        if (globalRoles == null) {
          globalRoles = new String[] {};
        }

        @SuppressWarnings("UnusedAssignment")
        int jenkinsListnerPriority = -1;
        try {
          jenkinsListnerPriority = Integer.parseInt(listenerPriority);
        } catch (NumberFormatException nef) {
          throw new IllegalArgumentException(
              "Invalid priority specified for jenkins "
                  + "application event listener. Please "
                  + "provide a number",
              nef);
        }

        JenkinsCISystemDriver jenkinsCISystemDriver =
            new JenkinsCISystemDriver(connector, globalRoles);
        ServiceContainer.setJenkinsCISystemDriver(jenkinsCISystemDriver);
        BundleContext bundleContext = context.getBundleContext();
        // Note: register the service only if its enabled in the
        // appfactory
        // configuration file.
        bundleContext.registerService(
            ContinuousIntegrationSystemDriver.class.getName(), jenkinsCISystemDriver, null);

        // Registering the Jenkins application event listener.
        bundleContext.registerService(
            ApplicationEventsListener.class.getName(),
            new JenkinsApplicationEventsListener(jenkinsListnerPriority),
            null);

        JenkinsStorage jenkinsStorage = new JenkinsStorage(connector);
        bundleContext.registerService(Storage.class.getName(), jenkinsStorage, null);
        bundleContext.registerService(
            TenantBuildManagerInitializer.class.getName(),
            new TenantBuildManagerInitializerImpl(),
            null);
      } else {
        log.info("Jenkins is not enabled");
      }

    } catch (Throwable e) {
      log.error("Error in registering Jenkins build service ", e);
    }
  }
 protected void unsetApplicationTypeManager(ApplicationTypeManager manager) {
   ServiceContainer.setApplicationTypeManager(null);
 }
 @SuppressWarnings("UnusedDeclaration")
 protected void unsetRepositoryManager(RepositoryManager repoManager) {
   ServiceContainer.setRepositoryManager(null);
 }
 @SuppressWarnings("UnusedDeclaration")
 protected void unsetAppFactoryConfiguration(AppFactoryConfiguration appFactoryConfiguration) {
   ServiceContainer.setAppFactoryConfiguration(null);
 }
  public boolean login(String loginName, String password) throws IOTException {

    HttpRequest request =
        new NoneAuthedHttpRequest(
            new HttpConfig.GetHttpConfig(), Constants.ServerAPIURI.GET_SESSION_ID);
    request.addParameter("dataType", "xml");
    ServiceContainer.getInstance()
        .getHttpHandler()
        .doRequest(
            request,
            new RequestListener<Session>() {

              @Override
              public void onRequestStart() {
                // TODO Auto-generated method stub

              }

              @Override
              public void onRequestGetControl(RequestControl control) {
                // TODO Auto-generated method stub

              }

              @Override
              public void onRequestCancelled() {
                // TODO Auto-generated method stub

              }

              @Override
              public void onRequestError(Exception e) {
                succeed = false;
                if (e instanceof IOTException) {
                  exception = (IOTException) e;
                } else {
                  exception = new IOTException(-1, e.getMessage());
                }
              }

              @Override
              public void onRequestResult(Session result) {
                // TODO Auto-generated method stub
                succeed = true;
                sessionID = result.getSessionID();
              }

              @Override
              public void onRequestComplete() {
                // TODO Auto-generated method stub
                synchronized (lock) {
                  lock.notify();
                }
              }
            });
    synchronized (lock) {
      try {
        lock.wait();
      } catch (InterruptedException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
      }

      IOTLog.d("LOGINService", sessionID == null ? "null" : sessionID);
    }

    if (!succeed && exception != null) throw exception;

    HttpRequest request2 =
        new NoneAuthedHttpRequest(new HttpConfig.GetHttpConfig(), Constants.ServerAPIURI.LOGIN);

    String mangledPwd = EncryptUtil.getStringMD5(password + ":" + sessionID);

    request2.addParameter("dataType", "json");
    request2.addParameter("__session_id", sessionID);
    request2.addParameter("username", loginName);
    request2.addParameter("mangled_password", mangledPwd);
    request2.addParameter("lang", "zh-cn");
    request2.addParameter("timezone", Integer.toString(TimeZone.getDefault().getRawOffset()));

    ServiceContainer.getInstance()
        .getHttpHandler()
        .doRequest(
            request2,
            new RequestListener<User>() {

              @Override
              public void onRequestStart() {
                // TODO Auto-generated method stub

              }

              @Override
              public void onRequestGetControl(RequestControl control) {
                // TODO Auto-generated method stub

              }

              @Override
              public void onRequestCancelled() {
                // TODO Auto-generated method stub

              }

              @Override
              public void onRequestError(Exception e) {
                succeed = false;
                if (e instanceof IOTException) {
                  exception = (IOTException) e;
                } else {
                  exception = new IOTException(-1, e.getMessage());
                }
              }

              @Override
              public void onRequestResult(User result) {
                // TODO Auto-generated method stub
                succeed = true;
                loginUser = result;
              }

              @Override
              public void onRequestComplete() {
                // TODO Auto-generated method stub
                synchronized (lock) {
                  lock.notify();
                }
              }
            });
    synchronized (lock) {
      try {
        lock.wait();
      } catch (InterruptedException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
      }

      IOTLog.d("LOGINService", loginUser == null ? "null" : loginUser.getUserID());
    }

    if (!succeed && exception != null) throw exception;

    if (succeed) {
      loginUser.setLoginName(loginName);
      loginUser.setPassword(password);
      ServiceContainer.getInstance().getSessionService().setSessionID(sessionID);
      ServiceContainer.getInstance().getSessionService().setLoginUser(loginUser);
    }

    return succeed;
  }
  public static IOTMonitorThreshold getBreachThreshold(Context context) {
    int co2LowerValue = Integer.MIN_VALUE;
    if (!""
        .equals(
            ServiceContainer.getInstance()
                .getPerferenceService()
                .getValue(Constants.PreferenceKey.BREACH_CO2_LOWERVALUE))) {
      co2LowerValue =
          Integer.parseInt(
              ServiceContainer.getInstance()
                  .getPerferenceService()
                  .getValue(Constants.PreferenceKey.BREACH_CO2_LOWERVALUE));
    } else {
      co2LowerValue = Integer.MIN_VALUE;
    }
    int co2UpperValue = Integer.MAX_VALUE;
    if (!""
        .equals(
            ServiceContainer.getInstance()
                .getPerferenceService()
                .getValue(Constants.PreferenceKey.BREACH_CO2_UPPERVALUE))) {
      co2UpperValue =
          Integer.parseInt(
              ServiceContainer.getInstance()
                  .getPerferenceService()
                  .getValue(Constants.PreferenceKey.BREACH_CO2_UPPERVALUE));
    } else {
      co2UpperValue = 1000;
    }

    int temperatureLowerValue = Integer.MIN_VALUE;
    if (!""
        .equals(
            ServiceContainer.getInstance()
                .getPerferenceService()
                .getValue(Constants.PreferenceKey.BREACH_TEMPERATURE_LOWERVALUE))) {
      temperatureLowerValue =
          Integer.parseInt(
              ServiceContainer.getInstance()
                  .getPerferenceService()
                  .getValue(Constants.PreferenceKey.BREACH_TEMPERATURE_LOWERVALUE));
    } else {
      temperatureLowerValue = 15;
    }
    int temperatureUpperValue = Integer.MAX_VALUE;
    if (!""
        .equals(
            ServiceContainer.getInstance()
                .getPerferenceService()
                .getValue(Constants.PreferenceKey.BREACH_TEMPERATURE_UPPERVALUE))) {
      temperatureUpperValue =
          Integer.parseInt(
              ServiceContainer.getInstance()
                  .getPerferenceService()
                  .getValue(Constants.PreferenceKey.BREACH_TEMPERATURE_UPPERVALUE));
    } else {
      temperatureUpperValue = 28;
    }

    int humidityLowerValue = Integer.MIN_VALUE;
    if (!""
        .equals(
            ServiceContainer.getInstance()
                .getPerferenceService()
                .getValue(Constants.PreferenceKey.BREACH_HUMIDITY_LOWERVALUE))) {
      humidityLowerValue =
          Integer.parseInt(
              ServiceContainer.getInstance()
                  .getPerferenceService()
                  .getValue(Constants.PreferenceKey.BREACH_HUMIDITY_LOWERVALUE));
    } else {
      humidityLowerValue = 0;
    }
    int humidityUpperValue = Integer.MAX_VALUE;
    if (!""
        .equals(
            ServiceContainer.getInstance()
                .getPerferenceService()
                .getValue(Constants.PreferenceKey.BREACH_HUMIDITY_UPPERVALUE))) {
      humidityUpperValue =
          Integer.parseInt(
              ServiceContainer.getInstance()
                  .getPerferenceService()
                  .getValue(Constants.PreferenceKey.BREACH_HUMIDITY_UPPERVALUE));
    } else {
      humidityUpperValue = 100;
    }

    return new IOTMonitorThreshold(
        co2LowerValue,
        co2UpperValue,
        temperatureLowerValue,
        temperatureUpperValue,
        humidityLowerValue,
        humidityUpperValue);
  }