/**
  * Dumps out the persisted mementos that are at the given directory.
  *
  * <p>Binds to the persisted state (as a "hot standby") to load the raw data (as strings), and to
  * write out the entity, location, policy, enricher, feed and catalog-item data.
  *
  * @param dir The directory containing the persisted state
  */
 public static void dumpMementoDir(File dir) {
   LocalManagementContextForTests mgmt =
       new LocalManagementContextForTests(BrooklynProperties.Factory.newEmpty());
   FileBasedObjectStore store = null;
   BrooklynMementoPersisterToObjectStore persister = null;
   try {
     store = new FileBasedObjectStore(dir);
     store.injectManagementContext(mgmt);
     store.prepareForSharedUse(PersistMode.AUTO, HighAvailabilityMode.HOT_STANDBY);
     persister =
         new BrooklynMementoPersisterToObjectStore(
             store, BrooklynProperties.Factory.newEmpty(), RebindTestUtils.class.getClassLoader());
     BrooklynMementoRawData data =
         persister.loadMementoRawData(RebindExceptionHandlerImpl.builder().build());
     List<BrooklynObjectType> types =
         ImmutableList.of(
             BrooklynObjectType.ENTITY,
             BrooklynObjectType.LOCATION,
             BrooklynObjectType.POLICY,
             BrooklynObjectType.ENRICHER,
             BrooklynObjectType.FEED,
             BrooklynObjectType.CATALOG_ITEM);
     for (BrooklynObjectType type : types) {
       LOG.info(type + " (" + data.getObjectsOfType(type).keySet() + "):");
       for (Map.Entry<String, String> entry : data.getObjectsOfType(type).entrySet()) {
         LOG.info("\t" + type + " " + entry.getKey() + ": " + entry.getValue());
       }
     }
   } finally {
     if (persister != null) persister.stop(false);
     if (store != null) store.close();
     mgmt.terminate();
   }
 }
  @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();
 }
  @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();
 }
    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;
    }
  public static Collection<Application> rebindAll(RebindOptions options) throws Exception {
    File mementoDir = options.mementoDir;
    File mementoDirBackup = options.mementoDirBackup;
    ClassLoader classLoader = checkNotNull(options.classLoader, "classLoader");
    ManagementContextInternal origManagementContext =
        (ManagementContextInternal) options.origManagementContext;
    ManagementContextInternal newManagementContext =
        (ManagementContextInternal) options.newManagementContext;
    PersistenceObjectStore objectStore = options.objectStore;
    HighAvailabilityMode haMode =
        (options.haMode == null ? HighAvailabilityMode.DISABLED : options.haMode);
    RebindExceptionHandler exceptionHandler = options.exceptionHandler;
    boolean hasPersister =
        newManagementContext != null
            && newManagementContext.getRebindManager().getPersister() != null;
    boolean checkSerializable = options.checkSerializable;
    boolean terminateOrigManagementContext = options.terminateOrigManagementContext;
    Function<BrooklynMementoPersister, Void> stateTransformer = options.stateTransformer;

    LOG.info("Rebinding app, using mementoDir " + mementoDir + "; object store " + objectStore);

    if (newManagementContext == null) {
      // TODO Could use empty properties, to save reading brooklyn.properties file.
      // Would that affect any tests?
      newManagementContext =
          new LocalManagementContextForTests(BrooklynProperties.Factory.newDefault());
    }
    if (!hasPersister) {
      if (objectStore == null) {
        objectStore =
            new FileBasedObjectStore(
                checkNotNull(mementoDir, "mementoDir and objectStore must not both be null"));
      }
      objectStore.injectManagementContext(newManagementContext);
      objectStore.prepareForSharedUse(PersistMode.AUTO, haMode);

      BrooklynMementoPersisterToObjectStore newPersister =
          new BrooklynMementoPersisterToObjectStore(
              objectStore, newManagementContext.getBrooklynProperties(), classLoader);
      newManagementContext
          .getRebindManager()
          .setPersister(newPersister, PersistenceExceptionHandlerImpl.builder().build());
    } else {
      if (objectStore != null)
        throw new IllegalStateException(
            "Must not supply ManagementContext with persister and an object store");
    }

    if (checkSerializable) {
      checkNotNull(
          origManagementContext, "must supply origManagementContext with checkSerializable");
      RebindTestUtils.checkCurrentMementoSerializable(origManagementContext);
    }

    if (terminateOrigManagementContext) {
      checkNotNull(
          origManagementContext,
          "must supply origManagementContext with terminateOrigManagementContext");
      origManagementContext.terminate();
    }

    if (mementoDirBackup != null) {
      FileUtil.copyDir(mementoDir, mementoDirBackup);
      FileUtil.setFilePermissionsTo700(mementoDirBackup);
    }

    if (stateTransformer != null) {
      BrooklynMementoPersister persister = newManagementContext.getRebindManager().getPersister();
      stateTransformer.apply(persister);
    }

    List<Application> newApps =
        newManagementContext
            .getRebindManager()
            .rebind(
                classLoader,
                exceptionHandler,
                (haMode == HighAvailabilityMode.DISABLED)
                    ? ManagementNodeState.MASTER
                    : ManagementNodeState.of(haMode).get());
    newManagementContext.getRebindManager().startPersistence();
    return newApps;
  }
 @Test(expectedExceptions = ClassCastException.class)
 public void testErrorWhenConfiguredClassIsNotAUsageListener() {
   BrooklynProperties brooklynProperties = BrooklynProperties.Factory.newEmpty();
   brooklynProperties.put(UsageManager.USAGE_LISTENERS, Integer.class.getName());
   mgmt = LocalManagementContextForTests.newInstance(brooklynProperties);
 }