@BeforeMethod(alwaysRun = true)
  public void setUp() throws Exception {
    List<String> propsToRemove =
        ImmutableList.of(
            "imageDescriptionRegex", "imageNameRegex", "inboundPorts", "hardwareId", "minRam");

    // Don't let any defaults from brooklyn.properties (except credentials) interfere with test
    brooklynProperties = BrooklynProperties.Factory.newDefault();
    for (String propToRemove : propsToRemove) {
      for (String propVariant :
          ImmutableList.of(
              propToRemove, CaseFormat.LOWER_CAMEL.to(CaseFormat.LOWER_HYPHEN, propToRemove))) {
        brooklynProperties.remove("brooklyn.locations.jclouds." + PROVIDER + "." + propVariant);
        brooklynProperties.remove("brooklyn.locations." + propVariant);
        brooklynProperties.remove("brooklyn.jclouds." + PROVIDER + "." + propVariant);
        brooklynProperties.remove("brooklyn.jclouds." + propVariant);
      }
    }

    // Also removes scriptHeader (e.g. if doing `. ~/.bashrc` and `. ~/.profile`, then that can
    // cause "stdin: is not a tty")
    brooklynProperties.remove("brooklyn.ssh.config.scriptHeader");

    ctx = new LocalManagementContext(brooklynProperties);
    app = ApplicationBuilder.newManagedApp(TestApplication.class, ctx);
  }
 @Test
 public void testAddUsageListenerViaProperties() throws Exception {
   BrooklynProperties brooklynProperties = BrooklynProperties.Factory.newEmpty();
   brooklynProperties.put(
       UsageManager.USAGE_LISTENERS, RecordingStaticUsageListener.class.getName());
   mgmt = LocalManagementContextForTests.newInstance(brooklynProperties);
   assertUsageListenerCalledWhenApplicationStarted();
 }
  /**
   * checks the supplied candidate user and password against the expect password (or SHA-256 + SALT
   * thereof) defined as brooklyn properties.
   */
  public static boolean checkExplicitUserPassword(
      ManagementContext mgmt, String user, String password) {
    BrooklynProperties properties = (BrooklynProperties) mgmt.getConfig();
    String expectedPassword = properties.getConfig(BrooklynWebConfig.PASSWORD_FOR_USER(user));
    String salt = properties.getConfig(BrooklynWebConfig.SALT_FOR_USER(user));
    String expectedSha256 = properties.getConfig(BrooklynWebConfig.SHA256_FOR_USER(user));

    return checkPassword(password, expectedPassword, expectedSha256, salt);
  }
  @Override
  protected LocalManagementContext newTestManagementContext() {
    ResourceUtils ru = new ResourceUtils(this);
    File jar = createJar(ru);
    File catalog = createCatalog(ru, jar);

    BrooklynProperties properties = BrooklynProperties.Factory.newEmpty();
    properties.put(BrooklynServerConfig.BROOKLYN_CATALOG_URL, catalog.toURI().toString());
    return LocalManagementContextForTests.builder(true)
        .useProperties(properties)
        .disableOsgi(false)
        .build();
  }
 @Override
 protected LocalManagementContext createNewManagementContext(
     File mementoDir, HighAvailabilityMode haMode) {
   BrooklynProperties properties = BrooklynProperties.Factory.newDefault();
   properties.put(
       BrooklynServerConfig.BROOKLYN_CATALOG_URL,
       "classpath://brooklyn/entity/rebind/rebind-catalog-item-test-catalog.xml");
   return RebindTestUtils.managementContextBuilder(mementoDir, classLoader)
       .properties(properties)
       .forLive(useLiveManagementContext())
       .haMode(haMode)
       .emptyCatalog(useEmptyCatalog())
       .buildUnstarted();
 }
 @Override
 protected LocalManagementContext createOrigManagementContext() {
   BrooklynProperties properties = BrooklynProperties.Factory.newDefault();
   properties.put(
       BrooklynServerConfig.BROOKLYN_CATALOG_URL,
       "classpath://brooklyn/entity/rebind/rebind-catalog-item-test-catalog.xml");
   properties.put(
       BrooklynServerConfig.CATALOG_LOAD_MODE,
       org.apache.brooklyn.core.catalog.CatalogLoadMode.LOAD_BROOKLYN_CATALOG_URL);
   return RebindTestUtils.managementContextBuilder(mementoDir, classLoader)
       .properties(properties)
       .persistPeriodMillis(getPersistPeriodMillis())
       .forLive(useLiveManagementContext())
       .buildStarted();
 }
 @Override
 public Map<String, Object> asMapWithStringKeys() {
   Map<ConfigKey<?>, Object> raw = delegate.getAllConfig();
   Map<String, Object> result = Maps.newLinkedHashMap();
   for (Map.Entry<ConfigKey<?>, Object> entry : raw.entrySet()) {
     result.put(entry.getKey().getName(), transform(entry.getKey(), entry.getValue()));
   }
   return result;
 }
 private static void addPropertiesFromMapSupplier(
     BrooklynProperties p, Supplier<Map<?, ?>> propertiesSupplier) {
   if (propertiesSupplier != null) {
     Map<?, ?> newProps = propertiesSupplier.get();
     if (newProps != null) {
       p.addFrom(newProps);
     }
   }
 }
    private static void addPropertiesFromFile(BrooklynProperties p, String file) {
      if (file == null) return;

      String fileTidied = Os.tidyPath(file);
      File f = new File(fileTidied);

      if (f.exists()) {
        p.addFrom(f);
      }
    }
    public LocalManagementContext buildUnstarted() {
      LocalManagementContext unstarted;
      BrooklynProperties properties =
          this.properties != null ? this.properties : BrooklynProperties.Factory.newDefault();
      if (this.emptyCatalog) {
        properties.putIfAbsent(
            BrooklynServerConfig.BROOKLYN_CATALOG_URL, ManagementContextInternal.EMPTY_CATALOG_URL);
      }
      if (!enablePersistenceBackups) {
        properties.putIfAbsent(
            BrooklynServerConfig.PERSISTENCE_BACKUPS_REQUIRED_ON_DEMOTION, false);
        properties.putIfAbsent(
            BrooklynServerConfig.PERSISTENCE_BACKUPS_REQUIRED_ON_PROMOTION, false);
        properties.putIfAbsent(BrooklynServerConfig.PERSISTENCE_BACKUPS_REQUIRED, false);
      }
      if (forLive) {
        unstarted = new LocalManagementContext(properties);
      } else {
        unstarted =
            LocalManagementContextForTests.builder(true)
                .useProperties(properties)
                .disableOsgi(!enableOsgi)
                .build();
      }

      objectStore.injectManagementContext(unstarted);
      objectStore.prepareForSharedUse(
          PersistMode.AUTO, (haMode == null ? HighAvailabilityMode.DISABLED : haMode));
      BrooklynMementoPersisterToObjectStore newPersister =
          new BrooklynMementoPersisterToObjectStore(
              objectStore, unstarted.getBrooklynProperties(), classLoader);
      ((RebindManagerImpl) unstarted.getRebindManager()).setPeriodicPersistPeriod(persistPeriod);
      unstarted
          .getRebindManager()
          .setPersister(newPersister, PersistenceExceptionHandlerImpl.builder().build());
      // set the HA persister, in case any children want to use HA
      unstarted
          .getHighAvailabilityManager()
          .setPersister(
              new ManagementPlaneSyncRecordPersisterToObjectStore(
                  unstarted, objectStore, classLoader));
      return unstarted;
    }
    private static void addPropertiesFromUrl(
        BrooklynProperties p, String url, boolean warnIfNotFound) {
      if (url == null) return;

      try {
        p.addFrom(ResourceUtils.create(BrooklynProperties.class).getResourceFromUrl(url));
      } catch (Exception e) {
        if (warnIfNotFound) LOG.warn("Could not load {}; continuing", url);
        if (LOG.isTraceEnabled()) LOG.trace("Could not load " + url + "; continuing", e);
      }
    }
  protected static void stripBrooklynProperties(BrooklynProperties props) {
    // remove all location properties except for identity and credential
    // (so key, scripts, etc settings don't interfere with tests)
    for (String key : ImmutableSet.copyOf(props.asMapWithStringKeys().keySet())) {
      if (key.startsWith(BROOKLYN_PROPERTIES_PREFIX)
          && !(key.endsWith("identity") || key.endsWith("credential"))) {
        props.remove(key);
      }
      if (key.startsWith(BROOKLYN_PROPERTIES_LEGACY_PREFIX)
          && !(key.endsWith("identity") || key.endsWith("credential"))) {
        props.remove(key);
      }

      // Also removes scriptHeader (e.g. if doing `. ~/.bashrc` and `. ~/.profile`, then that can
      // cause "stdin: is not a tty")
      if (key.startsWith("brooklyn.ssh")) {
        props.remove(key);
      }
    }
  }
      public BrooklynProperties build() {
        if (originalProperties != null)
          return new BrooklynPropertiesImpl().addFromMap(originalProperties);

        BrooklynProperties properties = new BrooklynPropertiesImpl();

        // TODO Could also read from http://brooklyn.io, for up-to-date values?
        // But might that make unit tests run very badly when developer is offline?
        addPropertiesFromUrl(properties, defaultLocationMetadataUrl, false);

        addPropertiesFromMapSupplier(properties, propertiesSupplier);
        addPropertiesFromFile(properties, globalLocationMetadataFile);
        addPropertiesFromFile(properties, globalPropertiesFile);
        addPropertiesFromFile(properties, localPropertiesFile);

        properties.addEnvironmentVars();
        properties.addSystemProperties();

        return properties;
      }
 @Override
 public boolean equals(Object o) {
   return delegate.equals(o);
 }
 @Override
 public Object put(Object key, Object value) {
   return delegate.put(key, value);
 }
 @Override
 @SuppressWarnings("rawtypes")
 public void putAll(Map vals) {
   delegate.putAll(vals);
 }
 @Test(expectedExceptions = ClassCastException.class)
 public void testErrorWhenConfiguredClassIsNotAUsageListener() {
   BrooklynProperties brooklynProperties = BrooklynProperties.Factory.newEmpty();
   brooklynProperties.put(UsageManager.USAGE_LISTENERS, Integer.class.getName());
   mgmt = LocalManagementContextForTests.newInstance(brooklynProperties);
 }
 @Override
 public <T> Object put(ConfigKey<T> key, T value) {
   return delegate.put(key, value);
 }
 @Override
 public boolean containsKey(Object key) {
   return delegate.containsKey(key);
 }
 @Override
 public boolean containsValue(Object value) {
   return delegate.containsValue(value);
 }
 @Override
 @SuppressWarnings({"unchecked", "rawtypes"})
 public Set<Map.Entry> entrySet() {
   return delegate.entrySet();
 }
 @Override
 public int size() {
   return delegate.size();
 }
 @Override
 @SuppressWarnings("rawtypes")
 public Set keySet() {
   return delegate.keySet();
 }
 @Override
 public void clear() {
   delegate.clear();
 }
 @Override
 public Object remove(Object key) {
   return delegate.remove(key);
 }
 @Override
 public Object get(Object key) {
   return delegate.get(key);
 }
 @Override
 public int hashCode() {
   return delegate.hashCode();
 }
 @Override
 public <T> boolean putIfAbsent(ConfigKey<T> key, T value) {
   return delegate.putIfAbsent(key, value);
 }
 @Override
 @SuppressWarnings("rawtypes")
 public Collection values() {
   return delegate.values();
 }
 @Override
 public boolean isEmpty() {
   return delegate.isEmpty();
 }