You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@brooklyn.apache.org by ri...@apache.org on 2014/05/23 18:56:46 UTC

[01/50] [abbrv] git commit: Updated following PR comments

Repository: incubator-brooklyn
Updated Branches:
  refs/heads/master 48a34e414 -> 48df48a96
  refs/pull/1385/merge [deleted] b416d758f
  refs/pull/1398/merge [deleted] 39da966b5
  refs/pull/1405/merge 7391ca902 -> 9f2ef4168 (forced update)
  refs/pull/1407/merge [deleted] fff36f548
  refs/pull/1408/merge 90ae7e62e -> df8e1a0b2 (forced update)
  refs/pull/1410/merge 167be7a78 -> 8179824f7 (forced update)
  refs/pull/1411/merge d8b897d5c -> 7e08b8937 (forced update)
  refs/pull/1413/head [created] 80532a5bc
  refs/pull/1413/merge [created] 46aeda224
  refs/pull/1414/head [created] 99b9e19bf
  refs/pull/1414/merge [created] 3114bfa88


Updated following PR comments


Project: http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/commit/238780f2
Tree: http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/tree/238780f2
Diff: http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/diff/238780f2

Branch: refs/pull/1410/merge
Commit: 238780f2f37250c0eb7458853c59af74d05867a4
Parents: f53e8f0
Author: Martin Harris <gi...@nakomis.com>
Authored: Thu May 15 13:07:37 2014 +0100
Committer: Martin Harris <gi...@nakomis.com>
Committed: Thu May 15 13:07:37 2014 +0100

----------------------------------------------------------------------
 .../entity/group/AbstractMembershipTrackingPolicy.java   | 11 +++++++----
 1 file changed, 7 insertions(+), 4 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/238780f2/core/src/main/java/brooklyn/entity/group/AbstractMembershipTrackingPolicy.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/brooklyn/entity/group/AbstractMembershipTrackingPolicy.java b/core/src/main/java/brooklyn/entity/group/AbstractMembershipTrackingPolicy.java
index b2582ce..99fd2b5 100644
--- a/core/src/main/java/brooklyn/entity/group/AbstractMembershipTrackingPolicy.java
+++ b/core/src/main/java/brooklyn/entity/group/AbstractMembershipTrackingPolicy.java
@@ -3,6 +3,7 @@ package brooklyn.entity.group;
 import java.util.Map;
 import java.util.Set;
 import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.ConcurrentMap;
 
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
@@ -32,7 +33,7 @@ public abstract class AbstractMembershipTrackingPolicy extends AbstractPolicy {
     
     private Group group;
     
-    private Map<String,Map<Sensor<Object>, Object>> entitySensorCache = new ConcurrentHashMap<String, Map<Sensor<Object>, Object>>();
+    private ConcurrentMap<String,Map<Sensor<Object>, Object>> entitySensorCache = new ConcurrentHashMap<String, Map<Sensor<Object>, Object>>();
     
     @SuppressWarnings("serial")
     public static final ConfigKey<Set<Sensor<?>>> SENSORS_TO_TRACK = ConfigKeys.newConfigKey(
@@ -125,10 +126,12 @@ public abstract class AbstractMembershipTrackingPolicy extends AbstractPolicy {
                     }
                     
                     String entityId = event.getSource().getId();
-                    Map<Sensor<Object>, Object> sensorCache = entitySensorCache.get(entityId);
+
+                    Map<Sensor<Object>, Object> newMap = MutableMap.<Sensor<Object>, Object>of();
+                    // NOTE: putIfAbsent returns null if the key is not present, or the *previous* value if present
+                    Map<Sensor<Object>, Object> sensorCache = entitySensorCache.putIfAbsent(entityId, newMap);
                     if (sensorCache == null) {
-                        sensorCache = MutableMap.<Sensor<Object>, Object>of();
-                        entitySensorCache.put(entityId, sensorCache);
+                        sensorCache = newMap;
                     }
                     
                     if (!notifyOnDuplicates && Objects.equal(event.getValue(), sensorCache.put(event.getSensor(), event.getValue()))) {


[13/50] [abbrv] git commit: Updated following PR review

Posted by ri...@apache.org.
Updated following PR review


Project: http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/commit/6f338897
Tree: http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/tree/6f338897
Diff: http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/diff/6f338897

Branch: refs/pull/1405/merge
Commit: 6f338897b704b1db1b88ec5cd9c1522e39ba2f08
Parents: 238780f
Author: Martin Harris <gi...@nakomis.com>
Authored: Thu May 22 10:47:42 2014 +0100
Committer: Martin Harris <gi...@nakomis.com>
Committed: Thu May 22 10:47:42 2014 +0100

----------------------------------------------------------------------
 .../brooklyn/entity/group/AbstractMembershipTrackingPolicy.java | 5 ++---
 .../src/main/java/brooklyn/util/collections/MutableSet.java     | 3 ---
 2 files changed, 2 insertions(+), 6 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/6f338897/core/src/main/java/brooklyn/entity/group/AbstractMembershipTrackingPolicy.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/brooklyn/entity/group/AbstractMembershipTrackingPolicy.java b/core/src/main/java/brooklyn/entity/group/AbstractMembershipTrackingPolicy.java
index 99fd2b5..049d49c 100644
--- a/core/src/main/java/brooklyn/entity/group/AbstractMembershipTrackingPolicy.java
+++ b/core/src/main/java/brooklyn/entity/group/AbstractMembershipTrackingPolicy.java
@@ -20,7 +20,6 @@ import brooklyn.event.SensorEvent;
 import brooklyn.event.SensorEventListener;
 import brooklyn.policy.basic.AbstractPolicy;
 import brooklyn.util.collections.MutableMap;
-import brooklyn.util.collections.MutableSet;
 
 import com.google.common.base.Objects;
 import com.google.common.base.Preconditions;
@@ -55,10 +54,10 @@ public abstract class AbstractMembershipTrackingPolicy extends AbstractPolicy {
     }
 
     protected Set<Sensor<?>> getSensorsToTrack() {
-        return MutableSet.<Sensor<?>>builder()
+        return ImmutableSet.<Sensor<?>>builder()
                 .addAll(getRequiredConfig(SENSORS_TO_TRACK))
                 .add(Attributes.SERVICE_UP)
-                .buildImmutable();
+                .build();
     }
     
     /**

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/6f338897/utils/common/src/main/java/brooklyn/util/collections/MutableSet.java
----------------------------------------------------------------------
diff --git a/utils/common/src/main/java/brooklyn/util/collections/MutableSet.java b/utils/common/src/main/java/brooklyn/util/collections/MutableSet.java
index 6ab967a..f791949 100644
--- a/utils/common/src/main/java/brooklyn/util/collections/MutableSet.java
+++ b/utils/common/src/main/java/brooklyn/util/collections/MutableSet.java
@@ -111,9 +111,6 @@ public class MutableSet<V> extends LinkedHashSet<V> {
           return new MutableSet<V>(result);
         }
         
-        public ImmutableSet<V> buildImmutable() {
-            return ImmutableSet.copyOf(result);
-        }
     }
     
     public boolean addIfNotNull(V e) {


[40/50] [abbrv] git commit: Merge 972115a2479fbafd8c3f793094a3fd0b831b6665 into 1c9ae9245088e6904c4ed66ec1f592e2588e6f8e

Posted by ri...@apache.org.
Merge 972115a2479fbafd8c3f793094a3fd0b831b6665 into 1c9ae9245088e6904c4ed66ec1f592e2588e6f8e


Project: http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/commit/7e08b893
Tree: http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/tree/7e08b893
Diff: http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/diff/7e08b893

Branch: refs/pull/1411/merge
Commit: 7e08b8937f8055737bec14aaf21b478741b02e47
Parents: 1c9ae92 972115a
Author: Zaid <za...@cloudsoftcorp.com>
Authored: Fri May 23 16:20:51 2014 +0000
Committer: Zaid <za...@cloudsoftcorp.com>
Committed: Fri May 23 16:20:51 2014 +0000

----------------------------------------------------------------------
 .../java/brooklyn/demo/RiakClusterExample.java  | 33 ++++++---
 .../brooklyn/entity/nosql/riak/RiakCluster.java |  9 +++
 .../entity/nosql/riak/RiakClusterImpl.java      | 77 +++++++++++++++-----
 .../brooklyn/entity/nosql/riak/RiakNode.java    | 48 ++++++------
 .../entity/nosql/riak/RiakNodeDriver.java       |  2 +
 .../entity/nosql/riak/RiakNodeImpl.java         |  3 +
 .../entity/nosql/riak/RiakNodeSshDriver.java    | 59 +++++++++------
 .../nosql/riak/RiakClusterEc2LiveTest.java      |  7 +-
 .../riak/RiakNodeGoogleComputeLiveTest.java     |  7 +-
 9 files changed, 169 insertions(+), 76 deletions(-)
----------------------------------------------------------------------



[21/50] [abbrv] git commit: More enricher and policy persistance changes

Posted by ri...@apache.org.
More enricher and policy persistance changes


Project: http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/commit/80532a5b
Tree: http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/tree/80532a5b
Diff: http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/diff/80532a5b

Branch: refs/pull/1413/head
Commit: 80532a5bcea8334f1c012657448e302230d7247d
Parents: 34d4f8a
Author: Andrew Kennedy <an...@cloudsoftcorp.com>
Authored: Thu May 22 17:24:03 2014 +0100
Committer: Andrew Kennedy <an...@cloudsoftcorp.com>
Committed: Thu May 22 17:57:52 2014 +0100

----------------------------------------------------------------------
 .../brooklyn/entity/rebind/ChangeListener.java  |  4 ++
 .../brooklyn/entity/rebind/RebindContext.java   | 12 ++--
 .../mementos/BrooklynMementoPersister.java      |  4 ++
 api/src/main/java/brooklyn/policy/Enricher.java | 17 +++--
 .../enricher/basic/AbstractEnricher.java        |  8 +++
 .../rebind/BasicEnricherRebindSupport.java      | 28 ++++----
 .../entity/rebind/BasicEntityRebindSupport.java | 20 +++++-
 .../rebind/ImmediateDeltaChangeListener.java    | 10 +++
 .../rebind/PeriodicDeltaChangeListener.java     | 35 +++++++--
 .../entity/rebind/PersisterDeltaImpl.java       | 13 ++++
 .../entity/rebind/RebindContextImpl.java        | 11 +++
 .../entity/rebind/RebindManagerImpl.java        | 76 +++++++++++++++++++-
 .../entity/rebind/dto/BrooklynMementoImpl.java  | 25 +++++++
 .../rebind/dto/BrooklynMementoManifestImpl.java | 14 ++++
 .../AbstractBrooklynMementoPersister.java       |  6 ++
 .../BrooklynMementoPersisterInMemory.java       | 12 ++++
 .../BrooklynMementoPersisterToMultiFile.java    | 71 +++++++++++++++---
 .../rebind/persister/XmlMementoSerializer.java  | 31 +++++++-
 .../internal/EntityChangeListener.java          |  2 +-
 .../internal/EntityManagementSupport.java       |  2 +
 .../persister/XmlMementoSerializerTest.java     | 75 ++++++++++++-------
 21 files changed, 408 insertions(+), 68 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/80532a5b/api/src/main/java/brooklyn/entity/rebind/ChangeListener.java
----------------------------------------------------------------------
diff --git a/api/src/main/java/brooklyn/entity/rebind/ChangeListener.java b/api/src/main/java/brooklyn/entity/rebind/ChangeListener.java
index ffc15da..ee17ec8 100644
--- a/api/src/main/java/brooklyn/entity/rebind/ChangeListener.java
+++ b/api/src/main/java/brooklyn/entity/rebind/ChangeListener.java
@@ -2,6 +2,7 @@ package brooklyn.entity.rebind;
 
 import brooklyn.entity.Entity;
 import brooklyn.location.Location;
+import brooklyn.policy.Enricher;
 import brooklyn.policy.Policy;
 
 /**
@@ -22,6 +23,7 @@ public interface ChangeListener {
         @Override public void onUnmanaged(Location location) {}
         @Override public void onChanged(Location location) {}
         @Override public void onChanged(Policy policy) {}
+        @Override public void onChanged(Enricher enricher) {}
     };
     
     void onManaged(Entity entity);
@@ -37,4 +39,6 @@ public interface ChangeListener {
     void onChanged(Location location);
     
     void onChanged(Policy policy);
+    
+    void onChanged(Enricher enricher);
 }

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/80532a5b/api/src/main/java/brooklyn/entity/rebind/RebindContext.java
----------------------------------------------------------------------
diff --git a/api/src/main/java/brooklyn/entity/rebind/RebindContext.java b/api/src/main/java/brooklyn/entity/rebind/RebindContext.java
index 264b8b0..2d8e364 100644
--- a/api/src/main/java/brooklyn/entity/rebind/RebindContext.java
+++ b/api/src/main/java/brooklyn/entity/rebind/RebindContext.java
@@ -2,6 +2,7 @@ package brooklyn.entity.rebind;
 
 import brooklyn.entity.Entity;
 import brooklyn.location.Location;
+import brooklyn.policy.Enricher;
 import brooklyn.policy.Policy;
 
 /**
@@ -15,11 +16,14 @@ import brooklyn.policy.Policy;
  */
 public interface RebindContext {
 
-    public Entity getEntity(String id);
+    Entity getEntity(String id);
 
-    public Location getLocation(String id);
+    Location getLocation(String id);
 
-    public Policy getPolicy(String id);
+    Policy getPolicy(String id);
+
+    Enricher getEnricher(String id);
+
+    Class<?> loadClass(String typeName) throws ClassNotFoundException;
 
-    public Class<?> loadClass(String typeName) throws ClassNotFoundException;
 }

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/80532a5b/api/src/main/java/brooklyn/mementos/BrooklynMementoPersister.java
----------------------------------------------------------------------
diff --git a/api/src/main/java/brooklyn/mementos/BrooklynMementoPersister.java b/api/src/main/java/brooklyn/mementos/BrooklynMementoPersister.java
index e29e70e..18f9b14 100644
--- a/api/src/main/java/brooklyn/mementos/BrooklynMementoPersister.java
+++ b/api/src/main/java/brooklyn/mementos/BrooklynMementoPersister.java
@@ -8,6 +8,8 @@ import java.util.concurrent.TimeoutException;
 import brooklyn.entity.Entity;
 import brooklyn.entity.rebind.RebindManager;
 import brooklyn.location.Location;
+import brooklyn.policy.Enricher;
+import brooklyn.policy.Policy;
 import brooklyn.util.time.Duration;
 
 import com.google.common.annotations.VisibleForTesting;
@@ -21,6 +23,8 @@ public interface BrooklynMementoPersister {
     public static interface LookupContext {
         Entity lookupEntity(Class<?> type, String id);
         Location lookupLocation(Class<?> type, String id);
+        Policy lookupPolicy(Class<?> type, String id);
+        Enricher lookupEnricher(Class<?> type, String id);
     }
 
     BrooklynMementoManifest loadMementoManifest() throws IOException;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/80532a5b/api/src/main/java/brooklyn/policy/Enricher.java
----------------------------------------------------------------------
diff --git a/api/src/main/java/brooklyn/policy/Enricher.java b/api/src/main/java/brooklyn/policy/Enricher.java
index ab6b546..6be006d 100644
--- a/api/src/main/java/brooklyn/policy/Enricher.java
+++ b/api/src/main/java/brooklyn/policy/Enricher.java
@@ -3,16 +3,19 @@ package brooklyn.policy;
 import java.util.Map;
 
 import brooklyn.config.ConfigKey;
+import brooklyn.entity.rebind.RebindSupport;
+import brooklyn.entity.rebind.Rebindable;
+import brooklyn.mementos.EnricherMemento;
 
 import com.google.common.annotations.Beta;
 
 /**
  * Publishes metrics for an entity, e.g. aggregating information from other sensors/entities.
- * 
- * Has some similarities to {@link Policy}. However, enrichers specifically do not invoke 
+ *
+ * Has some similarities to {@link Policy}. However, enrichers specifically do not invoke
  * effectors and should only function to publish new metrics.
  */
-public interface Enricher extends EntityAdjunct {
+public interface Enricher extends EntityAdjunct, Rebindable {
     /**
      * A unique id for this enricher.
      */
@@ -32,8 +35,12 @@ public interface Enricher extends EntityAdjunct {
     EnricherType getEnricherType();
 
     <T> T getConfig(ConfigKey<T> key);
-    
+
     <T> T setConfig(ConfigKey<T> key, T val);
-    
+
     Map<ConfigKey<?>, Object> getAllConfig();
+
+    @Override
+    RebindSupport<EnricherMemento> getRebindSupport();
+
 }

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/80532a5b/core/src/main/java/brooklyn/enricher/basic/AbstractEnricher.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/brooklyn/enricher/basic/AbstractEnricher.java b/core/src/main/java/brooklyn/enricher/basic/AbstractEnricher.java
index a83b1fc..4346be5 100644
--- a/core/src/main/java/brooklyn/enricher/basic/AbstractEnricher.java
+++ b/core/src/main/java/brooklyn/enricher/basic/AbstractEnricher.java
@@ -2,6 +2,9 @@ package brooklyn.enricher.basic;
 
 import java.util.Map;
 
+import brooklyn.entity.rebind.BasicEnricherRebindSupport;
+import brooklyn.entity.rebind.RebindSupport;
+import brooklyn.mementos.EnricherMemento;
 import brooklyn.policy.Enricher;
 import brooklyn.policy.EnricherType;
 import brooklyn.policy.basic.AbstractEntityAdjunct;
@@ -28,6 +31,11 @@ public abstract class AbstractEnricher extends AbstractEntityAdjunct implements
             init();
         }
     }
+
+    @Override
+    public RebindSupport<EnricherMemento> getRebindSupport() {
+        return new BasicEnricherRebindSupport(this);
+    }
     
     @Override
     public EnricherType getEnricherType() {

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/80532a5b/core/src/main/java/brooklyn/entity/rebind/BasicEnricherRebindSupport.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/brooklyn/entity/rebind/BasicEnricherRebindSupport.java b/core/src/main/java/brooklyn/entity/rebind/BasicEnricherRebindSupport.java
index 9d3a50e..3fca1b8 100644
--- a/core/src/main/java/brooklyn/entity/rebind/BasicEnricherRebindSupport.java
+++ b/core/src/main/java/brooklyn/entity/rebind/BasicEnricherRebindSupport.java
@@ -7,36 +7,36 @@ import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
 import brooklyn.entity.rebind.dto.MementosGenerators;
-import brooklyn.mementos.PolicyMemento;
-import brooklyn.policy.basic.AbstractPolicy;
+import brooklyn.mementos.EnricherMemento;
+import brooklyn.enricher.basic.AbstractEnricher;
 
-public class BasicEnricherRebindSupport implements RebindSupport<PolicyMemento> {
+public class BasicEnricherRebindSupport implements RebindSupport<EnricherMemento> {
 
     private static final Logger LOG = LoggerFactory.getLogger(BasicEnricherRebindSupport.class);
     
-    private final AbstractPolicy policy;
+    private final AbstractEnricher enricher;
     
-    public BasicEnricherRebindSupport(AbstractPolicy policy) {
-        this.policy = policy;
+    public BasicEnricherRebindSupport(AbstractEnricher enricher) {
+        this.enricher = enricher;
     }
     
     @Override
-    public PolicyMemento getMemento() {
+    public EnricherMemento getMemento() {
         return getMementoWithProperties(Collections.<String,Object>emptyMap());
     }
 
-    protected PolicyMemento getMementoWithProperties(Map<String,?> props) {
-        PolicyMemento memento = MementosGenerators.newPolicyMementoBuilder(policy).customFields(props).build();
-        if (LOG.isTraceEnabled()) LOG.trace("Creating memento for policy: {}", memento.toVerboseString());
+    protected EnricherMemento getMementoWithProperties(Map<String,?> props) {
+        EnricherMemento memento = MementosGenerators.newEnricherMementoBuilder(enricher).customFields(props).build();
+        if (LOG.isTraceEnabled()) LOG.trace("Creating memento for enricher: {}", memento.toVerboseString());
         return memento;
     }
 
     @Override
-    public void reconstruct(RebindContext rebindContext, PolicyMemento memento) {
-        if (LOG.isTraceEnabled()) LOG.trace("Reconstructing policy: {}", memento.toVerboseString());
+    public void reconstruct(RebindContext rebindContext, EnricherMemento memento) {
+        if (LOG.isTraceEnabled()) LOG.trace("Reconstructing enricher: {}", memento.toVerboseString());
 
         // Note that the flags have been set in the constructor
-        policy.setName(memento.getDisplayName());
+        enricher.setName(memento.getDisplayName());
         
         doReconsruct(rebindContext, memento);
     }
@@ -44,7 +44,7 @@ public class BasicEnricherRebindSupport implements RebindSupport<PolicyMemento>
     /**
      * For overriding, to give custom reconsruct behaviour.
      */
-    protected void doReconsruct(RebindContext rebindContext, PolicyMemento memento) {
+    protected void doReconsruct(RebindContext rebindContext, EnricherMemento memento) {
         // default is no-op
     }
 }

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/80532a5b/core/src/main/java/brooklyn/entity/rebind/BasicEntityRebindSupport.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/brooklyn/entity/rebind/BasicEntityRebindSupport.java b/core/src/main/java/brooklyn/entity/rebind/BasicEntityRebindSupport.java
index 90df2f4..e19c2fa 100644
--- a/core/src/main/java/brooklyn/entity/rebind/BasicEntityRebindSupport.java
+++ b/core/src/main/java/brooklyn/entity/rebind/BasicEntityRebindSupport.java
@@ -9,6 +9,7 @@ import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
 import brooklyn.config.ConfigKey;
+import brooklyn.enricher.basic.AbstractEnricher;
 import brooklyn.entity.Effector;
 import brooklyn.entity.Entity;
 import brooklyn.entity.Group;
@@ -40,14 +41,14 @@ public class BasicEntityRebindSupport implements RebindSupport<EntityMemento> {
 
     protected EntityMemento getMementoWithProperties(Map<String,?> props) {
         EntityMemento memento = MementosGenerators.newEntityMementoBuilder(entity).customFields(props).build();
-    	if (LOG.isTraceEnabled()) LOG.trace("Creating memento for entity: {}", memento.toVerboseString());
-    	return memento;
+        if (LOG.isTraceEnabled()) LOG.trace("Creating memento for entity: {}", memento.toVerboseString());
+        return memento;
     }
 
     @SuppressWarnings("unchecked")
     @Override
     public void reconstruct(RebindContext rebindContext, EntityMemento memento) {
-    	if (LOG.isTraceEnabled()) LOG.trace("Reconstructing entity: {}", memento.toVerboseString());
+        if (LOG.isTraceEnabled()) LOG.trace("Reconstructing entity: {}", memento.toVerboseString());
 
         // Note that the id should have been set in the constructor; it is immutable
         entity.setDisplayName(memento.getDisplayName());
@@ -82,6 +83,7 @@ public class BasicEntityRebindSupport implements RebindSupport<EntityMemento> {
         setParent(rebindContext, memento);
         addChildren(rebindContext, memento);
         addPolicies(rebindContext, memento);
+        addEnrichers(rebindContext, memento);
         addMembers(rebindContext, memento);
         addLocations(rebindContext, memento);
 
@@ -158,4 +160,16 @@ public class BasicEntityRebindSupport implements RebindSupport<EntityMemento> {
             }
         }
     }
+    
+    protected void addEnrichers(RebindContext rebindContext, EntityMemento memento) {
+        for (String enricherId : memento.getEnrichers()) {
+            AbstractEnricher enricher = (AbstractEnricher) rebindContext.getEnricher(enricherId);
+            if (enricher != null) {
+                entity.addEnricher(enricher);
+            } else {
+                LOG.warn("Enricher not found; discarding policy {} of entity {}({})",
+                        new Object[] {enricherId, memento.getType(), memento.getId()});
+            }
+        }
+    }
 }

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/80532a5b/core/src/main/java/brooklyn/entity/rebind/ImmediateDeltaChangeListener.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/brooklyn/entity/rebind/ImmediateDeltaChangeListener.java b/core/src/main/java/brooklyn/entity/rebind/ImmediateDeltaChangeListener.java
index 077be32..a33bb12 100644
--- a/core/src/main/java/brooklyn/entity/rebind/ImmediateDeltaChangeListener.java
+++ b/core/src/main/java/brooklyn/entity/rebind/ImmediateDeltaChangeListener.java
@@ -9,6 +9,7 @@ import brooklyn.location.Location;
 import brooklyn.location.basic.LocationInternal;
 import brooklyn.mementos.BrooklynMementoPersister;
 import brooklyn.mementos.LocationMemento;
+import brooklyn.policy.Enricher;
 import brooklyn.policy.Policy;
 
 import com.google.common.collect.Maps;
@@ -126,4 +127,13 @@ public class ImmediateDeltaChangeListener implements ChangeListener {
             persister.delta(delta);
         }
     }
+    
+    @Override
+    public void onChanged(Enricher enricher) {
+        if (running && persister != null) {
+            PersisterDeltaImpl delta = new PersisterDeltaImpl();
+            delta.enrichers.add(enricher.getRebindSupport().getMemento());
+            persister.delta(delta);
+        }
+    }
 }

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/80532a5b/core/src/main/java/brooklyn/entity/rebind/PeriodicDeltaChangeListener.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/brooklyn/entity/rebind/PeriodicDeltaChangeListener.java b/core/src/main/java/brooklyn/entity/rebind/PeriodicDeltaChangeListener.java
index 1a7a8fc..d7cc8e6 100644
--- a/core/src/main/java/brooklyn/entity/rebind/PeriodicDeltaChangeListener.java
+++ b/core/src/main/java/brooklyn/entity/rebind/PeriodicDeltaChangeListener.java
@@ -16,6 +16,7 @@ import brooklyn.location.basic.LocationInternal;
 import brooklyn.management.ExecutionManager;
 import brooklyn.management.Task;
 import brooklyn.mementos.BrooklynMementoPersister;
+import brooklyn.policy.Enricher;
 import brooklyn.policy.Policy;
 import brooklyn.util.exceptions.Exceptions;
 import brooklyn.util.task.BasicTask;
@@ -47,13 +48,15 @@ public class PeriodicDeltaChangeListener implements ChangeListener {
         Set<Location> locations = Sets.newLinkedHashSet();
         Set<Entity> entities = Sets.newLinkedHashSet();
         Set<Policy> policies = Sets.newLinkedHashSet();
+        Set<Enricher> enrichers = Sets.newLinkedHashSet();
         Set<String> removedLocationIds = Sets.newLinkedHashSet();
         Set<String> removedEntityIds = Sets.newLinkedHashSet();
         Set<String> removedPolicyIds = Sets.newLinkedHashSet();
+        Set<String> removedEnricherIds = Sets.newLinkedHashSet();
         
         public boolean isEmpty() {
-            return locations.isEmpty() && entities.isEmpty() && policies.isEmpty() && 
-                    removedEntityIds.isEmpty() && removedLocationIds.isEmpty() && removedPolicyIds.isEmpty();
+            return locations.isEmpty() && entities.isEmpty() && policies.isEmpty() && enrichers.isEmpty() &&
+                    removedEntityIds.isEmpty() && removedLocationIds.isEmpty() && removedPolicyIds.isEmpty() && removedEnricherIds.isEmpty();
         }
     }
     
@@ -196,12 +199,20 @@ public class PeriodicDeltaChangeListener implements ChangeListener {
                         try {
                             persisterDelta.policies.add(policy.getRebindSupport().getMemento());
                         } catch (Exception e) {
-                            handleGenerateMementoException(e, "location "+policy.getClass().getSimpleName()+"("+policy.getId()+")");
+                            handleGenerateMementoException(e, "policy "+policy.getClass().getSimpleName()+"("+policy.getId()+")");
+                        }
+                    }
+                    for (Enricher enricher : prevDeltaCollector.enrichers) {
+                        try {
+                            persisterDelta.enrichers.add(enricher.getRebindSupport().getMemento());
+                        } catch (Exception e) {
+                            handleGenerateMementoException(e, "enricher "+enricher.getClass().getSimpleName()+"("+enricher.getId()+")");
                         }
                     }
                     persisterDelta.removedLocationIds = prevDeltaCollector.removedLocationIds;
                     persisterDelta.removedEntityIds = prevDeltaCollector.removedEntityIds;
                     persisterDelta.removedPolicyIds = prevDeltaCollector.removedPolicyIds;
+                    persisterDelta.removedEnricherIds = prevDeltaCollector.removedEnricherIds;
                     
                     /*
                      * Need to guarantee "happens before", with any thread that subsequently reads
@@ -268,9 +279,13 @@ public class PeriodicDeltaChangeListener implements ChangeListener {
             // (e.g. AbstractController registering a AbstractMembershipTrackingPolicy)
             // Also, the entity constructor often re-creates the policy.
             // Also see MementosGenerator.newEntityMementoBuilder()
-//            for (Policy policy : entity.getPolicies()) {
-//                delta.policies.add(policy);
-//            }
+            for (Policy policy : entity.getPolicies()) {
+                deltaCollector.policies.add(policy);
+            }
+
+            for (Enricher enricher : entity.getEnrichers()) {
+                deltaCollector.enrichers.add(enricher);
+            }
         }
     }
     
@@ -307,4 +322,12 @@ public class PeriodicDeltaChangeListener implements ChangeListener {
             deltaCollector.policies.add(policy);
         }
     }
+    
+    @Override
+    public synchronized void onChanged(Enricher enricher) {
+        if (LOG.isTraceEnabled()) LOG.trace("onChanged: {}", enricher);
+        if (!isStopped()) {
+            deltaCollector.enrichers.add(enricher);
+        }
+    }
 }

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/80532a5b/core/src/main/java/brooklyn/entity/rebind/PersisterDeltaImpl.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/brooklyn/entity/rebind/PersisterDeltaImpl.java b/core/src/main/java/brooklyn/entity/rebind/PersisterDeltaImpl.java
index b3a3d7f..0950f81 100644
--- a/core/src/main/java/brooklyn/entity/rebind/PersisterDeltaImpl.java
+++ b/core/src/main/java/brooklyn/entity/rebind/PersisterDeltaImpl.java
@@ -3,6 +3,7 @@ package brooklyn.entity.rebind;
 import java.util.Collection;
 
 import brooklyn.mementos.BrooklynMementoPersister.Delta;
+import brooklyn.mementos.EnricherMemento;
 import brooklyn.mementos.EntityMemento;
 import brooklyn.mementos.LocationMemento;
 import brooklyn.mementos.PolicyMemento;
@@ -13,9 +14,11 @@ class PersisterDeltaImpl implements Delta {
     Collection<LocationMemento> locations = Sets.newLinkedHashSet();
     Collection<EntityMemento> entities = Sets.newLinkedHashSet();
     Collection<PolicyMemento> policies = Sets.newLinkedHashSet();
+    Collection<EnricherMemento> enrichers = Sets.newLinkedHashSet();
     Collection <String> removedLocationIds = Sets.newLinkedHashSet();
     Collection <String> removedEntityIds = Sets.newLinkedHashSet();
     Collection <String> removedPolicyIds = Sets.newLinkedHashSet();
+    Collection <String> removedEnricherIds = Sets.newLinkedHashSet();
     
     @Override
     public Collection<LocationMemento> locations() {
@@ -33,6 +36,11 @@ class PersisterDeltaImpl implements Delta {
     }
 
     @Override
+    public Collection<EnricherMemento> enrichers() {
+        return enrichers;
+    }
+
+    @Override
     public Collection<String> removedLocationIds() {
         return removedLocationIds;
     }
@@ -46,4 +54,9 @@ class PersisterDeltaImpl implements Delta {
     public Collection<String> removedPolicyIds() {
         return removedPolicyIds;
     }
+    
+    @Override
+    public Collection<String> removedEnricherIds() {
+        return removedEnricherIds;
+    }
 }

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/80532a5b/core/src/main/java/brooklyn/entity/rebind/RebindContextImpl.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/brooklyn/entity/rebind/RebindContextImpl.java b/core/src/main/java/brooklyn/entity/rebind/RebindContextImpl.java
index 90a3bb4..30c88ab 100644
--- a/core/src/main/java/brooklyn/entity/rebind/RebindContextImpl.java
+++ b/core/src/main/java/brooklyn/entity/rebind/RebindContextImpl.java
@@ -4,6 +4,7 @@ import java.util.Map;
 
 import brooklyn.entity.Entity;
 import brooklyn.location.Location;
+import brooklyn.policy.Enricher;
 import brooklyn.policy.Policy;
 
 import com.google.common.collect.Maps;
@@ -13,6 +14,7 @@ public class RebindContextImpl implements RebindContext {
     private final Map<String, Entity> entities = Maps.newLinkedHashMap();
     private final Map<String, Location> locations = Maps.newLinkedHashMap();
     private final Map<String, Policy> policies = Maps.newLinkedHashMap();
+    private final Map<String, Enricher> enrichers = Maps.newLinkedHashMap();
     private final ClassLoader classLoader;
     
     public RebindContextImpl(ClassLoader classLoader) {
@@ -31,6 +33,10 @@ public class RebindContextImpl implements RebindContext {
         policies.put(id, policy);
     }
     
+    public void registerEnricher(String id, Enricher enricher) {
+        enrichers.put(id, enricher);
+    }
+    
     @Override
     public Entity getEntity(String id) {
         return entities.get(id);
@@ -47,6 +53,11 @@ public class RebindContextImpl implements RebindContext {
     }
     
     @Override
+    public Enricher getEnricher(String id) {
+        return enrichers.get(id);
+    }
+    
+    @Override
     public Class<?> loadClass(String className) throws ClassNotFoundException {
         return classLoader.loadClass(className);
     }

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/80532a5b/core/src/main/java/brooklyn/entity/rebind/RebindManagerImpl.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/brooklyn/entity/rebind/RebindManagerImpl.java b/core/src/main/java/brooklyn/entity/rebind/RebindManagerImpl.java
index 821a42d..4b0ce65 100644
--- a/core/src/main/java/brooklyn/entity/rebind/RebindManagerImpl.java
+++ b/core/src/main/java/brooklyn/entity/rebind/RebindManagerImpl.java
@@ -28,10 +28,12 @@ import brooklyn.mementos.BrooklynMemento;
 import brooklyn.mementos.BrooklynMementoManifest;
 import brooklyn.mementos.BrooklynMementoPersister;
 import brooklyn.mementos.BrooklynMementoPersister.LookupContext;
+import brooklyn.mementos.EnricherMemento;
 import brooklyn.mementos.EntityMemento;
 import brooklyn.mementos.LocationMemento;
 import brooklyn.mementos.PolicyMemento;
 import brooklyn.mementos.TreeNode;
+import brooklyn.policy.Enricher;
 import brooklyn.policy.Policy;
 import brooklyn.util.collections.MutableMap;
 import brooklyn.util.exceptions.Exceptions;
@@ -155,6 +157,7 @@ public class RebindManagerImpl implements RebindManager {
             Map<String,Entity> entities = Maps.newLinkedHashMap();
             Map<String,Location> locations = Maps.newLinkedHashMap();
             Map<String,Policy> policies = Maps.newLinkedHashMap();
+            Map<String,Enricher> enrichers = Maps.newLinkedHashMap();
             
             final RebindContextImpl rebindContext = new RebindContextImpl(classLoader);
     
@@ -186,6 +189,32 @@ public class RebindManagerImpl implements RebindManager {
                     }
                     return result;
                 }
+                @Override public Policy lookupPolicy(Class<?> type, String id) {
+                    Policy result = rebindContext.getPolicy(id);
+                    if (result == null) {
+                        if (removeDanglingRefs) {
+                            LOG.warn("No policy found with id "+id+"; returning null");
+                        } else {
+                            throw new IllegalStateException("No policy found with id "+id);
+                        }
+                    } else if (type != null && !type.isInstance(result)) {
+                        LOG.warn("Policy with id "+id+" does not match type "+type+"; returning "+result);
+                    }
+                    return result;
+                }
+                @Override public Enricher lookupEnricher(Class<?> type, String id) {
+                    Enricher result = rebindContext.getEnricher(id);
+                    if (result == null) {
+                        if (removeDanglingRefs) {
+                            LOG.warn("No enricher found with id "+id+"; returning null");
+                        } else {
+                            throw new IllegalStateException("No enricher found with id "+id);
+                        }
+                    } else if (type != null && !type.isInstance(result)) {
+                        LOG.warn("Enricher with id "+id+" does not match type "+type+"; returning "+result);
+                    }
+                    return result;
+                }
             };
             
             // Two-phase deserialization.
@@ -234,6 +263,16 @@ public class RebindManagerImpl implements RebindManager {
                 rebindContext.registerPolicy(policyMemento.getId(), policy);
             }
             
+            // Instantiate enrichers
+            LOG.info("RebindManager instantiating enrichers: {}", memento.getEnricherIds());
+            for (EnricherMemento enricherMemento : memento.getEnricherMementos().values()) {
+                if (LOG.isDebugEnabled()) LOG.debug("RebindManager instantiating policy {}", enricherMemento);
+                
+                Enricher enricher = newEnricher(enricherMemento, reflections);
+                enrichers.put(enricherMemento.getId(), enricher);
+                rebindContext.registerEnricher(enricherMemento.getId(), enricher);
+            }
+            
             // Reconstruct locations
             LOG.info("RebindManager reconstructing locations");
             for (LocationMemento locMemento : sortParentFirst(memento.getLocationMementos()).values()) {
@@ -242,7 +281,7 @@ public class RebindManagerImpl implements RebindManager {
     
                 ((LocationInternal)location).getRebindSupport().reconstruct(rebindContext, locMemento);
             }
-    
+
             // Reconstruct policies
             LOG.info("RebindManager reconstructing policies");
             for (PolicyMemento policyMemento : memento.getPolicyMementos().values()) {
@@ -251,6 +290,15 @@ public class RebindManagerImpl implements RebindManager {
     
                 policy.getRebindSupport().reconstruct(rebindContext, policyMemento);
             }
+
+            // Reconstruct enrichers
+            LOG.info("RebindManager reconstructing enrichers");
+            for (EnricherMemento enricherMemento : memento.getEnricherMementos().values()) {
+                Enricher enricher = rebindContext.getEnricher(enricherMemento.getId());
+                if (LOG.isDebugEnabled()) LOG.debug("RebindManager reconstructing enricher {}", enricherMemento);
+    
+                enricher.getRebindSupport().reconstruct(rebindContext, enricherMemento);
+            }
     
             // Reconstruct entities
             LOG.info("RebindManager reconstructing entities");
@@ -423,7 +471,6 @@ public class RebindManagerImpl implements RebindManager {
         // note 'used' config keys get marked in BasicLocationRebindSupport
     }
 
-
     /**
      * Constructs a new policy, passing to its constructor the policy id and all of memento.getFlags().
      */
@@ -440,6 +487,22 @@ public class RebindManagerImpl implements RebindManager {
         return (Policy) invokeConstructor(reflections, policyClazz, new Object[] {flags});
     }
 
+    /**
+     * Constructs a new enricher, passing to its constructor the enricher id and all of memento.getFlags().
+     */
+    private Enricher newEnricher(EnricherMemento memento, Reflections reflections) {
+        String id = memento.getId();
+        String enricherType = checkNotNull(memento.getType(), "enricherType of "+id);
+        Class<?> enricherClazz = reflections.loadClass(enricherType);
+
+        Map<String, Object> flags = MutableMap.<String, Object>builder()
+                .put("id", id)
+                .putAll(memento.getFlags())
+                .build();
+
+        return (Enricher) invokeConstructor(reflections, enricherClazz, new Object[] {flags});
+    }
+
     private <T> T invokeConstructor(Reflections reflections, Class<T> clazz, Object[]... possibleArgs) {
         for (Object[] args : possibleArgs) {
             try {
@@ -533,5 +596,14 @@ public class RebindManagerImpl implements RebindManager {
                 LOG.error("Error persisting mememento onChanged("+policy+"); continuing.", t);
             }
         }
+        
+        @Override
+        public void onChanged(Enricher enricher) {
+            try {
+                delegate.onChanged(enricher);
+            } catch (Throwable t) {
+                LOG.error("Error persisting mememento onChanged("+enricher+"); continuing.", t);
+            }
+        }
     }
 }

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/80532a5b/core/src/main/java/brooklyn/entity/rebind/dto/BrooklynMementoImpl.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/brooklyn/entity/rebind/dto/BrooklynMementoImpl.java b/core/src/main/java/brooklyn/entity/rebind/dto/BrooklynMementoImpl.java
index 7704659..b75a112 100644
--- a/core/src/main/java/brooklyn/entity/rebind/dto/BrooklynMementoImpl.java
+++ b/core/src/main/java/brooklyn/entity/rebind/dto/BrooklynMementoImpl.java
@@ -8,6 +8,7 @@ import java.util.Map;
 
 import brooklyn.BrooklynVersion;
 import brooklyn.mementos.BrooklynMemento;
+import brooklyn.mementos.EnricherMemento;
 import brooklyn.mementos.EntityMemento;
 import brooklyn.mementos.LocationMemento;
 import brooklyn.mementos.PolicyMemento;
@@ -31,6 +32,7 @@ public class BrooklynMementoImpl implements BrooklynMemento, Serializable {
         protected final Map<String, EntityMemento> entities = Maps.newLinkedHashMap();
         protected final Map<String, LocationMemento> locations = Maps.newLinkedHashMap();
         protected final Map<String, PolicyMemento> policies = Maps.newLinkedHashMap();
+        protected final Map<String, EnricherMemento> enrichers = Maps.newLinkedHashMap();
         
         public Builder brooklynVersion(String val) {
             brooklynVersion = val; return this;
@@ -53,6 +55,9 @@ public class BrooklynMementoImpl implements BrooklynMemento, Serializable {
         public Builder policy(PolicyMemento val) {
             policies.put(val.getId(), val); return this;
         }
+        public Builder enricher(EnricherMemento val) {
+            enrichers.put(val.getId(), val); return this;
+        }
         public Builder entity(EntityMemento val) {
             entities.put(val.getId(), val); return this;
         }
@@ -62,6 +67,9 @@ public class BrooklynMementoImpl implements BrooklynMemento, Serializable {
         public Builder policies(Map<String, PolicyMemento> vals) {
             policies.putAll(vals); return this;
         }
+        public Builder enricheres(Map<String, EnricherMemento> vals) {
+            enrichers.putAll(vals); return this;
+        }
         public BrooklynMemento build() {
             return new BrooklynMementoImpl(this);
         }
@@ -74,6 +82,7 @@ public class BrooklynMementoImpl implements BrooklynMemento, Serializable {
     private Map<String, EntityMemento> entities;
     private Map<String, LocationMemento> locations;
     private Map<String, PolicyMemento> policies;
+    private Map<String, EnricherMemento> enrichers;
     
     private BrooklynMementoImpl(Builder builder) {
         brooklynVersion = builder.brooklynVersion;
@@ -82,6 +91,7 @@ public class BrooklynMementoImpl implements BrooklynMemento, Serializable {
         entities = builder.entities;
         locations = builder.locations;
         policies = builder.policies;
+        enrichers = builder.enrichers;
     }
 
     @Override
@@ -98,6 +108,11 @@ public class BrooklynMementoImpl implements BrooklynMemento, Serializable {
     public PolicyMemento getPolicyMemento(String id) {
         return policies.get(id);
     }
+    
+    @Override
+    public EnricherMemento getEnricherMemento(String id) {
+        return enrichers.get(id);
+    }
 
     @Override
     public Collection<String> getApplicationIds() {
@@ -120,6 +135,11 @@ public class BrooklynMementoImpl implements BrooklynMemento, Serializable {
     }
     
     @Override
+    public Collection<String> getEnricherIds() {
+        return Collections.unmodifiableSet(enrichers.keySet());
+    }
+    
+    @Override
     public Collection<String> getTopLevelLocationIds() {
         return Collections.unmodifiableList(topLevelLocationIds);
     }
@@ -137,4 +157,9 @@ public class BrooklynMementoImpl implements BrooklynMemento, Serializable {
     public Map<String, PolicyMemento> getPolicyMementos() {
         return Collections.unmodifiableMap(policies);
     }
+
+    @Override
+    public Map<String, EnricherMemento> getEnricherMementos() {
+        return Collections.unmodifiableMap(enrichers);
+    }
 }

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/80532a5b/core/src/main/java/brooklyn/entity/rebind/dto/BrooklynMementoManifestImpl.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/brooklyn/entity/rebind/dto/BrooklynMementoManifestImpl.java b/core/src/main/java/brooklyn/entity/rebind/dto/BrooklynMementoManifestImpl.java
index fdfc1e0..e517f15 100644
--- a/core/src/main/java/brooklyn/entity/rebind/dto/BrooklynMementoManifestImpl.java
+++ b/core/src/main/java/brooklyn/entity/rebind/dto/BrooklynMementoManifestImpl.java
@@ -21,6 +21,7 @@ public class BrooklynMementoManifestImpl implements BrooklynMementoManifest, Ser
         protected final Map<String, String> entityIdToType = Maps.newLinkedHashMap();
         protected final Map<String, String> locationIdToType = Maps.newLinkedHashMap();
         protected final Map<String, String> policyIdToType = Maps.newLinkedHashMap();
+        protected final Map<String, String> enricherIdToType = Maps.newLinkedHashMap();
         
         public Builder brooklynVersion(String val) {
             brooklynVersion = val; return this;
@@ -43,6 +44,12 @@ public class BrooklynMementoManifestImpl implements BrooklynMementoManifest, Ser
         public Builder policies(Map<String, String> vals) {
             policyIdToType.putAll(vals); return this;
         }
+        public Builder enricher(String id, String type) {
+            enricherIdToType.put(id, type); return this;
+        }
+        public Builder enrichers(Map<String, String> vals) {
+            enricherIdToType.putAll(vals); return this;
+        }
         public BrooklynMementoManifest build() {
             return new BrooklynMementoManifestImpl(this);
         }
@@ -51,11 +58,13 @@ public class BrooklynMementoManifestImpl implements BrooklynMementoManifest, Ser
     private Map<String, String> entityIdToType;
     private Map<String, String> locationIdToType;
     private Map<String, String> policyIdToType;
+    private Map<String, String> enricherIdToType;
     
     private BrooklynMementoManifestImpl(Builder builder) {
         entityIdToType = builder.entityIdToType;
         locationIdToType = builder.locationIdToType;
         policyIdToType = builder.policyIdToType;
+        enricherIdToType = builder.enricherIdToType;
     }
 
     @Override
@@ -72,4 +81,9 @@ public class BrooklynMementoManifestImpl implements BrooklynMementoManifest, Ser
     public Map<String, String> getPolicyIdToType() {
         return Collections.unmodifiableMap(policyIdToType);
     }
+
+    @Override
+    public Map<String, String> getEnricherIdToType() {
+        return Collections.unmodifiableMap(enricherIdToType);
+    }
 }

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/80532a5b/core/src/main/java/brooklyn/entity/rebind/persister/AbstractBrooklynMementoPersister.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/brooklyn/entity/rebind/persister/AbstractBrooklynMementoPersister.java b/core/src/main/java/brooklyn/entity/rebind/persister/AbstractBrooklynMementoPersister.java
index 00ad013..1ba1cd1 100644
--- a/core/src/main/java/brooklyn/entity/rebind/persister/AbstractBrooklynMementoPersister.java
+++ b/core/src/main/java/brooklyn/entity/rebind/persister/AbstractBrooklynMementoPersister.java
@@ -6,6 +6,7 @@ import brooklyn.entity.rebind.dto.MutableBrooklynMemento;
 import brooklyn.mementos.BrooklynMemento;
 import brooklyn.mementos.BrooklynMementoManifest;
 import brooklyn.mementos.BrooklynMementoPersister;
+import brooklyn.mementos.EnricherMemento;
 import brooklyn.mementos.EntityMemento;
 import brooklyn.mementos.LocationMemento;
 import brooklyn.mementos.PolicyMemento;
@@ -36,6 +37,9 @@ public abstract class AbstractBrooklynMementoPersister implements BrooklynMement
         for (PolicyMemento entity : memento.getPolicyMementos().values()) {
             builder.policy(entity.getId(), entity.getType());
         }
+        for (EnricherMemento entity : memento.getEnricherMementos().values()) {
+            builder.enricher(entity.getId(), entity.getType());
+        }
         return builder.build();
     }
     
@@ -54,8 +58,10 @@ public abstract class AbstractBrooklynMementoPersister implements BrooklynMement
         memento.removeEntities(delta.removedEntityIds());
         memento.removeLocations(delta.removedLocationIds());
         memento.removePolicies(delta.removedPolicyIds());
+        memento.removeEnrichers(delta.removedEnricherIds());
         memento.updateEntityMementos(delta.entities());
         memento.updateLocationMementos(delta.locations());
         memento.updatePolicyMementos(delta.policies());
+        memento.updateEnricherMementos(delta.enrichers());
     }
 }

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/80532a5b/core/src/main/java/brooklyn/entity/rebind/persister/BrooklynMementoPersisterInMemory.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/brooklyn/entity/rebind/persister/BrooklynMementoPersisterInMemory.java b/core/src/main/java/brooklyn/entity/rebind/persister/BrooklynMementoPersisterInMemory.java
index 19b88d6..fe55213 100644
--- a/core/src/main/java/brooklyn/entity/rebind/persister/BrooklynMementoPersisterInMemory.java
+++ b/core/src/main/java/brooklyn/entity/rebind/persister/BrooklynMementoPersisterInMemory.java
@@ -16,6 +16,8 @@ import brooklyn.entity.proxying.EntityProxy;
 import brooklyn.location.Location;
 import brooklyn.location.basic.LocationInternal;
 import brooklyn.mementos.BrooklynMemento;
+import brooklyn.policy.Enricher;
+import brooklyn.policy.Policy;
 import brooklyn.util.collections.MutableList;
 import brooklyn.util.os.Os;
 import brooklyn.util.time.Duration;
@@ -85,6 +87,16 @@ public class BrooklynMementoPersisterInMemory extends AbstractBrooklynMementoPer
                         if (type != null) types.add(type);
                         return (Location) newDummy(types);
                     }
+                    @Override public Policy lookupPolicy(Class<?> type, String id) {
+                        List<Class<?>> types = MutableList.<Class<?>>of(Policy.class);
+                        if (type != null) types.add(type);
+                        return (Policy) newDummy(types);
+                    }
+                    @Override public Enricher lookupEnricher(Class<?> type, String id) {
+                        List<Class<?>> types = MutableList.<Class<?>>of(Enricher.class);
+                        if (type != null) types.add(type);
+                        return (Enricher) newDummy(types);
+                    }
                     private Object newDummy(List<Class<?>> types) {
                         return java.lang.reflect.Proxy.newProxyInstance(
                             classLoader,

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/80532a5b/core/src/main/java/brooklyn/entity/rebind/persister/BrooklynMementoPersisterToMultiFile.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/brooklyn/entity/rebind/persister/BrooklynMementoPersisterToMultiFile.java b/core/src/main/java/brooklyn/entity/rebind/persister/BrooklynMementoPersisterToMultiFile.java
index a39bbfd..2b5f012 100644
--- a/core/src/main/java/brooklyn/entity/rebind/persister/BrooklynMementoPersisterToMultiFile.java
+++ b/core/src/main/java/brooklyn/entity/rebind/persister/BrooklynMementoPersisterToMultiFile.java
@@ -19,6 +19,7 @@ import brooklyn.entity.rebind.dto.BrooklynMementoManifestImpl;
 import brooklyn.mementos.BrooklynMemento;
 import brooklyn.mementos.BrooklynMementoManifest;
 import brooklyn.mementos.BrooklynMementoPersister;
+import brooklyn.mementos.EnricherMemento;
 import brooklyn.mementos.EntityMemento;
 import brooklyn.mementos.LocationMemento;
 import brooklyn.mementos.PolicyMemento;
@@ -44,10 +45,12 @@ public class BrooklynMementoPersisterToMultiFile implements BrooklynMementoPersi
     private final File entitiesDir;
     private final File locationsDir;
     private final File policiesDir;
+    private final File enrichersDir;
 
     private final ConcurrentMap<String, MementoFileWriter<EntityMemento>> entityWriters = new ConcurrentHashMap<String, MementoFileWriter<EntityMemento>>();
     private final ConcurrentMap<String, MementoFileWriter<LocationMemento>> locationWriters = new ConcurrentHashMap<String, MementoFileWriter<LocationMemento>>();
     private final ConcurrentMap<String, MementoFileWriter<PolicyMemento>> policyWriters = new ConcurrentHashMap<String, MementoFileWriter<PolicyMemento>>();
+    private final ConcurrentMap<String, MementoFileWriter<EnricherMemento>> enricherWriters = new ConcurrentHashMap<String, MementoFileWriter<EnricherMemento>>();
     
     private final MementoSerializer<Object> serializer;
 
@@ -77,6 +80,10 @@ public class BrooklynMementoPersisterToMultiFile implements BrooklynMementoPersi
         policiesDir = new File(dir, "policies");
         policiesDir.mkdir();
         checkDirIsAccessible(policiesDir);
+        
+        enrichersDir = new File(dir, "enrichers");
+        enrichersDir.mkdir();
+        checkDirIsAccessible(enrichersDir);
 
         File planeDir = new File(dir, "plane");
         planeDir.mkdir();
@@ -114,9 +121,10 @@ public class BrooklynMementoPersisterToMultiFile implements BrooklynMementoPersi
         File[] entityFiles = entitiesDir.listFiles(fileFilter);
         File[] locationFiles = locationsDir.listFiles(fileFilter);
         File[] policyFiles = policiesDir.listFiles(fileFilter);
+        File[] enricherFiles = enrichersDir.listFiles(fileFilter);
 
-        LOG.info("Loading memento manifest from {}; {} entities, {} locations, {} policies", 
-                new Object[] {dir, entityFiles.length, locationFiles.length, policyFiles.length});
+        LOG.info("Loading memento manifest from {}; {} entities, {} locations, {} policies, {} policies", 
+                new Object[] {dir, entityFiles.length, locationFiles.length, policyFiles.length, enricherFiles.length});
         
         BrooklynMementoManifestImpl.Builder builder = BrooklynMementoManifestImpl.builder();
         
@@ -139,6 +147,12 @@ public class BrooklynMementoPersisterToMultiFile implements BrooklynMementoPersi
                 String type = (String) XmlUtil.xpath(contents, "/policy/type");
                 builder.policy(id, type);
             }
+            for (File file : enricherFiles) {
+                String contents = readFile(file);
+                String id = (String) XmlUtil.xpath(contents, "/enricher/id");
+                String type = (String) XmlUtil.xpath(contents, "/enricher/type");
+                builder.enricher(id, type);
+            }
             
             if (LOG.isDebugEnabled()) LOG.debug("Loaded memento manifest; took {}", Time.makeTimeStringRounded(stopwatch.elapsed(TimeUnit.MILLISECONDS))); 
             return builder.build();
@@ -164,9 +178,10 @@ public class BrooklynMementoPersisterToMultiFile implements BrooklynMementoPersi
         File[] entityFiles = entitiesDir.listFiles(fileFilter);
         File[] locationFiles = locationsDir.listFiles(fileFilter);
         File[] policyFiles = policiesDir.listFiles(fileFilter);
+        File[] enricherFiles = enrichersDir.listFiles(fileFilter);
 
-        LOG.info("Loading memento from {}; {} entities, {} locations, {} policies", 
-                new Object[] {dir, entityFiles.length, locationFiles.length, policyFiles.length});
+        LOG.info("Loading memento from {}; {} entities, {} locations, {} policies and {} enrichers", 
+                new Object[] {dir, entityFiles.length, locationFiles.length, policyFiles.length}, enricherFiles.length);
         
         BrooklynMementoImpl.Builder builder = BrooklynMementoImpl.builder();
         
@@ -199,6 +214,14 @@ public class BrooklynMementoPersisterToMultiFile implements BrooklynMementoPersi
                     builder.policy(memento);
                 }
             }
+            for (File file : enricherFiles) {
+                EnricherMemento memento = (EnricherMemento) serializer.fromString(readFile(file));
+                if (memento == null) {
+                    LOG.warn("No enricher-memento deserialized from file "+file+"; ignoring and continuing");
+                } else {
+                    builder.enricher(memento);
+                }
+            }
             
             if (LOG.isDebugEnabled()) LOG.debug("Loaded memento; took {}", Time.makeTimeStringRounded(stopwatch.elapsed(TimeUnit.MILLISECONDS))); 
             return builder.build();
@@ -225,6 +248,9 @@ public class BrooklynMementoPersisterToMultiFile implements BrooklynMementoPersi
         for (PolicyMemento m : newMemento.getPolicyMementos().values()) {
             persist(m);
         }
+        for (EnricherMemento m : newMemento.getEnricherMementos().values()) {
+            persist(m);
+        }
     }
     
     @Override
@@ -233,10 +259,10 @@ public class BrooklynMementoPersisterToMultiFile implements BrooklynMementoPersi
             if (LOG.isDebugEnabled()) LOG.debug("Ignoring checkpointed delta of memento, because not running");
             return;
         }
-        if (LOG.isTraceEnabled()) LOG.trace("Checkpointed delta of memento; updating {} entities, {} locations and {} policies; " +
-        		"removing {} entities, {} locations and {} policies", 
-                new Object[] {delta.entities(), delta.locations(), delta.policies(),
-                delta.removedEntityIds(), delta.removedLocationIds(), delta.removedPolicyIds()});
+        if (LOG.isTraceEnabled()) LOG.trace("Checkpointed delta of memento; updating {} entities, {} locations, {} policies and {} enrichers; " +
+        		"removing {} entities, {} locations {} policies and {} enrichers", 
+                new Object[] {delta.entities(), delta.locations(), delta.policies(), delta.enrichers(),
+                delta.removedEntityIds(), delta.removedLocationIds(), delta.removedPolicyIds(), delta.removedEnricherIds()});
         
         for (EntityMemento entity : delta.entities()) {
             persist(entity);
@@ -247,6 +273,9 @@ public class BrooklynMementoPersisterToMultiFile implements BrooklynMementoPersi
         for (PolicyMemento policy : delta.policies()) {
             persist(policy);
         }
+        for (EnricherMemento enricher : delta.enrichers()) {
+            persist(enricher);
+        }
         for (String id : delta.removedEntityIds()) {
             deleteEntity(id);
         }
@@ -256,6 +285,9 @@ public class BrooklynMementoPersisterToMultiFile implements BrooklynMementoPersi
         for (String id : delta.removedPolicyIds()) {
             deletePolicy(id);
         }
+        for (String id : delta.removedEnricherIds()) {
+            deleteEnricher(id);
+        }
     }
 
     @VisibleForTesting
@@ -279,6 +311,9 @@ public class BrooklynMementoPersisterToMultiFile implements BrooklynMementoPersi
         for (MementoFileWriter<?> writer : policyWriters.values()) {
             writer.waitForWriteCompleted(timeout);
         }
+        for (MementoFileWriter<?> writer : enricherWriters.values()) {
+            writer.waitForWriteCompleted(timeout);
+        }
     }
 
     // TODO Promote somewhere sensible; share code with BrooklynLauncher.checkPersistenceDirAccessible
@@ -322,6 +357,15 @@ public class BrooklynMementoPersisterToMultiFile implements BrooklynMementoPersi
         }
         writer.write(policy);
     }
+    
+    private void persist(EnricherMemento enricher) {
+        MementoFileWriter<EnricherMemento> writer = enricherWriters.get(enricher.getId());
+        if (writer == null) {
+            enricherWriters.putIfAbsent(enricher.getId(), new MementoFileWriter<EnricherMemento>(getFileFor(enricher), executor, serializer));
+            writer = enricherWriters.get(enricher.getId());
+        }
+        writer.write(enricher);
+    }
 
     private void deleteEntity(String id) {
         MementoFileWriter<EntityMemento> writer = entityWriters.get(id);
@@ -343,6 +387,13 @@ public class BrooklynMementoPersisterToMultiFile implements BrooklynMementoPersi
             writer.delete();
         }
     }
+    
+    private void deleteEnricher(String id) {
+        MementoFileWriter<EnricherMemento> writer = enricherWriters.get(id);
+        if (writer != null) {
+            writer.delete();
+        }
+    }
 
     private File getFileFor(EntityMemento entity) {
         return new File(entitiesDir, entity.getId());
@@ -355,4 +406,8 @@ public class BrooklynMementoPersisterToMultiFile implements BrooklynMementoPersi
     private File getFileFor(PolicyMemento policy) {
         return new File(policiesDir, policy.getId());
     }
+    
+    private File getFileFor(EnricherMemento enricher) {
+        return new File(enrichersDir, enricher.getId());
+    }
 }

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/80532a5b/core/src/main/java/brooklyn/entity/rebind/persister/XmlMementoSerializer.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/brooklyn/entity/rebind/persister/XmlMementoSerializer.java b/core/src/main/java/brooklyn/entity/rebind/persister/XmlMementoSerializer.java
index 8b44234..02da444 100644
--- a/core/src/main/java/brooklyn/entity/rebind/persister/XmlMementoSerializer.java
+++ b/core/src/main/java/brooklyn/entity/rebind/persister/XmlMementoSerializer.java
@@ -15,8 +15,10 @@ import brooklyn.entity.basic.BasicParameterType;
 import brooklyn.entity.effector.EffectorAndBody;
 import brooklyn.entity.effector.EffectorTasks.EffectorBodyTaskFactory;
 import brooklyn.entity.effector.EffectorTasks.EffectorTaskFactory;
+import brooklyn.entity.rebind.dto.BasicEnricherMemento;
 import brooklyn.entity.rebind.dto.BasicEntityMemento;
 import brooklyn.entity.rebind.dto.BasicLocationMemento;
+import brooklyn.entity.rebind.dto.BasicPolicyMemento;
 import brooklyn.entity.rebind.dto.MutableBrooklynMemento;
 import brooklyn.entity.trait.Identifiable;
 import brooklyn.event.basic.BasicAttributeSensor;
@@ -24,6 +26,8 @@ import brooklyn.event.basic.BasicConfigKey;
 import brooklyn.location.Location;
 import brooklyn.management.Task;
 import brooklyn.mementos.BrooklynMementoPersister.LookupContext;
+import brooklyn.policy.Enricher;
+import brooklyn.policy.Policy;
 import brooklyn.util.exceptions.Exceptions;
 import brooklyn.util.xstream.XmlSerializer;
 
@@ -57,6 +61,8 @@ public class XmlMementoSerializer<T> extends XmlSerializer<T> implements Memento
         
         xstream.alias("entity", BasicEntityMemento.class);
         xstream.alias("location", BasicLocationMemento.class);
+        xstream.alias("policy", BasicPolicyMemento.class);
+        xstream.alias("enricher", BasicEnricherMemento.class);
         xstream.alias("configKey", BasicConfigKey.class);
         xstream.alias("attributeSensor", BasicAttributeSensor.class);
         
@@ -67,11 +73,14 @@ public class XmlMementoSerializer<T> extends XmlSerializer<T> implements Memento
         
         xstream.alias("entityRef", Entity.class);
         xstream.alias("locationRef", Location.class);
+        xstream.alias("policyRef", Policy.class);
+        xstream.alias("enricherRef", Enricher.class);
 
         xstream.registerConverter(new LocationConverter());
+        xstream.registerConverter(new PolicyConverter());
+        xstream.registerConverter(new EnricherConverter());
         xstream.registerConverter(new EntityConverter());
         xstream.registerConverter(new TaskConverter(xstream.getMapper()));
-        // TODO policies/enrichers serialization/deserialization?!
     }
     
     // Warning: this is called in the super-class constuctor, so before this constructor!
@@ -187,6 +196,26 @@ public class XmlMementoSerializer<T> extends XmlSerializer<T> implements Memento
             return lookupContext.lookupLocation(type, id);
         }
     }
+
+    public class PolicyConverter extends IdentifiableConverter<Policy> {
+        PolicyConverter() {
+            super(Policy.class);
+        }
+        @Override
+        protected Policy lookup(Class<?> type, String id) {
+            return lookupContext.lookupPolicy(type, id);
+        }
+    }
+
+    public class EnricherConverter extends IdentifiableConverter<Enricher> {
+        EnricherConverter() {
+            super(Enricher.class);
+        }
+        @Override
+        protected Enricher lookup(Class<?> type, String id) {
+            return lookupContext.lookupEnricher(type, id);
+        }
+    }
     
     public class EntityConverter extends IdentifiableConverter<Entity> {
         EntityConverter() {

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/80532a5b/core/src/main/java/brooklyn/management/internal/EntityChangeListener.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/brooklyn/management/internal/EntityChangeListener.java b/core/src/main/java/brooklyn/management/internal/EntityChangeListener.java
index 197b5ae..36a6324 100644
--- a/core/src/main/java/brooklyn/management/internal/EntityChangeListener.java
+++ b/core/src/main/java/brooklyn/management/internal/EntityChangeListener.java
@@ -30,7 +30,7 @@ public interface EntityChangeListener {
 
     void onChildrenChanged();
 
-    void onPoliciesChanged();
+    void onPoliciesChanged(); // TODO
 
     void onEffectorStarting(Effector<?> effector);
     

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/80532a5b/core/src/main/java/brooklyn/management/internal/EntityManagementSupport.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/brooklyn/management/internal/EntityManagementSupport.java b/core/src/main/java/brooklyn/management/internal/EntityManagementSupport.java
index c9b974b..6d65648 100644
--- a/core/src/main/java/brooklyn/management/internal/EntityManagementSupport.java
+++ b/core/src/main/java/brooklyn/management/internal/EntityManagementSupport.java
@@ -344,7 +344,9 @@ public class EntityManagementSupport {
         }
         @Override
         public void onAttributeChanged(AttributeSensor<?> attribute) {
+            // if important persist, otherwiise ignore
             getManagementContext().getRebindManager().getChangeListener().onChanged(entity);
+            // getManagementContext().getRebindManager().getAttributeChangeListener().onChanged(entity, attribute);
         }
         @Override
         public void onConfigChanged(ConfigKey<?> key) {

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/80532a5b/core/src/test/java/brooklyn/entity/rebind/persister/XmlMementoSerializerTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/brooklyn/entity/rebind/persister/XmlMementoSerializerTest.java b/core/src/test/java/brooklyn/entity/rebind/persister/XmlMementoSerializerTest.java
index 02e06fb..47d525b 100644
--- a/core/src/test/java/brooklyn/entity/rebind/persister/XmlMementoSerializerTest.java
+++ b/core/src/test/java/brooklyn/entity/rebind/persister/XmlMementoSerializerTest.java
@@ -22,6 +22,8 @@ import brooklyn.location.Location;
 import brooklyn.location.LocationSpec;
 import brooklyn.management.ManagementContext;
 import brooklyn.mementos.BrooklynMementoPersister.LookupContext;
+import brooklyn.policy.Enricher;
+import brooklyn.policy.Policy;
 import brooklyn.test.entity.TestApplication;
 import brooklyn.util.collections.MutableList;
 import brooklyn.util.collections.MutableMap;
@@ -43,76 +45,76 @@ public class XmlMementoSerializerTest {
     public void setUp() throws Exception {
         serializer = new XmlMementoSerializer<Object>(XmlMementoSerializerTest.class.getClassLoader());
     }
-    
+
     @Test
     public void testMutableSet() throws Exception {
         Set<?> obj = MutableSet.of("123");
         assertSerializeAndDeserialize(obj);
     }
-    
+
     @Test
     public void testLinkedHashSet() throws Exception {
         Set<String> obj = new LinkedHashSet<String>();
         obj.add("123");
         assertSerializeAndDeserialize(obj);
     }
-    
+
     @Test
     public void testImmutableSet() throws Exception {
         Set<String> obj = ImmutableSet.of("123");
         assertSerializeAndDeserialize(obj);
     }
-    
+
     @Test
     public void testMutableList() throws Exception {
         List<?> obj = MutableList.of("123");
         assertSerializeAndDeserialize(obj);
     }
-    
+
     @Test
     public void testLinkedList() throws Exception {
         List<String> obj = new LinkedList<String>();
         obj.add("123");
         assertSerializeAndDeserialize(obj);
     }
-    
+
     @Test
     public void testImmutableList() throws Exception {
         List<String> obj = ImmutableList.of("123");
         assertSerializeAndDeserialize(obj);
     }
-    
+
     @Test
     public void testMutableMap() throws Exception {
         Map<?,?> obj = MutableMap.of("mykey", "myval");
         assertSerializeAndDeserialize(obj);
     }
-    
+
     @Test
     public void testLinkedHashMap() throws Exception {
         Map<String,String> obj = new LinkedHashMap<String,String>();
         obj.put("mykey", "myval");
         assertSerializeAndDeserialize(obj);
     }
-    
+
     @Test
     public void testImmutableMap() throws Exception {
         Map<?,?> obj = ImmutableMap.of("mykey", "myval");
         assertSerializeAndDeserialize(obj);
     }
-    
+
     @Test
     public void testEntity() throws Exception {
         final TestApplication app = ApplicationBuilder.newManagedApp(TestApplication.class);
         ManagementContext managementContext = app.getManagementContext();
         try {
-            serializer.setLookupContext(new LookupContextImpl(ImmutableMap.of(app.getId(), app), ImmutableMap.<String,Location>of()));
+            serializer.setLookupContext(new LookupContextImpl(ImmutableMap.of(app.getId(), app), ImmutableMap.<String,Location>of(), ImmutableMap.<String,Policy>of(), ImmutableMap.<String,Enricher>of()));
             assertSerializeAndDeserialize(app);
         } finally {
             Entities.destroyAll(managementContext);
         }
     }
-    
+
     @Test
     public void testLocation() throws Exception {
         TestApplication app = ApplicationBuilder.newManagedApp(TestApplication.class);
@@ -120,41 +122,41 @@ public class XmlMementoSerializerTest {
         try {
             @SuppressWarnings("deprecation")
             final Location loc = managementContext.getLocationManager().createLocation(LocationSpec.create(brooklyn.location.basic.SimulatedLocation.class));
-            serializer.setLookupContext(new LookupContextImpl(ImmutableMap.<String,Entity>of(), ImmutableMap.of(loc.getId(), loc)));
+            serializer.setLookupContext(new LookupContextImpl(ImmutableMap.<String,Entity>of(), ImmutableMap.of(loc.getId(), loc), ImmutableMap.<String,Policy>of(), ImmutableMap.<String,Enricher>of()));
             assertSerializeAndDeserialize(loc);
         } finally {
             Entities.destroyAll(managementContext);
         }
     }
-    
+
     @Test
     public void testFieldReffingEntity() throws Exception {
         final TestApplication app = ApplicationBuilder.newManagedApp(TestApplication.class);
         ReffingEntity reffer = new ReffingEntity(app);
         ManagementContext managementContext = app.getManagementContext();
         try {
-            serializer.setLookupContext(new LookupContextImpl(ImmutableMap.of(app.getId(), app), ImmutableMap.<String,Location>of()));
+            serializer.setLookupContext(new LookupContextImpl(ImmutableMap.of(app.getId(), app), ImmutableMap.<String,Location>of(), ImmutableMap.<String,Policy>of(), ImmutableMap.<String,Enricher>of()));
             ReffingEntity reffer2 = assertSerializeAndDeserialize(reffer);
             assertEquals(reffer2.entity, app);
         } finally {
             Entities.destroyAll(managementContext);
         }
     }
-    
+
     @Test
     public void testUntypedFieldReffingEntity() throws Exception {
         final TestApplication app = ApplicationBuilder.newManagedApp(TestApplication.class);
         ReffingEntity reffer = new ReffingEntity((Object)app);
         ManagementContext managementContext = app.getManagementContext();
         try {
-            serializer.setLookupContext(new LookupContextImpl(ImmutableMap.of(app.getId(), app), ImmutableMap.<String,Location>of()));
+            serializer.setLookupContext(new LookupContextImpl(ImmutableMap.of(app.getId(), app), ImmutableMap.<String,Location>of(), ImmutableMap.<String,Policy>of(), ImmutableMap.<String,Enricher>of()));
             ReffingEntity reffer2 = assertSerializeAndDeserialize(reffer);
             assertEquals(reffer2.obj, app);
         } finally {
             Entities.destroyAll(managementContext);
         }
     }
-    
+
     public static class ReffingEntity {
         public Entity entity;
         public Object obj;
@@ -173,7 +175,7 @@ public class XmlMementoSerializerTest {
             return Objects.hashCode(entity, obj);
         }
     }
-    
+
     @SuppressWarnings("unchecked")
     private <T> T assertSerializeAndDeserialize(T obj) throws Exception {
         String serializedForm = serializer.toString(obj);
@@ -182,14 +184,19 @@ public class XmlMementoSerializerTest {
         assertEquals(deserialized, obj, "serializedForm="+serializedForm);
         return (T) deserialized;
     }
-    
+
     static class LookupContextImpl implements LookupContext {
         private final Map<String, ? extends Entity> entities;
         private final Map<String, ? extends Location> locations;
-        
-        LookupContextImpl(Map<String,? extends Entity> entities, Map<String,? extends Location> locations) {
+        private final Map<String, ? extends Policy> policies;
+        private final Map<String, ? extends Enricher> enrichers;
+
+        LookupContextImpl(Map<String,? extends Entity> entities, Map<String,? extends Location> locations,
+                Map<String,? extends Policy> policies, Map<String,? extends Enricher> enrichers) {
             this.entities = entities;
             this.locations = locations;
+            this.policies = policies;
+            this.enrichers = enrichers;
         }
         @Override public Entity lookupEntity(Class<?> type, String id) {
             if (entities.containsKey(id)) {
@@ -199,7 +206,7 @@ public class XmlMementoSerializerTest {
                 }
                 return result;
             }
-            throw new NoSuchElementException("no entity with id "+id+"; contenders are "+locations.keySet()); 
+            throw new NoSuchElementException("no entity with id "+id+"; contenders are "+entities.keySet());
         }
         @Override public Location lookupLocation(Class<?> type, String id) {
             if (locations.containsKey(id)) {
@@ -209,7 +216,27 @@ public class XmlMementoSerializerTest {
                 }
                 return result;
             }
-            throw new NoSuchElementException("no location with id "+id+"; contenders are "+locations.keySet()); 
+            throw new NoSuchElementException("no location with id "+id+"; contenders are "+locations.keySet());
+        }
+        @Override public Policy lookupPolicy(Class<?> type, String id) {
+            if (policies.containsKey(id)) {
+                Policy result = policies.get(id);
+                if (type != null && !type.isInstance(result)) {
+                    throw new IllegalStateException("Policy with id "+id+" does not match type "+type+"; got "+result);
+                }
+                return result;
+            }
+            throw new NoSuchElementException("no policy with id "+id+"; contenders are "+policies.keySet());
+        }
+        @Override public Enricher lookupEnricher(Class<?> type, String id) {
+            if (enrichers.containsKey(id)) {
+                Enricher result = enrichers.get(id);
+                if (type != null && !type.isInstance(result)) {
+                    throw new IllegalStateException("Enricher with id "+id+" does not match type "+type+"; got "+result);
+                }
+                return result;
+            }
+            throw new NoSuchElementException("no enricher with id "+id+"; contenders are "+enrichers.keySet());
         }
     };
 }


[46/50] [abbrv] git commit: correct message about ctrl-c to shutdown because if running in background that does not work!

Posted by ri...@apache.org.
correct message about ctrl-c to shutdown because if running in background that does not work!


Project: http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/commit/37cf8174
Tree: http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/tree/37cf8174
Diff: http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/diff/37cf8174

Branch: refs/pull/1414/merge
Commit: 37cf81745a9e32b3de2c81498cd1c65f1b6fde0f
Parents: 17ac898
Author: Alex Heneveld <al...@cloudsoftcorp.com>
Authored: Fri May 23 10:34:32 2014 -0600
Committer: Alex Heneveld <al...@cloudsoftcorp.com>
Committed: Fri May 23 10:34:32 2014 -0600

----------------------------------------------------------------------
 usage/cli/src/main/java/brooklyn/cli/Main.java | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/37cf8174/usage/cli/src/main/java/brooklyn/cli/Main.java
----------------------------------------------------------------------
diff --git a/usage/cli/src/main/java/brooklyn/cli/Main.java b/usage/cli/src/main/java/brooklyn/cli/Main.java
index 8d32c93..d9069a4 100644
--- a/usage/cli/src/main/java/brooklyn/cli/Main.java
+++ b/usage/cli/src/main/java/brooklyn/cli/Main.java
@@ -501,7 +501,7 @@ public class Main {
                 stopAllApps(ctx.getApplications());
             } else {
                 // Block forever so that Brooklyn doesn't exit (until someone does cntrl-c or kill)
-                log.info("Launched Brooklyn; now blocking to wait for cntrl-c or kill");
+                log.info("Launched Brooklyn; will now block until shutdown issued. Shutdown via GUI or API or process interrupt.");
                 waitUntilInterrupted();
             }
         }


[44/50] [abbrv] git commit: add function for converting to string, and use that for the "cpu fraction" sensor

Posted by ri...@apache.org.
add function for converting to string, and use that for the "cpu fraction" sensor


Project: http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/commit/17ac8986
Tree: http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/tree/17ac8986
Diff: http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/diff/17ac8986

Branch: refs/pull/1414/head
Commit: 17ac89862c4fd89fb35c35a816b9967ab50b455e
Parents: 37bf67a
Author: Alex Heneveld <al...@cloudsoftcorp.com>
Authored: Fri May 23 10:28:04 2014 -0600
Committer: Alex Heneveld <al...@cloudsoftcorp.com>
Committed: Fri May 23 10:28:04 2014 -0600

----------------------------------------------------------------------
 .../java/brooklyn/entity/java/JavaAppUtils.java |  5 ++--
 .../java/brooklyn/util/math/MathFunctions.java  | 24 +++++++++++++++++++-
 .../brooklyn/util/math/MathFunctionsTest.java   | 18 +++++++++++++++
 3 files changed, 43 insertions(+), 4 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/17ac8986/software/base/src/main/java/brooklyn/entity/java/JavaAppUtils.java
----------------------------------------------------------------------
diff --git a/software/base/src/main/java/brooklyn/entity/java/JavaAppUtils.java b/software/base/src/main/java/brooklyn/entity/java/JavaAppUtils.java
index b5bfb31..eb6d2e5 100644
--- a/software/base/src/main/java/brooklyn/entity/java/JavaAppUtils.java
+++ b/software/base/src/main/java/brooklyn/entity/java/JavaAppUtils.java
@@ -216,7 +216,6 @@ public class JavaAppUtils {
     private static final AtomicBoolean initialized = new AtomicBoolean(false);
 
     /** Setup renderer hints for the MXBean attributes. */
-    @SuppressWarnings("rawtypes")
     public static void init() {
         if (initialized.get()) return;
         synchronized (initialized) {
@@ -233,8 +232,8 @@ public class JavaAppUtils {
             RendererHints.register(UsesJavaMXBeans.START_TIME, RendererHints.displayValue(Time.toDateString()));
             RendererHints.register(UsesJavaMXBeans.UP_TIME, RendererHints.displayValue(Duration.millisToStringRounded()));
             RendererHints.register(UsesJavaMXBeans.PROCESS_CPU_TIME, RendererHints.displayValue(Duration.millisToStringRounded()));
-            RendererHints.register(UsesJavaMXBeans.PROCESS_CPU_TIME_FRACTION_LAST, RendererHints.displayValue(Duration.millisToStringRounded()));
-            RendererHints.register(UsesJavaMXBeans.PROCESS_CPU_TIME_FRACTION_IN_WINDOW, RendererHints.displayValue(Duration.millisToStringRounded()));
+            RendererHints.register(UsesJavaMXBeans.PROCESS_CPU_TIME_FRACTION_LAST, RendererHints.displayValue(MathFunctions.percent(4)));
+            RendererHints.register(UsesJavaMXBeans.PROCESS_CPU_TIME_FRACTION_IN_WINDOW, RendererHints.displayValue(MathFunctions.percent(4)));
 
             initialized.set(true);
         }

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/17ac8986/utils/common/src/main/java/brooklyn/util/math/MathFunctions.java
----------------------------------------------------------------------
diff --git a/utils/common/src/main/java/brooklyn/util/math/MathFunctions.java b/utils/common/src/main/java/brooklyn/util/math/MathFunctions.java
index c70cdfc..dbf5604 100644
--- a/utils/common/src/main/java/brooklyn/util/math/MathFunctions.java
+++ b/utils/common/src/main/java/brooklyn/util/math/MathFunctions.java
@@ -2,6 +2,8 @@ package brooklyn.util.math;
 
 import javax.annotation.Nullable;
 
+import brooklyn.util.text.Strings;
+
 import com.google.common.base.Function;
 
 public class MathFunctions {
@@ -61,5 +63,25 @@ public class MathFunctions {
             }
         };
     }
-    
+
+    /** returns a string of up to maxLen length (longer in extreme cases) also capped at significantDigits significantDigits */
+    public static Function<Number, String> readableString(final int significantDigits, final int maxLen) {
+        return new Function<Number, String>() {
+            public String apply(@Nullable Number input) {
+                if (input==null) return null;
+                return Strings.makeRealString(input.doubleValue(), maxLen, significantDigits, 0);
+            }
+        };
+    }
+
+    /** returns a string where the input number is expressed as percent, with given number of significant digits */
+    public static Function<Number, String> percent(final int significantDigits) {
+        return new Function<Number, String>() {
+            public String apply(@Nullable Number input) {
+                if (input==null) return null;
+                return readableString(significantDigits, significantDigits+3).apply(input.doubleValue() * 100d)+"%";
+            }
+        };
+    }
+
 }

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/17ac8986/utils/common/src/test/java/brooklyn/util/math/MathFunctionsTest.java
----------------------------------------------------------------------
diff --git a/utils/common/src/test/java/brooklyn/util/math/MathFunctionsTest.java b/utils/common/src/test/java/brooklyn/util/math/MathFunctionsTest.java
new file mode 100644
index 0000000..6f0955d
--- /dev/null
+++ b/utils/common/src/test/java/brooklyn/util/math/MathFunctionsTest.java
@@ -0,0 +1,18 @@
+package brooklyn.util.math;
+
+import org.testng.Assert;
+import org.testng.annotations.Test;
+
+public class MathFunctionsTest {
+
+    @Test
+    public void testAdd() {
+        Assert.assertEquals(MathFunctions.plus(3).apply(4), (Integer)7);
+        Assert.assertEquals(MathFunctions.plus(0.3).apply(0.4).doubleValue(), 0.7, 0.00000001);
+    }
+    
+    @Test
+    public void testPercent() {
+        Assert.assertEquals(MathFunctions.percent(3).apply(0.0123456), "1.23%");
+    }
+}


[17/50] [abbrv] git commit: Move to docs for 0.7.0. Includes YAML GS and new Location section. - GS split to 1) Download and Deploy, 2) Catalog and Polices - brooklyn.properties small tidies - many screenshots added - YAML sample moved to include file -

Posted by ri...@apache.org.
Move to docs for 0.7.0. Includes YAML GS and new Location section.
- GS split to 1) Download and Deploy, 2) Catalog and Polices
- brooklyn.properties small tidies
- many screenshots added
- YAML sample moved to include file
- Deprecated help file contents removed.


Project: http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/commit/bd0e1e07
Tree: http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/tree/bd0e1e07
Diff: http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/diff/bd0e1e07

Branch: refs/heads/master
Commit: bd0e1e077e04726f4119fc0fa65e3bb3b5cf58a4
Parents: f54024f
Author: David Toy <d...@vidtoy.co.uk>
Authored: Mon Apr 14 21:24:08 2014 +0100
Committer: David Toy <d...@vidtoy.co.uk>
Committed: Thu May 22 11:21:06 2014 +0100

----------------------------------------------------------------------
 docs/_scripts/help.txt                          |  81 +-----------
 docs/use/guide/locations/index.md               |  35 +++--
 docs/use/guide/quickstart/brooklyn.properties   |  72 +++++-----
 ...cation-catalog-web-cluster-with-db-large.png | Bin 0 -> 131618 bytes
 ...talog-web-cluster-with-db-location-large.png | Bin 0 -> 152721 bytes
 ...ion-catalog-web-cluster-with-db-location.png | Bin 0 -> 86425 bytes
 ...-application-catalog-web-cluster-with-db.png | Bin 0 -> 76065 bytes
 .../images/add-application-modal-yaml.png       | Bin 0 -> 68401 bytes
 .../images/jboss7-cluster-policies-large.png    | Bin 0 -> 157883 bytes
 .../images/jboss7-cluster-policies.png          | Bin 0 -> 94056 bytes
 .../images/my-db-activities-large.png           | Bin 0 -> 208313 bytes
 .../quickstart/images/my-db-activities.png      | Bin 0 -> 130262 bytes
 .../images/my-web-cluster-starting.png          | Bin 0 -> 32948 bytes
 .../my-web-cluster-stop-confirm-large.png       | Bin 0 -> 148155 bytes
 .../images/my-web-cluster-stop-confirm.png      | Bin 0 -> 79280 bytes
 .../quickstart/images/my-web-summary-large.png  | Bin 0 -> 178785 bytes
 .../guide/quickstart/images/my-web-summary.png  | Bin 0 -> 80583 bytes
 docs/use/guide/quickstart/images/my-web.png     | Bin 0 -> 83081 bytes
 docs/use/guide/quickstart/index.md              | 130 ++++++++++---------
 docs/use/guide/quickstart/my-web-cluster.yaml   |  19 +++
 .../guide/quickstart/policies-and-catalogs.md   |  66 ++++++++++
 docs/use/guide/quickstart/toc.json              |   4 +
 docs/use/guide/toc.json                         |   5 +-
 23 files changed, 224 insertions(+), 188 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/bd0e1e07/docs/_scripts/help.txt
----------------------------------------------------------------------
diff --git a/docs/_scripts/help.txt b/docs/_scripts/help.txt
index f6e4ae5..0a41a7b 100644
--- a/docs/_scripts/help.txt
+++ b/docs/_scripts/help.txt
@@ -9,81 +9,8 @@ _scripts/build.sh
     will build the site in _site including javadoc for offline browsing
 
 
+Release Process
+===============
 
-###############################################################################
-# Deprecation Warning                                                         #
-#                                                                             #
-# The following content has been superseded, and will be removed shortly      #
-# Please view /dev/tips/release.md or see:                                    #
-# http://brooklyncentral.github.io/v/0.6.0-SNAPSHOT/dev/tips/release.html     #
-#                                                                             #
-###############################################################################
-
-
-GO LIVE (SNAPSHOT)
-------------------
-
-to make the docs live you build.sh then push _site to github brooklyncentral/brooklyncentral.github.com
-the following instructions cover this, assuming brooklyncentral.github.com is a sibling dir to the brooklyn project,
-and you are in the docs dir
-
-
-updating a snapshot version, in /v/VERSION/ on the server:
-
-export TARGET=`pwd -P`/../../brooklyncentral.github.com
-export BV=0.7.0-SNAPSHOT   # BROOKLYN_VERSION
-
-# make sure repo is at latest
-pushd $TARGET
-git pull
-popd
-
-# build, copy
-if [ ! -f $TARGET/index.html ] ; then echo "could not find docs in $TARGET" ; exit 1 ; fi
-_scripts/build.sh || { echo "failed to build docs" ; exit 1 ; }
-rm -rf $TARGET/v/$BV
-mkdir $TARGET/v/$BV
-cp -r _site/* $TARGET/v/$BV/
-
-# and push
-pushd $TARGET
-git add -A .
-git commit -m "updated version docs for version $BV"
-git push
-popd
-
-
-RELEASE
--------
-
-when we do a RELEASE we must run the above for e.g. BV=0.4.0
-AND must update the files in the root dir of brooklyncentral.github.com
-
-the commands below do this (basically like the process above but 
-with / in place of /v/$BV and overriding url in _config.yml 
-with the --url arg below):
-
-
-# remove old root files
-pushd $TARGET
-if [ -f start/index.html ] ; then
-  for x in * ; do if [[ $x != "v" ]] ; then rm -rf $x ; fi ; done
-else
-  echo IN WRONG DIRECTORY $TARGET - export TARGET to continue
-  exit 1
-fi
-popd
-
-# build for hosting of / rather than /v/VERSION/
-_scripts/build.sh --url "" || { echo "failed to build docs" ; exit 1 ; }
-cp -r _site/* $TARGET/
-
-# and git push
-pushd $TARGET
-git add -A .
-git commit -m "updated root docs for version $BV"
-git push
-popd
-
-
-// END
+Docs release instructions can be found at:
+http://brooklyncentral.github.io/dev/tips/release.html

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/bd0e1e07/docs/use/guide/locations/index.md
----------------------------------------------------------------------
diff --git a/docs/use/guide/locations/index.md b/docs/use/guide/locations/index.md
index 9570aa4..1c0668e 100644
--- a/docs/use/guide/locations/index.md
+++ b/docs/use/guide/locations/index.md
@@ -11,9 +11,11 @@ These can be clouds (public or private), fixed infrastructure environments, or y
 
 Brooklyn looks for Location configuration in `~/.brooklyn/brooklyn.properties`.
 
-### Must have an SSH key
+## Setting up an SSH key
 
-To access any locations, Brooklyn must have access to an SSH key. By default Brooklyn looks for a key at `~/.ssh/id_rsa` and `~/.ssh/id_dsa`.
+While some locations can be accessed using *user:password* credentials it is more common to use authentication keys.
+
+To use keyfile based authentication, Brooklyn requires that the management machine has an SSH key. By default Brooklyn looks for a key at `~/.ssh/id_rsa` and `~/.ssh/id_dsa`.
 
 If you do not already have an SSH key installed, create a new id_rsa key:
 
@@ -28,60 +30,67 @@ that has a passphrase, or a location other than `~/.ssh`, you can specify this i
 
 ## Localhost
 
-To allow Brooklyn to access locahost the SSH key must be added to the `authorized_keys` on that machine.
+Brooklyn can access localhost if there is an SSH key on the machine and if the SSH key has been added to the list of  `authorized_keys` on that machine.
 
 {% highlight bash %}
 # _Appends_ id_rsa.pub to authorized_keys. Other keys are unaffected.
 $ cat ~/.ssh/id_rsa.pub >> ~/.ssh/authorized_keys
 {% endhighlight %}
 
-(MacOS user?: In addition to the above, enable 'Remote Login' in System Preferences >
- Sharing.)
+MacOS user? In addition to the above, enable 'Remote Login' in System Preferences >
+ Sharing.
 
 
 ## Cloud Endpoints (via jclouds)
 
-[Apache jclouds](http://www.jclouds.org) is a multi-cloud library that Brooklyn uses to access [many clouds](http://www.jclouds.org/documentation/reference/supported-providers/).
+[Apache jclouds](http://www.jclouds.org) is a multi-cloud library that Brooklyn uses to access many clouds. The [full list of supported providers](http://jclouds.apache.org/reference/providers/) is available on jclouds.apache.org.
+
+Add your cloud provider's (API) credentials to `brooklyn.properties` and create an SSH key on the management machine.
+
+Some clouds provide both API keys and SSH keys. In this case add only the API credentials to `brooklyn.properties`. (jclouds will transparently use the API credentials to setup access using the management machine's SSH key.)
 
 ### Example: AWS Virginia Large Centos
 
 {% highlight bash %}
+## Snippet from ~/.brooklyn/brooklyn.properties.
+
 # Provide jclouds with AWS API credentials.
-brooklyn.jclouds.aws-ec2.identity = AKA_YOUR_ACCESS_KEY_ID
-brooklyn.jclouds.aws-ec2.credential = YourSecretKeyWhichIsABase64EncodedString
+brooklyn.location.jclouds.aws-ec2.identity = AKA_YOUR_ACCESS_KEY_ID
+brooklyn.location.jclouds.aws-ec2.credential = YourSecretKeyWhichIsABase64EncodedString
 
 # Name this location 'AWS Virginia Large Centos' and wire to AWS US-East-1
 brooklyn.location.named.AWS\ Virginia\ Large\ Centos = jclouds:aws-ec2:us-east-1
 
-# Specify image, user and minimum ram size (ie instance size)
+# (Using the same name) specify image, user and minimum ram size (ie instance size)
 brooklyn.location.named.AWS\ Virginia\ Large\ Centos.imageId=us-east-1/ami-7d7bfc14
 brooklyn.location.named.AWS\ Virginia\ Large\ Centos.user=root
 brooklyn.location.named.AWS\ Virginia\ Large\ Centos.minRam=4096
 
-# Snippet from ~/.brooklyn/brooklyn.properties.
+
 {% endhighlight %}
 
-This will  appear as 'AWS Virginia Large Centos' in the web console, but will need to be escaped on the command line:  `AWS\ Virginia\ Large\ Centos`.
+This will  appear as 'AWS Virginia Large Centos' in the web console, but will need to be escaped on the command line as:  `AWS\ Virginia\ Large\ Centos`.
 
 See the Getting Started [template brooklyn.properties](/use/guide/quickstart/brooklyn.properties) for more examples of using cloud endpoints.
 
 
 ## Fixed Infrastructure
 
-Bring-ing your own nodes (BYON) to Brooklyn is straightforward.
+Bringing your own nodes (BYON) to Brooklyn is straightforward.
 
 You will need the IP addresses of the nodes and the access credentials. Both SSH and password based login are supported.
 
 ### Example: On-Prem Iron
 
 {% highlight bash %}
+## Snippet from ~/.brooklyn/brooklyn.properties.
+
 # Use the byon prefix, and provide the IP addresss (or IP ranges)
 brooklyn.location.named.On-Prem\ Iron\ Example=byon:(hosts="10.9.1.1,10.9.1.2,produser2@10.9.2.{10,11,20-29}")
 brooklyn.location.named.On-Prem\ Iron\ Example.user=produser1
 brooklyn.location.named.On-Prem\ Iron\ Example.privateKeyFile=~/.ssh/produser_id_rsa
 brooklyn.location.named.On-Prem\ Iron\ Example.privateKeyPassphrase=s3cr3tpassphrase
 
-# Snippet from ~/.brooklyn/brooklyn.properties.
 {% endhighlight %}
 
 

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/bd0e1e07/docs/use/guide/quickstart/brooklyn.properties
----------------------------------------------------------------------
diff --git a/docs/use/guide/quickstart/brooklyn.properties b/docs/use/guide/quickstart/brooklyn.properties
index 53b479a..08a9d7c 100644
--- a/docs/use/guide/quickstart/brooklyn.properties
+++ b/docs/use/guide/quickstart/brooklyn.properties
@@ -6,22 +6,13 @@
 
 # It's great to have you here.
 
-# Getting Started options have been pulled to the top. They are repeated further down.
-# When you are happy with what Brooklyn does, and how to use it, you can delete the
-# Getting Started Section completely, and use the full options below to setup your 
-# configuration.
-
-# (There's a formatting guide at the very bottom.)
+# Getting Started options have been pulled to the top. There's a formatting guide at the
+# very bottom.
 
 ############################ Getting Started Options  ####################################
 
-# By default we have AWS and Rackspace (non-UK) set up (but with invalid credentials!)
-# For each of those, either set the credentials immediately below
-# or remove the corresponding "location.named" lines far below 
-# (i.e. look for  brooklyn.location.named...=...<aws>..  or =...<cloudservers>... )
-
-# For other clouds, ADD corresponding identity and credential lines 
-# and enable the "brooklyn.location.named" line(s) setup far below
+# By default we have AWS set up (but with invalid credentials!).  Many, many other
+# providers are supported.
 
 ## Amazon EC2 Credentials
 # These should be an "Access Key ID" and "Secret Access Key" for your account.
@@ -30,18 +21,28 @@
 brooklyn.location.jclouds.aws-ec2.identity = AKA_YOUR_ACCESS_KEY_ID
 brooklyn.location.jclouds.aws-ec2.credential = <access-key-hex-digits>
 
-# Instructions for many other clouds (public and private) are below.
-
 # Beware of trailing spaces in your cloud credentials. This will cause unexpected
 # 401: unauthorized responses.
 
-## SSH key for localhost 
+## Using Other Clouds
+# 1. Cast your eyes down this document to find your preferred cloud in the Named Locations
+#    section, and the examples.
+# 2. Uncomment the relevant line(s) for your provider.
+# 3. ADD  -.identity and -.credential lines for your provider, similar to the AWS ones above,
+#    replacing 'aws-ec2' with jcloud's id for your cloud.
+
+
+## Deploying to Localhost
+## see: brooklyncentral.github.io/use/guide/locations/
+#
 ## ~/.ssh/id_rsa is Brooklyn's default location
-## Passphrases are supported, but not required
 # brooklyn.location.localhost.privateKeyFile = ~/.ssh/id_rsa
+## Passphrases are supported, but not required
 # brooklyn.location.localhost.privateKeyPassphrase = s3cr3tpassphrase
 
-## Geoscaling Service (Used for global web fabric demo) https://www.geoscaling.com/dns2/
+## Geoscaling Service - used for the Global Web Fabric demo
+## see: brooklyncentral.github.io/use/examples/global-web-fabric/ and
+## https://www.geoscaling.com/dns2/
 ## other services may take similar configuration similarly; or can usually be set in YAML
 # brooklyn.geoscaling.username = USERNAME
 # brooklyn.geoscaling.password = PASSWORD
@@ -52,10 +53,9 @@ brooklyn.location.jclouds.aws-ec2.credential = <access-key-hex-digits>
 
 # That's it, although you may want to read through these options...
 
-
 ################################ Brooklyn Options ########################################
 
-## Brooklyn Mgmt Base Directory: specify where mgmt data should be stored on this server; 
+## Brooklyn Management Base Directory: specify where management data should be stored on this server;
 ## ~/.brooklyn/ is the default but you could use something like /opt/brooklyn/state/
 ## (provided this process has write permissions) 
 # brooklyn.base.dir=~/.brooklyn/
@@ -91,11 +91,11 @@ brooklyn.location.jclouds.aws-ec2.credential = <access-key-hex-digits>
 ## many cloud machines don't have sufficient entropy for lots of encrypted networking, so fake it:
 # brooklyn.location.jclouds.installDevUrandom=true
 
-## This sets a property for all AWS machines. Recommended to avoid getting m1.micros !
+## Sets a minimium ram property for all jclouds locations. Recommended to avoid getting m1.micros on AWS!
 brooklyn.location.jclouds.minRam = 2048
 
-## By default it will set up a user with the same name as the user running on the brooklyn server, 
-## but you can force a user here:
+## When setting up a new cloud machine Brooklyn creates a user with the same name as the user running
+## Brooklyn on the management server, but you can force a different user here:
 # brooklyn.location.jclouds.user=brooklyn
 ## And you can force a password or key (by default it will use the keys in ~/.ssh/id_rsa{,.pub}
 # brooklyn.location.jclouds.password=s3cr3t
@@ -103,7 +103,7 @@ brooklyn.location.jclouds.minRam = 2048
 ################################ Named Locations ########################################
 
 # Named locations appear in the web console. If using the command line or YAML it may be 
-# just as easy to use the jclouds:<provider> locations and specify add'l properties there. 
+# just as easy to use the jclouds:<provider> locations and specify additional properties there.
 
 ## Example: AWS Virginia using Rightscale 6.3 64bit Centos AMI and Large Instances
 # brooklyn.location.named.aws-va-centos-large = jclouds:aws-ec2:us-east-1
@@ -125,7 +125,7 @@ brooklyn.location.named.aws-oregon = jclouds:aws-ec2:us-west-2
 brooklyn.location.named.aws-ireland = jclouds:aws-ec2:eu-west-1
 brooklyn.location.named.aws-tokyo = jclouds:aws-ec2:ap-northeast-1
 
-## Similarly, for Google Compute
+## Google Compute
 ## Note at present you have to create and download the P12 key from the Google "APIs & auth -> Registered Apps" interface,
 ## then convert to PEM private key format using  `openssl pkcs12 -in Certificates.p12 -out Certificates.pem -nodes`
 ## then embed that on one line as the 'credential, replacing new lines with \n as below
@@ -146,13 +146,13 @@ brooklyn.location.named.aws-tokyo = jclouds:aws-ec2:ap-northeast-1
 ## gce images often start with iptables turned on; turn it off 
 # brooklyn.location.jclouds.google-compute-engine.stopIptables=true
 
-## Similarly, here are definitions for HP Cloud - also Ubuntu 12.04 LTS
+## HP Cloud - also Ubuntu 12.04 LTS
 ## You specify your HP Credentials like this:
 # brooklyn.location.jclouds.hpcloud-compute.identity = projectname:username
 # brooklyn.location.jclouds.hpcloud-compute.credential = password
 ## where username and password are the same as logging in to the web console, and
 ## projectname can be found here: https://account.hpcloud.com/projects
-#�brooklyn.location.named.HP\ Cloud\ Arizona-1 = jclouds:hpcloud-compute:az-1.region-a.geo-1
+#�brooklyn.location.named.HP\ Cloud\ Arizona-1 = jclouds:hpcloud-compute:az-1.region-a.geo-1
 # brooklyn.location.named.HP\ Cloud\ Arizona-1.imageId = az-1.region-a.geo-1/75845
 # brooklyn.location.named.HP\ Cloud\ Arizona-1.user = ubuntu
 
@@ -172,7 +172,7 @@ brooklyn.location.named.aws-tokyo = jclouds:aws-ec2:ap-northeast-1
 ## Brooklyn uses the jclouds multi-cloud library to access many clouds.
 ## http://www.jclouds.org/documentation/reference/supported-providers/
 
-## Templates for many other clouds, but remember the identity and credentials:
+## Templates for many other clouds, but remember to add identity and credentials:
 
 # brooklyn.location.named.Bluelock = jclouds:bluelock-vcloud-zone01
 
@@ -222,23 +222,23 @@ brooklyn.location.named.aws-tokyo = jclouds:aws-ec2:ap-northeast-1
 
 
 ## Production pool of machines for my application (deploy to named:On-Prem\ Iron\ Example)
-#brooklyn.location.named.On-Prem\ Iron\ Example=byon:(hosts="10.9.1.1,10.9.1.2,produser2@10.9.2.{10,11,20-29}")
-#brooklyn.location.named.On-Prem\ Iron\ Example.user=produser1
-#brooklyn.location.named.On-Prem\ Iron\ Example.privateKeyFile=~/.ssh/produser_id_rsa
-#brooklyn.location.named.On-Prem\ Iron\ Example.privateKeyPassphrase=s3cr3tpassphrase
+# brooklyn.location.named.On-Prem\ Iron\ Example=byon:(hosts="10.9.1.1,10.9.1.2,produser2@10.9.2.{10,11,20-29}")
+# brooklyn.location.named.On-Prem\ Iron\ Example.user=produser1
+# brooklyn.location.named.On-Prem\ Iron\ Example.privateKeyFile=~/.ssh/produser_id_rsa
+# brooklyn.location.named.On-Prem\ Iron\ Example.privateKeyPassphrase=s3cr3tpassphrase
 
-## Various private clouds
+## Various Private Clouds
 
 ## openstack identity and credential are random strings of letters and numbers (TBC - still the case?)
-#brooklyn.location.named.My\ Openstack=jclouds:openstack-nova:https://9.9.9.9:9999/v2.0/
+# brooklyn.location.named.My\ Openstack=jclouds:openstack-nova:https://9.9.9.9:9999/v2.0/
 
 ## cloudstack identity and credential are rather long random strings of letters and numbers
 ## you generate this in the cloudstack gui, under accounts, then "view users", then "generate key"
 ## use the "api key" as the identity and "secret key" as the credential
-#brooklyn.location.named.My\ Cloudstack=jclouds:cloudstack:http://9.9.9.9:9999/client/api/
+# brooklyn.location.named.My\ Cloudstack=jclouds:cloudstack:http://9.9.9.9:9999/client/api/
 
 ## abiquo identity and credential are your login username/passed
-#brooklyn.location.named.My\ Abiquo=jclouds:abiquo:http://demonstration.abiquo.com/api/
+# brooklyn.location.named.My\ Abiquo=jclouds:abiquo:http://demonstration.abiquo.com/api/
 
 ###############################  Formatting Guide  #######################################
 

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/bd0e1e07/docs/use/guide/quickstart/images/add-application-catalog-web-cluster-with-db-large.png
----------------------------------------------------------------------
diff --git a/docs/use/guide/quickstart/images/add-application-catalog-web-cluster-with-db-large.png b/docs/use/guide/quickstart/images/add-application-catalog-web-cluster-with-db-large.png
new file mode 100644
index 0000000..b566b1a
Binary files /dev/null and b/docs/use/guide/quickstart/images/add-application-catalog-web-cluster-with-db-large.png differ

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/bd0e1e07/docs/use/guide/quickstart/images/add-application-catalog-web-cluster-with-db-location-large.png
----------------------------------------------------------------------
diff --git a/docs/use/guide/quickstart/images/add-application-catalog-web-cluster-with-db-location-large.png b/docs/use/guide/quickstart/images/add-application-catalog-web-cluster-with-db-location-large.png
new file mode 100644
index 0000000..05e9b0c
Binary files /dev/null and b/docs/use/guide/quickstart/images/add-application-catalog-web-cluster-with-db-location-large.png differ

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/bd0e1e07/docs/use/guide/quickstart/images/add-application-catalog-web-cluster-with-db-location.png
----------------------------------------------------------------------
diff --git a/docs/use/guide/quickstart/images/add-application-catalog-web-cluster-with-db-location.png b/docs/use/guide/quickstart/images/add-application-catalog-web-cluster-with-db-location.png
new file mode 100644
index 0000000..c13fdd8
Binary files /dev/null and b/docs/use/guide/quickstart/images/add-application-catalog-web-cluster-with-db-location.png differ

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/bd0e1e07/docs/use/guide/quickstart/images/add-application-catalog-web-cluster-with-db.png
----------------------------------------------------------------------
diff --git a/docs/use/guide/quickstart/images/add-application-catalog-web-cluster-with-db.png b/docs/use/guide/quickstart/images/add-application-catalog-web-cluster-with-db.png
new file mode 100644
index 0000000..ebb6f42
Binary files /dev/null and b/docs/use/guide/quickstart/images/add-application-catalog-web-cluster-with-db.png differ

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/bd0e1e07/docs/use/guide/quickstart/images/add-application-modal-yaml.png
----------------------------------------------------------------------
diff --git a/docs/use/guide/quickstart/images/add-application-modal-yaml.png b/docs/use/guide/quickstart/images/add-application-modal-yaml.png
new file mode 100644
index 0000000..c50b7ab
Binary files /dev/null and b/docs/use/guide/quickstart/images/add-application-modal-yaml.png differ

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/bd0e1e07/docs/use/guide/quickstart/images/jboss7-cluster-policies-large.png
----------------------------------------------------------------------
diff --git a/docs/use/guide/quickstart/images/jboss7-cluster-policies-large.png b/docs/use/guide/quickstart/images/jboss7-cluster-policies-large.png
new file mode 100644
index 0000000..3d84477
Binary files /dev/null and b/docs/use/guide/quickstart/images/jboss7-cluster-policies-large.png differ

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/bd0e1e07/docs/use/guide/quickstart/images/jboss7-cluster-policies.png
----------------------------------------------------------------------
diff --git a/docs/use/guide/quickstart/images/jboss7-cluster-policies.png b/docs/use/guide/quickstart/images/jboss7-cluster-policies.png
new file mode 100644
index 0000000..2f85328
Binary files /dev/null and b/docs/use/guide/quickstart/images/jboss7-cluster-policies.png differ

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/bd0e1e07/docs/use/guide/quickstart/images/my-db-activities-large.png
----------------------------------------------------------------------
diff --git a/docs/use/guide/quickstart/images/my-db-activities-large.png b/docs/use/guide/quickstart/images/my-db-activities-large.png
new file mode 100644
index 0000000..c214d9e
Binary files /dev/null and b/docs/use/guide/quickstart/images/my-db-activities-large.png differ

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/bd0e1e07/docs/use/guide/quickstart/images/my-db-activities.png
----------------------------------------------------------------------
diff --git a/docs/use/guide/quickstart/images/my-db-activities.png b/docs/use/guide/quickstart/images/my-db-activities.png
new file mode 100644
index 0000000..0f2327c
Binary files /dev/null and b/docs/use/guide/quickstart/images/my-db-activities.png differ

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/bd0e1e07/docs/use/guide/quickstart/images/my-web-cluster-starting.png
----------------------------------------------------------------------
diff --git a/docs/use/guide/quickstart/images/my-web-cluster-starting.png b/docs/use/guide/quickstart/images/my-web-cluster-starting.png
new file mode 100644
index 0000000..c389b0b
Binary files /dev/null and b/docs/use/guide/quickstart/images/my-web-cluster-starting.png differ

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/bd0e1e07/docs/use/guide/quickstart/images/my-web-cluster-stop-confirm-large.png
----------------------------------------------------------------------
diff --git a/docs/use/guide/quickstart/images/my-web-cluster-stop-confirm-large.png b/docs/use/guide/quickstart/images/my-web-cluster-stop-confirm-large.png
new file mode 100644
index 0000000..c9bdab6
Binary files /dev/null and b/docs/use/guide/quickstart/images/my-web-cluster-stop-confirm-large.png differ

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/bd0e1e07/docs/use/guide/quickstart/images/my-web-cluster-stop-confirm.png
----------------------------------------------------------------------
diff --git a/docs/use/guide/quickstart/images/my-web-cluster-stop-confirm.png b/docs/use/guide/quickstart/images/my-web-cluster-stop-confirm.png
new file mode 100644
index 0000000..179b00a
Binary files /dev/null and b/docs/use/guide/quickstart/images/my-web-cluster-stop-confirm.png differ

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/bd0e1e07/docs/use/guide/quickstart/images/my-web-summary-large.png
----------------------------------------------------------------------
diff --git a/docs/use/guide/quickstart/images/my-web-summary-large.png b/docs/use/guide/quickstart/images/my-web-summary-large.png
new file mode 100644
index 0000000..fc4bffe
Binary files /dev/null and b/docs/use/guide/quickstart/images/my-web-summary-large.png differ

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/bd0e1e07/docs/use/guide/quickstart/images/my-web-summary.png
----------------------------------------------------------------------
diff --git a/docs/use/guide/quickstart/images/my-web-summary.png b/docs/use/guide/quickstart/images/my-web-summary.png
new file mode 100644
index 0000000..e85752f
Binary files /dev/null and b/docs/use/guide/quickstart/images/my-web-summary.png differ

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/bd0e1e07/docs/use/guide/quickstart/images/my-web.png
----------------------------------------------------------------------
diff --git a/docs/use/guide/quickstart/images/my-web.png b/docs/use/guide/quickstart/images/my-web.png
new file mode 100644
index 0000000..2bd6ac3
Binary files /dev/null and b/docs/use/guide/quickstart/images/my-web.png differ

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/bd0e1e07/docs/use/guide/quickstart/index.md
----------------------------------------------------------------------
diff --git a/docs/use/guide/quickstart/index.md b/docs/use/guide/quickstart/index.md
index 35db7f3..289acd8 100644
--- a/docs/use/guide/quickstart/index.md
+++ b/docs/use/guide/quickstart/index.md
@@ -7,30 +7,12 @@ categories: [use, guide]
 
 {% include fields.md %}
 
-This guide will walk you through deploying an application to a public cloud, and managing that application.
+This guide will walk you through deploying an application to a public cloud.
 
 We will be deploying an example 3-tier web application, described using this blueprint: 
 
 {% highlight yaml %}
-name: My Web Cluster
-location: localhost
-
-services:
-
-- serviceType: brooklyn.entity.webapp.ControlledDynamicWebAppCluster
-  name: My Web
-  location: localhost
-  brooklyn.config:
-    wars.root: http://search.maven.org/remotecontent?filepath=io/brooklyn/example/brooklyn-example-hello-world-sql-webapp/0.6.0-M2/brooklyn-example-hello-world-sql-webapp-0.6.0-M2.war
-    java.sysprops: 
-      brooklyn.example.db.url: $brooklyn:formatString("jdbc:%s%s?user=%s\\&password=%s",
-         component("db").attributeWhenReady("database.url"), "visitors", "brooklyn", "br00k11n")
-
-- serviceType: brooklyn.entity.database.mysql.MySqlNode
-  id: db
-  name: My DB
-  brooklyn.config:
-    creationScriptUrl: classpath://visitors-creation-script.sql
+{% readj my-web-cluster.yaml %}
 {% endhighlight %}
 
 (This is written in YAML, following the [camp specification](https://www.oasis-open.org/committees/camp/). )
@@ -58,12 +40,14 @@ $ tar -zxf brooklyn-dist-{{ site.brooklyn-version }}-dist.tar.gz
 
 This will create a `brooklyn-{{ site.brooklyn-version }}` folder.
 
-Note: you'll also need Java JRE or SDK installed (version 6 or later).
+Note: You'll need a Java JRE or SDK installed (version 6 or later), as Brooklyn is Java under the covers.
 
 ## Launch Brooklyn
 
 Let's setup some paths for easy commands.
 
+(Click the clipboard on these code snippets for easier c&p.)
+
 {% highlight bash %}
 $ cd brooklyn-{{ site.brooklyn-version }}
 $ BROOKLYN_DIR="$(pwd)"
@@ -78,7 +62,10 @@ $ brooklyn launch
 
 Brooklyn will output the address of the management interface:
 
-`... Started Brooklyn console at http://127.0.0.1:8081/` ([link](http://127.0.0.1:8081/))
+
+`INFO  Starting brooklyn web-console on loopback interface because no security config is set`
+
+`INFO  Started Brooklyn console at http://127.0.0.1:8081/, running classpath://brooklyn.war and []`
 
 But before we really use Brooklyn, we need to setup some Locations.
  
@@ -86,19 +73,23 @@ Stop Brooklyn with ctrl-c.
 
 ## Configuring a Location
 
-Brooklyn deploys applications to Locations. Locations can be clouds, machines with fixed IPs or localhost (for testing).
+Brooklyn deploys applications to Locations.
+
+Locations can be clouds, machines with fixed IPs or localhost (for testing).
 
 Brooklyn loads Location configuration  from `~/.brooklyn/brooklyn.properties`. 
 
-Create a `.brooklyn` folder in your home directory:
+Create a `.brooklyn` folder in your home directory and download the template [brooklyn.properties](brooklyn.properties) to that folder.
 
 {% highlight bash %}
 $ mkdir ~/.brooklyn
+$ cd ~/.brooklyn
+$ wget {{site.url}}/use/guide/quickstart/brooklyn.properties
 {% endhighlight %}
 
-Download the template [brooklyn.properties](brooklyn.properties)  and place this in `~/.brooklyn`.  
+Open brooklyn.properties in a text editor and add your cloud credentials.
 
-Open the file in a text editor and add your cloud credentials. If you would rather test Brooklyn on localhost, follow [these instructions](/use/guide/locations/) to ensure that your Brooklyn can access your machine.
+If you would rather test Brooklyn on localhost, follow [these instructions]({{site.url}}/use/guide/locations/) to ensure that your Brooklyn can access your machine.
 
 Restart Brooklyn:
 
@@ -108,66 +99,83 @@ $ brooklyn launch
 
 ## Launching an Application
 
-There are several ways to deploy a YAML blueprint:
+There are several ways to deploy a YAML blueprint (including specifying the blueprint on the command line or submitting it via the REST API).
 
-1. We can supply a blueprint file at startup: `brooklyn launch --app /path/to/myblueprint.yaml`
-1. We can deploy using the web-console.
-1. We can deploy using the brooklyn REST api.
+For now, we will simply copy-and-paste the raw YAML blueprint into the web console.
 
-We will use the second option to deploy a 3-tier web-app, using the YAML file at the top of this page.
+Open the web console ([127.0.0.1:8081](http://127.0.0.1:8081)). As Brooklyn is not currently managing any applications the 'Create Application' dialog opens automatically. Select the YAML tab.
 
-On the home page of the Brooklyn web-console, click the "add application" button (if no applications are currently running, this will be opened automatically). Select the YAML tab and paste your YAML code.
+![Brooklyn web console, showing the YAML tab of the Add Application dialog.](images/add-application-modal-yaml.png)
 
-### Chose your cloud / location
 
-Edit the yaml to use the location you configured, e.g. replace:
+### Chose your Cloud / Location
+
+Edit the 'location' parameter in the YAML template (repeated below) to use the location you configured.
+
+For example, replace:
 {% highlight yaml %}
-location: localhost
+location: location
 {% endhighlight %}
 
-with:
+with (one of):
 {% highlight yaml %}
+location: aws-ec2:us-east-1
+location: rackspace-cloudservers-us:ORD
 location: google-compute-engine:europe-west1-a
+location: localhost
 {% endhighlight %}
 
-Click "finish". You should see your application listed, with status "STARTING".
+**My Web Cluster Blueprint**
 
-## Monitoring and managing applications
+{% highlight yaml %}
+{% readj my-web-cluster.yaml %}
+{% endhighlight %}
 
-In the Brooklyn web-console clicking on an application listed on the home page, or the Applications tab, will show all the applications currently running.
+Paste the modified YAML into the dialog and click 'Finish'.
+The dialog will close and Brooklyn will begin deploying your application.
 
-We can explore the management hierarchy of an application, which will show us the entities it is composed of. If you have deployed the above YAML, then you'll see a standard 3-tier web-app. Clicking on the ControlledDynamicWebAppCluster will show if the cluster is ready to serve and, when ready, will provide a web address for the front of the loadbalancer.
+Your application will be shown as 'Starting' on the web console's front page.
 
-If the service.isUp, you can view the demo web application in your browser at the webapp.url.
+![My Web Cluster is STARTING.](images/my-web-cluster-starting.png)
 
-Through the Activities tab, you can drill into the activities each entity is doing or has recently done. Click on the task to see its details, and to drill into its "Children Tasks". For example, if you drill into MySqlNode's start operation, you can see the "Start (processes)", then "launch", and then the ssh command used including the stdin, stdout and stderr.
 
+## Monitoring and Managing Applications
 
-## Stopping the application
+Click on the application name, or open the Applications tab.
 
-To stop an application, select the application in the tree view, click on the Effectors tab, and invoke the "Stop" effector. This will cleanly shutdown all components in the application.
+We can explore the management hierarchy of the application, which will show us the entities it is composed of.
 
-### Testing the Policies
+ * My Web Cluster (A `BasicApplication`)
+     * My DB (A `MySqlNode`)
+     * My Web (A `ControlledDynamicWebAppCluster`)
+        * Cluster of JBoss7 Servers (A `DynamicWebAppCluster`)
+        * NginxController (An `NginxController`)
 
-Brooklyn at its heart is a policy driven management plane which can implement business and technical policies.
 
-The Web Cluster with DB demo comes pre-configured with an `AutoScalerPolicy`, attached to
-the cluster of JBoss7 servers and a `targets` policy attached to the loadbalancer. You can
- observe policies this in the management console using the Policy tab of the relevant
- entity (e.g. `DynamicWebAppCluster` shows the `AutoScalerPolicy`.
 
-The cluster autoscaler policy will automatically scale the cluster up or down to be the
-right size for the current load. ('One server' is the minimum size allowed by the policy.)
-The loadbalancer will automatically be updated by the targets policy as the cluster size
-changes.
+Clicking on the 'My Web' entity will show the Summary tab. Here we can see if the cluster is ready to serve and, when ready, grab the web address for the front of the loadbalancer.
+
+![Exploring My Web.](images/my-web.png)
+
+
+The Activity tab allows us to drill down into what activities each entity is currently doing or has recently done. It is possible to drill down to all child tasks, and view the commands issued, and any errors or warnings that occured.
+
+Drill into the 'My DB' start operation. Working down through  'Start (processes)', then 'launch', we can discover the ssh command used including the stdin, stdout and stderr.
+
+[![My DB Activities.](images/my-db-activities.png)](images/my-db-activities-large.png)
+
+
+## Stopping the Application
+
+To stop an application, select the application in the tree view (the top/root entity), click on the Effectors tab, and invoke the 'Stop' effector. This will cleanly shutdown all components in the application and return any cloud machines that were being used.
+
+[![My DB Activities.](images/my-web-cluster-stop-confirm.png)](images/my-web-cluster-stop-confirm-large.png)
 
-Sitting idle, your cluster will only contain one server, but you can check that the policy
-works  using a tool like [jmeter](http://jmeter.apache.org/) pointed at the nginx endpoint
-to create load on the cluster.
 
 ### Next 
 
-The [Elastic Web Cluster Example]({{site.url}}/use/examples/webcluster/index.html) page 
-details how to build the demo application from scratch. It shows how Brooklyn can 
-complement your application with policy driven management, and how an application can be 
-run without using the service catalog.
+So far we have touched on Brooklyn's ability to *deploy* an application blueprint to a cloud provider, but this a very small part of Brooklyn's capabilities!
+
+Brooklyn's real power is in using Policies to automatically *manage* applications. There is also the (very useful) ability to store a catalog of application blueprints, ready to go.
+
+[Getting Started - Policies and Catalogs](policies-and-catalogs.html)

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/bd0e1e07/docs/use/guide/quickstart/my-web-cluster.yaml
----------------------------------------------------------------------
diff --git a/docs/use/guide/quickstart/my-web-cluster.yaml b/docs/use/guide/quickstart/my-web-cluster.yaml
new file mode 100644
index 0000000..bbafa00
--- /dev/null
+++ b/docs/use/guide/quickstart/my-web-cluster.yaml
@@ -0,0 +1,19 @@
+name: My Web Cluster
+location: location
+services:
+
+- serviceType: brooklyn.entity.webapp.ControlledDynamicWebAppCluster
+  name: My Web
+  brooklyn.config:
+    wars.root: http://search.maven.org/remotecontent?filepath=io/brooklyn/example/brooklyn-example-hello-world-sql-webapp/{{ site.brooklyn-version }}/brooklyn-example-hello-world-sql-webapp-{{ site.brooklyn-version }}.war
+    java.sysprops:
+      brooklyn.example.db.url: >
+        $brooklyn:formatString("jdbc:%s%s?user=%s\\&password=%s",
+        component("db").attributeWhenReady("datastore.url"),
+        "visitors", "brooklyn", "br00k11n")
+
+- serviceType: brooklyn.entity.database.mysql.MySqlNode
+  id: db
+  name: My DB
+  brooklyn.config:
+    creationScriptUrl: https://bit.ly/brooklyn-visitors-creation-script
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/bd0e1e07/docs/use/guide/quickstart/policies-and-catalogs.md
----------------------------------------------------------------------
diff --git a/docs/use/guide/quickstart/policies-and-catalogs.md b/docs/use/guide/quickstart/policies-and-catalogs.md
new file mode 100644
index 0000000..efa06ff
--- /dev/null
+++ b/docs/use/guide/quickstart/policies-and-catalogs.md
@@ -0,0 +1,66 @@
+---
+title: Getting Started - Policies and Catalogs
+layout: page
+toc: ../guide_toc.json
+categories: [use, guide]
+---
+
+{% include fields.md %}
+
+In the [previous step](index.html) we downloaded Brooklyn and used it to deploy an application to a cloud, but at its heart Brooklyn is a policy driven *management* plane.
+
+Here we will introduce Polices using a simple demo app, which we will load from a Service Catalog.
+
+## Service Catalogs
+
+Download the template [catalog.xml](catalog.xml) to your `~/.brooklyn/` folder, and relaunch Brooklyn.
+
+{% highlight bash %}
+$ cd ~/.brooklyn
+$ wget {{site.url}}/use/guide/quickstart/catalog.xml
+
+$ brooklyn launch
+{% endhighlight %}
+
+Now when we open the web console, two applications are displayed from the catalog.
+
+Select the 'Demo Web Cluster with DB' and click 'Next'.
+
+[![Viewing Catalog entries in Add Application dialog.](images/add-application-catalog-web-cluster-with-db.png)](add-application-catalog-web-cluster-with-db-largea.png)
+
+Select the Location that Brooklyn should deploy to, and name your application:
+
+[![Selecting a location and application name.](images/add-application-catalog-web-cluster-with-db-location.png)](images/add-application-catalog-web-cluster-with-db-location-large.png)
+
+Click 'Finish' to launch the application as before.
+
+
+### Exploring and Testing Policies
+
+The Demo Web Cluster with DB application is pre-configured with two polices.
+
+The app server cluster has an `AutoScalerPolicy`, and the loadbalancer has a `targets` policy.
+
+Use the Applications tab in the web console to drill down into the Policies section of the ControlledDynamicWebAppCluster's Cluster of JBoss7Servers.
+
+You will see that the `AutoScalerPolicy` is running.
+
+[![Inspecting the jboss7 cluster policies.](images/jboss7-cluster-policies.png)](images/jboss7-cluster-policies-large.png)
+
+
+This policy automatically scales the cluster up or down to be the right size for the cluster's current load. (One server is the minimum size allowed by the policy.)
+
+The loadbalancer's `targets` policy ensures that the loadbalancer is updated as the cluster size changes.
+
+Sitting idle, this cluster will only contain one server, but you can use a tool like [jmeter](http://jmeter.apache.org/) pointed at the nginx endpoint to create load on the cluster. (Download a [jmeter test plan](https://github.com/brooklyncentral/brooklyn/blob/master/examples/simple-web-cluster/resources/jmeter-test-plan.jmx).)
+
+As load is added, Brooklyn requests a new cloud machine, creates a new app server, and adds it to the cluster. As load is removed, servers are removed from the cluster, and the infrastructure is handed back to the cloud.
+
+### Next
+
+The [Elastic Web Cluster Example]({{site.url}}/use/examples/webcluster/index.html) page
+details how to build this demo application from scratch in Java. It shows in more detail how Brooklyn can
+complement your application with policy driven management, and how applications can be
+run from the command line.
+
+

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/bd0e1e07/docs/use/guide/quickstart/toc.json
----------------------------------------------------------------------
diff --git a/docs/use/guide/quickstart/toc.json b/docs/use/guide/quickstart/toc.json
new file mode 100644
index 0000000..d65eddb
--- /dev/null
+++ b/docs/use/guide/quickstart/toc.json
@@ -0,0 +1,4 @@
+[{ "title": "Download & Deploy",
+  "file":  "{{ site.url }}/use/guide/quickstart/index.html" },
+{ "title": "Policies & Catalogs",
+  "file":  "{{ site.url }}/use/guide/quickstart/policies-and-catalogs.html" }]

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/bd0e1e07/docs/use/guide/toc.json
----------------------------------------------------------------------
diff --git a/docs/use/guide/toc.json b/docs/use/guide/toc.json
index 8bdb955..7c4aa13 100644
--- a/docs/use/guide/toc.json
+++ b/docs/use/guide/toc.json
@@ -1,12 +1,15 @@
 [
 { "title": "Quick Start",
-  "file":  "{{ site.url }}/use/guide/quickstart/index.html" }, 
+  "file":  "{{ site.url }}/use/guide/quickstart/index.html",
+   "children": {% readj ./quickstart/toc.json %} },
 { "title": "Defining Applications",
   "file":  "{{ site.url }}/use/guide/defining-applications/basic-concepts.html", 
   "children": {% readj ./defining-applications/toc.json %} },
 { "title": "Management",
   "file":  "{{ site.url }}/use/guide/management/index.html" ,
   "children": {% readj ./management/toc.json %} },
+{ "title": "Locations",
+  "file":  "{{ site.url }}/use/guide/locations/index.html" },
 { "title": "Policies",
   "file":  "{{ site.url }}/use/guide/policies/index.html",
   "children": {% readj ./policies/toc.json %} },


[29/50] [abbrv] git commit: Merge pull request #1398 from aledsage/refactor/DynamicClusterTest-from-groovy-to-java

Posted by ri...@apache.org.
Merge pull request #1398 from aledsage/refactor/DynamicClusterTest-from-groovy-to-java

Refactor DynamicClusterTest from groovy to java (and tidies)

Project: http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/commit/cb2d0d3a
Tree: http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/tree/cb2d0d3a
Diff: http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/diff/cb2d0d3a

Branch: refs/pull/1410/merge
Commit: cb2d0d3a184095b4bfdefe73a95435f4e4beb906
Parents: 48a34e4 b0e541e
Author: Andrew Kennedy <gr...@apache.org>
Authored: Fri May 23 17:18:40 2014 +0100
Committer: Andrew Kennedy <gr...@apache.org>
Committed: Fri May 23 17:18:40 2014 +0100

----------------------------------------------------------------------
 .../entity/group/DynamicClusterTest.groovy      | 726 -----------------
 .../entity/group/DynamicClusterTest.java        | 790 +++++++++++++++++++
 2 files changed, 790 insertions(+), 726 deletions(-)
----------------------------------------------------------------------



[35/50] [abbrv] git commit: Merge pull request #1385 from Nakomis/abstract-membership-tracking-policy-ignore-duplicates

Posted by ri...@apache.org.
Merge pull request #1385 from Nakomis/abstract-membership-tracking-policy-ignore-duplicates

Added NOTIFY_ON_DUPLICATES to AbstractMembershipTrackingPolicy

Project: http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/commit/1c9ae924
Tree: http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/tree/1c9ae924
Diff: http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/diff/1c9ae924

Branch: refs/pull/1410/merge
Commit: 1c9ae9245088e6904c4ed66ec1f592e2588e6f8e
Parents: cb2d0d3 6f33889
Author: Andrew Kennedy <gr...@apache.org>
Authored: Fri May 23 17:20:05 2014 +0100
Committer: Andrew Kennedy <gr...@apache.org>
Committed: Fri May 23 17:20:05 2014 +0100

----------------------------------------------------------------------
 .../group/AbstractMembershipTrackingPolicy.java | 77 ++++++++++++++------
 .../group/MembershipTrackingPolicyTest.java     | 39 +++++++++-
 .../brooklyn/util/collections/MutableSet.java   |  2 +
 3 files changed, 95 insertions(+), 23 deletions(-)
----------------------------------------------------------------------



[32/50] [abbrv] git commit: Merge pull request #1398 from aledsage/refactor/DynamicClusterTest-from-groovy-to-java

Posted by ri...@apache.org.
Merge pull request #1398 from aledsage/refactor/DynamicClusterTest-from-groovy-to-java

Refactor DynamicClusterTest from groovy to java (and tidies)

Project: http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/commit/cb2d0d3a
Tree: http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/tree/cb2d0d3a
Diff: http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/diff/cb2d0d3a

Branch: refs/pull/1408/merge
Commit: cb2d0d3a184095b4bfdefe73a95435f4e4beb906
Parents: 48a34e4 b0e541e
Author: Andrew Kennedy <gr...@apache.org>
Authored: Fri May 23 17:18:40 2014 +0100
Committer: Andrew Kennedy <gr...@apache.org>
Committed: Fri May 23 17:18:40 2014 +0100

----------------------------------------------------------------------
 .../entity/group/DynamicClusterTest.groovy      | 726 -----------------
 .../entity/group/DynamicClusterTest.java        | 790 +++++++++++++++++++
 2 files changed, 790 insertions(+), 726 deletions(-)
----------------------------------------------------------------------



[07/50] [abbrv] git commit: Deletes nested DynamicClusterTest.FailingEntity

Posted by ri...@apache.org.
Deletes nested DynamicClusterTest.FailingEntity

- use instead brooklyn.entity.trait.FailingEntity


Project: http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/commit/b0e541e4
Tree: http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/tree/b0e541e4
Diff: http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/diff/b0e541e4

Branch: refs/heads/master
Commit: b0e541e487af240c698e46f314c9a8271e7bc446
Parents: d52e7ed
Author: Aled Sage <al...@gmail.com>
Authored: Wed May 21 12:18:25 2014 +0100
Committer: Aled Sage <al...@gmail.com>
Committed: Wed May 21 15:52:42 2014 +0100

----------------------------------------------------------------------
 .../entity/group/DynamicClusterTest.java        | 101 +++++++------------
 1 file changed, 38 insertions(+), 63 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/b0e541e4/core/src/test/java/brooklyn/entity/group/DynamicClusterTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/brooklyn/entity/group/DynamicClusterTest.java b/core/src/test/java/brooklyn/entity/group/DynamicClusterTest.java
index 9fb9230..a59079d 100644
--- a/core/src/test/java/brooklyn/entity/group/DynamicClusterTest.java
+++ b/core/src/test/java/brooklyn/entity/group/DynamicClusterTest.java
@@ -34,6 +34,7 @@ import brooklyn.entity.basic.EntityFactory;
 import brooklyn.entity.basic.Lifecycle;
 import brooklyn.entity.proxying.EntitySpec;
 import brooklyn.entity.trait.Changeable;
+import brooklyn.entity.trait.FailingEntity;
 import brooklyn.location.Location;
 import brooklyn.location.basic.SimulatedLocation;
 import brooklyn.management.Task;
@@ -330,7 +331,10 @@ public class DynamicClusterTest {
                 .configure("factory", new EntityFactory() {
                     @Override public Entity newEntity(Map flags, Entity parent) {
                         int num = counter.incrementAndGet();
-                        return new FailingEntity(flags, (num==failNum));
+                        return app.getManagementContext().getEntityManager().createEntity(EntitySpec.create(FailingEntity.class)
+                                .configure(flags)
+                                .configure(FailingEntity.FAIL_ON_START, (num==failNum))
+                                .parent(parent));
                     }}));
 
         cluster.start(ImmutableList.of(loc));
@@ -338,7 +342,7 @@ public class DynamicClusterTest {
         assertEquals(cluster.getCurrentSize(), (Integer)2);
         assertEquals(cluster.getMembers().size(), 2);
         for (Entity member : cluster.getMembers()) {
-            assertFalse(((FailingEntity)member).failOnStart);
+            assertFalse(((FailingEntity)member).getConfig(FailingEntity.FAIL_ON_START));
         }
     }
 
@@ -352,7 +356,10 @@ public class DynamicClusterTest {
                 .configure("factory", new EntityFactory() {
                     @Override public Entity newEntity(Map flags, Entity parent) {
                         int num = counter.incrementAndGet();
-                        return new FailingEntity(flags, (num==failNum));
+                        return app.getManagementContext().getEntityManager().createEntity(EntitySpec.create(FailingEntity.class)
+                                .configure(flags)
+                                .configure(FailingEntity.FAIL_ON_START, (num==failNum))
+                                .parent(parent));
                     }}));
 
         cluster.start(ImmutableList.of(loc));
@@ -361,7 +368,7 @@ public class DynamicClusterTest {
         assertEquals(cluster.getCurrentSize(), (Integer)1);
         assertEquals(cluster.getMembers().size(), 1);
         for (Entity member : cluster.getMembers()) {
-            assertFalse(((FailingEntity)member).failOnStart);
+            assertFalse(((FailingEntity)member).getConfig(FailingEntity.FAIL_ON_START));
         }
     }
 
@@ -374,7 +381,10 @@ public class DynamicClusterTest {
                 .configure("factory", new EntityFactory() {
                     @Override public Entity newEntity(Map flags, Entity parent) {
                         int num = counter.incrementAndGet();
-                        return new FailingEntity(flags, (num==failNum));
+                        return app.getManagementContext().getEntityManager().createEntity(EntitySpec.create(FailingEntity.class)
+                                .configure(flags)
+                                .configure(FailingEntity.FAIL_ON_START, (num==failNum))
+                                .parent(parent));
                     }}));
 
         try {
@@ -392,7 +402,7 @@ public class DynamicClusterTest {
         assertEquals(cluster.getCurrentSize(), (Integer)1);
         assertEquals(cluster.getMembers().size(), 1);
         for (Entity member : cluster.getMembers()) {
-            assertFalse(((FailingEntity)member).failOnStart);
+            assertFalse(((FailingEntity)member).getConfig(FailingEntity.FAIL_ON_START));
         }
     }
 
@@ -406,7 +416,10 @@ public class DynamicClusterTest {
                 .configure("factory", new EntityFactory() {
                     @Override public Entity newEntity(Map flags, Entity parent) {
                         int num = counter.incrementAndGet();
-                        return new FailingEntity(flags, (num==failNum));
+                        return app.getManagementContext().getEntityManager().createEntity(EntitySpec.create(FailingEntity.class)
+                                .configure(flags)
+                                .configure(FailingEntity.FAIL_ON_START, (num==failNum))
+                                .parent(parent));
                     }}));
 
         cluster.start(ImmutableList.of(loc));
@@ -414,13 +427,13 @@ public class DynamicClusterTest {
         assertEquals(cluster.getCurrentSize(), (Integer)2);
         assertEquals(cluster.getMembers().size(), 2);
         assertEquals(Iterables.size(Iterables.filter(cluster.getChildren(), Predicates.instanceOf(FailingEntity.class))), 3);
-        for (Entity it : cluster.getMembers()) {
-            assertFalse(((FailingEntity)it).failOnStart);
+        for (Entity member : cluster.getMembers()) {
+            assertFalse(((FailingEntity)member).getConfig(FailingEntity.FAIL_ON_START));
         }
 
         assertEquals(cluster.getAttribute(DynamicCluster.QUARANTINE_GROUP).getMembers().size(), 1);
-        for (Entity it : cluster.getAttribute(DynamicCluster.QUARANTINE_GROUP).getMembers()) {
-            assertTrue(((FailingEntity)it).failOnStart);
+        for (Entity member : cluster.getAttribute(DynamicCluster.QUARANTINE_GROUP).getMembers()) {
+            assertTrue(((FailingEntity)member).getConfig(FailingEntity.FAIL_ON_START));
         }
     }
 
@@ -435,7 +448,10 @@ public class DynamicClusterTest {
                 .configure("factory", new EntityFactory() {
                     @Override public Entity newEntity(Map flags, Entity parent) {
                         int num = counter.incrementAndGet();
-                        return new FailingEntity(flags, (num==failNum));
+                        return app.getManagementContext().getEntityManager().createEntity(EntitySpec.create(FailingEntity.class)
+                                .configure(flags)
+                                .configure(FailingEntity.FAIL_ON_START, (num==failNum))
+                                .parent(parent));
                     }}));
 
         cluster.start(ImmutableList.of(loc));
@@ -452,14 +468,12 @@ public class DynamicClusterTest {
         // Failed node will not be managed either
         assertEquals(Iterables.size(Iterables.filter(cluster.getChildren(), Predicates.instanceOf(FailingEntity.class))), 2);
         for (Entity member : cluster.getMembers()) {
-            assertFalse(((FailingEntity)member).failOnStart);
+            assertFalse(((FailingEntity)member).getConfig(FailingEntity.FAIL_ON_START));
         }
     }
 
     @Test
     public void defaultRemovalStrategyShutsDownNewestFirstWhenResizing() throws Exception {
-        TestEntity entity;
-        final int failNum = 2;
         final List<Entity> creationOrder = Lists.newArrayList();
         DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
                 .configure("initialSize", 0)
@@ -709,7 +723,10 @@ public class DynamicClusterTest {
                 .configure("factory", new EntityFactory() {
                     @Override public Entity newEntity(Map flags, Entity parent) {
                         int num = counter.incrementAndGet();
-                        return new FailingEntity(flags, (num==failNum));
+                        return app.getManagementContext().getEntityManager().createEntity(EntitySpec.create(FailingEntity.class)
+                                .configure(flags)
+                                .configure(FailingEntity.FAIL_ON_START, (num==failNum))
+                                .parent(parent));
                     }}));
 
         cluster.start(ImmutableList.of(loc));
@@ -734,7 +751,10 @@ public class DynamicClusterTest {
                 .configure("factory", new EntityFactory() {
                     @Override public Entity newEntity(Map flags, Entity parent) {
                         int num = counter.incrementAndGet();
-                        return new FailingEntity(flags, false, (num==failNum), IllegalStateException.class);
+                        return app.getManagementContext().getEntityManager().createEntity(EntitySpec.create(FailingEntity.class)
+                                .configure(flags)
+                                .configure(FailingEntity.FAIL_ON_STOP, (num==failNum))
+                                .parent(parent));
                     }}));
 
         cluster.start(ImmutableList.of(loc));
@@ -767,49 +787,4 @@ public class DynamicClusterTest {
             return e;
         }
     }
-
-    public static class FailingEntity extends TestEntityImpl {
-        final boolean failOnStart;
-        final boolean failOnStop;
-        final Class<? extends Exception> exceptionClazz;
-    
-        public FailingEntity(Map flags, boolean failOnStart) {
-            this(flags, failOnStart, false);
-        }
-        
-        public FailingEntity(Map flags, boolean failOnStart, boolean failOnStop) {
-            this(flags, failOnStart, failOnStop, IllegalStateException.class);
-        }
-        
-        public FailingEntity(Map flags, boolean failOnStart, boolean failOnStop, Class<? extends Exception> exceptionClazz) {
-            super(flags);
-            this.failOnStart = failOnStart;
-            this.failOnStop = failOnStop;
-            this.exceptionClazz = exceptionClazz;
-        }
-        
-        @Override
-        public void start(Collection<? extends Location> locs) {
-            if (failOnStart) {
-                try {
-                    Exception e = exceptionClazz.getConstructor(String.class).newInstance("Simulating entity start failure for test");
-                    throw e;
-                } catch (Exception e) {
-                    throw Exceptions.propagate(e);
-                }
-            }
-        }
-        
-        @Override
-        public void stop() {
-            if (failOnStop) {
-                try {
-                    Exception e = exceptionClazz.getConstructor(String.class).newInstance("Simulating entity stop failure for test");
-                    throw e;
-                } catch (Exception e) {
-                    throw Exceptions.propagate(e);
-                }
-            }
-        }
-    }
-}
\ No newline at end of file
+}


[03/50] [abbrv] git commit: Covert DynamicClusterTest from groovy to java

Posted by ri...@apache.org.
Covert DynamicClusterTest from groovy to java


Project: http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/commit/d52e7ed2
Tree: http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/tree/d52e7ed2
Diff: http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/diff/d52e7ed2

Branch: refs/pull/1411/merge
Commit: d52e7ed2fe0c2aa623bcacee6dd4f3638e2c5647
Parents: d3d5c11
Author: Aled Sage <al...@gmail.com>
Authored: Wed May 21 12:07:53 2014 +0100
Committer: Aled Sage <al...@gmail.com>
Committed: Wed May 21 15:52:41 2014 +0100

----------------------------------------------------------------------
 .../entity/group/DynamicClusterTest.groovy      | 726 -----------------
 .../entity/group/DynamicClusterTest.java        | 815 +++++++++++++++++++
 2 files changed, 815 insertions(+), 726 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/d52e7ed2/core/src/test/java/brooklyn/entity/group/DynamicClusterTest.groovy
----------------------------------------------------------------------
diff --git a/core/src/test/java/brooklyn/entity/group/DynamicClusterTest.groovy b/core/src/test/java/brooklyn/entity/group/DynamicClusterTest.groovy
deleted file mode 100644
index 636abbc..0000000
--- a/core/src/test/java/brooklyn/entity/group/DynamicClusterTest.groovy
+++ /dev/null
@@ -1,726 +0,0 @@
-package brooklyn.entity.group
-
-import brooklyn.entity.basic.Attributes
-import brooklyn.entity.basic.Lifecycle
-
-import static org.testng.Assert.*
-
-import java.util.concurrent.CopyOnWriteArrayList
-import java.util.concurrent.CountDownLatch
-import java.util.concurrent.ExecutionException
-import java.util.concurrent.ExecutorService
-import java.util.concurrent.Executors
-import java.util.concurrent.TimeUnit
-import java.util.concurrent.atomic.AtomicInteger
-
-import org.testng.annotations.AfterMethod
-import org.testng.annotations.BeforeMethod
-import org.testng.annotations.Test
-
-import brooklyn.entity.Application
-import brooklyn.entity.Entity
-import brooklyn.entity.basic.ApplicationBuilder
-import brooklyn.entity.basic.BrooklynTaskTags
-import brooklyn.entity.basic.Entities
-import brooklyn.entity.proxying.EntitySpec
-import brooklyn.entity.trait.Changeable
-import brooklyn.location.Location
-import brooklyn.location.basic.SimulatedLocation
-import brooklyn.management.Task
-import brooklyn.test.TestUtils
-import brooklyn.test.entity.TestApplication
-import brooklyn.test.entity.TestEntity
-import brooklyn.test.entity.TestEntityImpl
-import brooklyn.util.GroovyJavaMethods
-import brooklyn.util.exceptions.Exceptions
-
-import com.google.common.base.Predicates
-import com.google.common.base.Throwables;
-import com.google.common.collect.ImmutableList
-import com.google.common.collect.ImmutableSet
-import com.google.common.collect.Iterables
-
-
-class DynamicClusterTest {
-
-    private static final int TIMEOUT_MS = 2000
-
-    TestApplication app
-    SimulatedLocation loc
-    SimulatedLocation loc2
-    Random random = new Random()
-
-    @BeforeMethod
-    public void setUp() {
-        app = ApplicationBuilder.newManagedApp(TestApplication.class);
-        loc = new SimulatedLocation()
-        loc2 = new SimulatedLocation()
-    }
-
-    @AfterMethod(alwaysRun = true)
-    public void tearDown(){
-        if (app != null) Entities.destroyAll(app.getManagementContext());
-    }
-
-    @Test
-    public void creationOkayWithoutNewEntityFactoryArgument() {
-        app.createAndManageChild(EntitySpec.create(DynamicCluster.class));
-    }
-
-    @Test
-    public void constructionRequiresThatNewEntityArgumentIsAnEntityFactory() {
-        try {
-            app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
-                    .configure("factory", "error"));
-            fail();
-        } catch (Exception e) {
-            if (Exceptions.getFirstThrowableOfType(e, IllegalArgumentException.class) == null) throw e;
-        }
-    }
-
-    @Test
-    public void startRequiresThatNewEntityArgumentIsGiven() {
-        DynamicCluster c = app.createAndManageChild(EntitySpec.create(DynamicCluster.class));
-        try {
-            c.start([loc]);
-            fail();
-        } catch (Exception e) {
-            if (Exceptions.getFirstThrowableOfType(e, IllegalStateException.class) == null) throw e;
-        }
-    }
-
-    @Test
-    public void startMethodFailsIfLocationsParameterHasMoreThanOneElement() {
-        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
-                .configure("factory", { new TestEntityImpl() }));
-        try {
-            cluster.start([ loc, loc2 ])
-            fail();
-        } catch (Exception e) {
-            if (Exceptions.getFirstThrowableOfType(e, IllegalArgumentException.class) == null) throw e;
-        }
-    }
-
-    @Test
-    public void testClusterHasOneLocationAfterStarting() {
-        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
-                .configure("factory", { new TestEntityImpl() }));
-        cluster.start([loc])
-        assertEquals(cluster.getLocations().size(), 1)
-        assertEquals(cluster.getLocations() as List, [loc])
-    }
-
-    @Test
-    public void testServiceUpAfterStartingWithNoMembers() {
-        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
-                .configure(DynamicCluster.MEMBER_SPEC, EntitySpec.create(TestEntity.class))
-                .configure(DynamicCluster.INITIAL_SIZE, 0))
-        cluster.start([loc])
-        assertEquals(cluster.getAttribute(Attributes.SERVICE_STATE), Lifecycle.RUNNING)
-        assertTrue(cluster.getAttribute(Attributes.SERVICE_UP))
-    }
-
-    @Test
-    public void usingEntitySpecResizeFromZeroToOneStartsANewEntityAndSetsItsParent() {
-        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
-                .configure("memberSpec", EntitySpec.create(TestEntity.class)));
-        
-        cluster.start([loc])
-
-        cluster.resize(1)
-        Entity entity = Iterables.getOnlyElement(cluster.getMembers());
-        assertEquals entity.count, 1
-        assertEquals entity.parent, cluster
-        assertEquals entity.application, app
-    }
-
-    @Test
-    public void resizeFromZeroToOneStartsANewEntityAndSetsItsParent() {
-        TestEntity entity
-        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
-                .configure("factory", { properties -> entity = new TestEntityImpl(properties) }));
-
-        cluster.start([loc])
-
-        cluster.resize(1)
-        assertEquals entity.counter.get(), 1
-        assertEquals entity.parent, cluster
-        assertEquals entity.application, app
-    }
-
-    @Test
-    public void currentSizePropertyReflectsActualClusterSize() {
-        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
-                .configure("factory", { properties -> return new TestEntityImpl(properties) }));
-
-        assertEquals cluster.currentSize, 0
-
-        cluster.start([loc])
-        assertEquals cluster.currentSize, 1
-        assertEquals cluster.getAttribute(Changeable.GROUP_SIZE), 1
-
-        int newSize = cluster.resize(0)
-        assertEquals newSize, 0
-        assertEquals newSize, cluster.currentSize
-        assertEquals newSize, cluster.members.size()
-        assertEquals newSize, cluster.getAttribute(Changeable.GROUP_SIZE)
-
-        newSize = cluster.resize(4)
-        assertEquals newSize, 4
-        assertEquals newSize, cluster.currentSize
-        assertEquals newSize, cluster.members.size()
-        assertEquals newSize, cluster.getAttribute(Changeable.GROUP_SIZE)
-
-        newSize = cluster.resize(0)
-        assertEquals newSize, 0
-        assertEquals newSize, cluster.currentSize
-        assertEquals newSize, cluster.members.size()
-        assertEquals newSize, cluster.getAttribute(Changeable.GROUP_SIZE)
-    }
-
-    @Test
-    public void clusterSizeAfterStartIsInitialSize() {
-        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
-                .configure("factory", { properties -> return new TestEntityImpl(properties) })
-                .configure("initialSize", 2));
-
-        cluster.start([loc])
-        assertEquals cluster.currentSize, 2
-        assertEquals cluster.members.size(), 2
-        assertEquals cluster.getAttribute(Changeable.GROUP_SIZE), 2
-    }
-
-    @Test
-    public void clusterLocationIsPassedOnToEntityStart() {
-        Collection<Location> locations = [ loc ]
-        TestEntity entity
-        def newEntity = { properties, cluster ->
-            entity = new TestEntityImpl(parent:cluster) {
-	            List<Location> stashedLocations = null
-	            @Override
-	            void start(Collection<? extends Location> loc) {
-	                super.start(loc)
-	                stashedLocations = loc
-	            }
-	        }
-        }
-        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
-                .configure("factory", newEntity)
-                .configure("initialSize", 1));
-
-        cluster.start(locations)
-
-        assertNotNull entity.stashedLocations
-        assertEquals entity.stashedLocations.size(), 1
-        assertEquals entity.stashedLocations[0], locations[0]
-    }
-
-    @Test
-    public void resizeFromOneToZeroChangesClusterSize() {
-        TestEntity entity
-        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
-                .configure("factory", { properties -> entity = new TestEntityImpl(properties) })
-                .configure("initialSize", 1));
-
-        cluster.start([loc])
-        assertEquals cluster.currentSize, 1
-        assertEquals entity.counter.get(), 1
-        cluster.resize(0)
-        assertEquals cluster.currentSize, 0
-        assertEquals entity.counter.get(), 0
-    }
-
-    @Test
-    public void concurrentResizesToSameNumberCreatesCorrectNumberOfNodes() {
-        final int OVERHEAD_MS = 500
-        final int STARTUP_TIME_MS = 50
-        final AtomicInteger numStarted = new AtomicInteger(0)
-        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
-                .configure("factory", { 
-                    Map flags, Entity cluster -> 
-                    Thread.sleep(STARTUP_TIME_MS); numStarted.incrementAndGet(); new TestEntityImpl(flags, cluster)
-                }));
-
-        assertEquals cluster.currentSize, 0
-        cluster.start([loc])
-
-        ExecutorService executor = Executors.newCachedThreadPool()
-        List<Throwable> throwables = new CopyOnWriteArrayList<Throwable>()
-
-        try {
-            for (int i in 1..10) {
-                executor.submit( {
-                    try {
-                        cluster.resize(2)
-                    } catch (Throwable e) {
-                        throwables.add(e)
-                    }
-                })
-            }
-
-            executor.shutdown()
-            assertTrue(executor.awaitTermination(10*STARTUP_TIME_MS+OVERHEAD_MS, TimeUnit.MILLISECONDS))
-            if (throwables.size() > 0) throw throwables.get(0)
-            assertEquals(cluster.currentSize, 2)
-            assertEquals(cluster.getAttribute(Changeable.GROUP_SIZE), 2)
-            assertEquals(numStarted.get(), 2)
-        } finally {
-            executor.shutdownNow();
-        }
-    }
-
-    @Test(enabled = false)
-    public void stoppingTheClusterStopsTheEntity() {
-        TestEntity entity
-        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
-                .configure("factory", { properties -> entity = new TestEntityImpl(properties) })
-                .configure("initialSize", 1));
-
-        cluster.start([loc])
-        assertEquals entity.counter.get(), 1
-        cluster.stop()
-        assertEquals entity.counter.get(), 0
-    }
-
-    /**
-     * This tests the fix for ENGR-1826.
-     */
-    @Test
-    public void failingEntitiesDontBreakClusterActions() {
-        final int failNum = 2
-        final AtomicInteger counter = new AtomicInteger(0)
-        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
-                .configure("initialSize", 0)
-                .configure("factory", { properties ->
-                    int num = counter.incrementAndGet();
-                    return new FailingEntity(properties, (num==failNum))
-                }));
-
-        cluster.start([loc])
-        cluster.resize(3)
-        assertEquals(cluster.currentSize, 2)
-        assertEquals(cluster.getMembers().size(), 2)
-        for (Entity member : cluster.getMembers()) {
-            assertFalse(((FailingEntity)member).failOnStart)
-        }
-    }
-
-    @Test
-    public void testInitialQuorumSizeSufficientForStartup() {
-        final int failNum = 1;
-        final AtomicInteger counter = new AtomicInteger(0)
-        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
-                .configure("initialSize", 2)
-                .configure(DynamicCluster.INITIAL_QUORUM_SIZE, 1)
-                .configure("factory", { properties ->
-                    int num = counter.incrementAndGet();
-                    return new FailingEntity(properties, (num==failNum))
-                }));
-
-        cluster.start([loc])
-        
-        // note that children include quarantine group; and quarantined nodes
-        assertEquals(cluster.getCurrentSize(), 1)
-        assertEquals(cluster.getMembers().size(), 1)
-        for (Entity member : cluster.getMembers()) {
-            assertFalse(((FailingEntity)member).failOnStart)
-        }
-    }
-
-    @Test
-    public void testInitialQuorumSizeDefaultsToInitialSize() throws Exception {
-        final int failNum = 1;
-        final AtomicInteger counter = new AtomicInteger(0)
-        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
-                .configure("initialSize", 2)
-                .configure("factory", { properties ->
-                    int num = counter.incrementAndGet();
-                    return new FailingEntity(properties, (num==failNum))
-                }));
-
-        try {
-            cluster.start([loc])
-        } catch (Exception e) {
-            IllegalStateException unwrapped = Exceptions.getFirstThrowableOfType(e, IllegalStateException.class);
-            if (unwrapped != null && unwrapped.getMessage().contains("failed to get to initial size")) {
-                // success
-            } else {
-                throw e; // fail
-            }
-        }
-        
-        // note that children include quarantine group; and quarantined nodes
-        assertEquals(cluster.getCurrentSize(), 1)
-        assertEquals(cluster.getMembers().size(), 1)
-        for (Entity member : cluster.getMembers()) {
-            assertFalse(((FailingEntity)member).failOnStart)
-        }
-    }
-
-    @Test
-    public void testCanQuarantineFailedEntities() {
-        final int failNum = 2
-        final AtomicInteger counter = new AtomicInteger(0)
-        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
-                .configure("quarantineFailedEntities", true)
-                .configure("initialSize", 0)
-                .configure("factory", { properties ->
-                    int num = counter.incrementAndGet();
-                    return new FailingEntity(properties, (num==failNum))
-                }));
-
-        cluster.start([loc])
-        cluster.resize(3)
-        assertEquals(cluster.currentSize, 2)
-        assertEquals(cluster.getMembers().size(), 2)
-        assertEquals(Iterables.size(Iterables.filter(cluster.getChildren(), Predicates.instanceOf(FailingEntity.class))), 3)
-        cluster.members.each {
-            assertFalse(((FailingEntity)it).failOnStart)
-        }
-
-        assertEquals(cluster.getAttribute(DynamicCluster.QUARANTINE_GROUP).members.size(), 1)
-        cluster.getAttribute(DynamicCluster.QUARANTINE_GROUP).members.each {
-            assertTrue(((FailingEntity)it).failOnStart)
-        }
-    }
-
-    @Test
-    public void testDoNotQuarantineFailedEntities() {
-        final int failNum = 2
-        final AtomicInteger counter = new AtomicInteger(0)
-        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
-                // default is quarantineFailedEntities==true
-                .configure("quarantineFailedEntities", false)
-                .configure("initialSize", 0)
-                .configure("factory", { properties ->
-                    int num = counter.incrementAndGet();
-                    return new FailingEntity(properties, (num==failNum))
-                }));
-
-        cluster.start([loc])
-        
-        // no quarantine group, as a child
-        assertEquals(cluster.getChildren().size(), 0, "children="+cluster.getChildren())
-        
-        // Failed node will not be a member or child
-        cluster.resize(3)
-        assertEquals(cluster.currentSize, 2)
-        assertEquals(cluster.getMembers().size(), 2)
-        assertEquals(cluster.getChildren().size(), 2, "children="+cluster.getChildren())
-        
-        // Failed node will not be managed either
-        assertEquals(Iterables.size(Iterables.filter(cluster.getChildren(), Predicates.instanceOf(FailingEntity.class))), 2)
-        for (Entity member : cluster.getMembers()) {
-            assertFalse(((FailingEntity)member).failOnStart)
-        }
-    }
-
-    @Test
-    public void defaultRemovalStrategyShutsDownNewestFirstWhenResizing() {
-        TestEntity entity
-        final int failNum = 2
-        final List<Entity> creationOrder = []
-        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
-                .configure("initialSize", 0)
-                .configure("factory", { properties ->
-                    Entity result = new TestEntityImpl(properties)
-                    creationOrder << result
-                    return result
-                }));
-
-        cluster.start([loc])
-        cluster.resize(1)
-        cluster.resize(2)
-        assertEquals(cluster.currentSize, 2)
-        assertEquals(ImmutableSet.copyOf(cluster.getMembers()), ImmutableSet.copyOf(creationOrder), "actual="+cluster.getMembers())
-
-        // Now stop one
-        cluster.resize(1)
-        assertEquals(cluster.currentSize, 1)
-        assertEquals(ImmutableList.copyOf(cluster.getMembers()), creationOrder.subList(0, 1))
-    }
-
-    @Test
-    public void resizeLoggedAsEffectorCall() {
-        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
-                .configure("factory", { properties -> return new TestEntityImpl(properties) }));
-
-        app.start([loc])
-        cluster.resize(1)
-
-        Set<Task> tasks = app.getManagementContext().getExecutionManager().getTasksWithAllTags([
-            BrooklynTaskTags.tagForContextEntity(cluster),"EFFECTOR"])
-        assertEquals(tasks.size(), 2)
-        assertTrue(Iterables.get(tasks, 0).getDescription().contains("start"))
-        assertTrue(Iterables.get(tasks, 1).getDescription().contains("resize"))
-    }
-
-    @Test
-    public void testStoppedChildIsRemoveFromGroup() {
-        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
-                .configure("initialSize", 1)
-                .configure("factory", { properties -> return new TestEntityImpl(properties) }));
-
-        cluster.start([loc])
-
-        TestEntity child = Iterables.get(cluster.getMembers(), 0);
-        child.stop()
-        Entities.unmanage(child)
-
-        TestUtils.executeUntilSucceeds(timeout:TIMEOUT_MS) {
-            assertFalse(cluster.getChildren().contains(child), "children="+cluster.getChildren())
-            assertEquals(cluster.currentSize, 0)
-            assertEquals(cluster.members.size(), 0)
-        }
-    }
-
-    @Test
-    public void testPluggableRemovalStrategyIsUsed() {
-        List<Entity> removedEntities = []
-
-        Closure removalStrategy = { Collection<Entity> contenders ->
-            Entity choice = Iterables.get(contenders, random.nextInt(contenders.size()))
-            removedEntities.add(choice)
-            return choice
-        }
-        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
-                .configure("factory", { properties -> return new TestEntityImpl(properties) })
-                .configure("initialSize", 10)
-                .configure("removalStrategy", removalStrategy));
-
-        cluster.start([loc])
-        Set origMembers = cluster.members as Set
-
-        for (int i = 10; i >= 0; i--) {
-            cluster.resize(i)
-            assertEquals(cluster.getAttribute(Changeable.GROUP_SIZE), i)
-            assertEquals(removedEntities.size(), 10-i)
-            assertEquals(ImmutableSet.copyOf(Iterables.concat(cluster.members, removedEntities)), origMembers)
-        }
-    }
-
-    @Test
-    public void testPluggableRemovalStrategyCanBeSetAfterConstruction() {
-        List<Entity> removedEntities = []
-
-        Closure removalStrategy = { Collection<Entity> contenders ->
-            Entity choice = Iterables.get(contenders, random.nextInt(contenders.size()))
-            removedEntities.add(choice)
-            return choice
-        }
-        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
-                .configure("factory", { properties -> return new TestEntityImpl(properties) })
-                .configure("initialSize", 10));
-
-        cluster.start([loc])
-        Set origMembers = cluster.members as Set
-
-        cluster.setRemovalStrategy(GroovyJavaMethods.functionFromClosure(removalStrategy));
-
-        for (int i = 10; i >= 0; i--) {
-            cluster.resize(i)
-            assertEquals(cluster.getAttribute(Changeable.GROUP_SIZE), i)
-            assertEquals(removedEntities.size(), 10-i)
-            assertEquals(ImmutableSet.copyOf(Iterables.concat(cluster.members, removedEntities)), origMembers)
-        }
-    }
-
-    @Test
-    public void testResizeDoesNotBlockCallsToQueryGroupMembership() {
-        CountDownLatch executingLatch = new CountDownLatch(1)
-        CountDownLatch continuationLatch = new CountDownLatch(1)
-        
-        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
-                .configure("initialSize", 0)
-                .configure("factory", { properties ->
-                        executingLatch.countDown()
-                        continuationLatch.await()
-                        return new TestEntityImpl(properties)
-                    }));
-
-        cluster.start([loc])
-
-        Thread thread = new Thread( { cluster.resize(1) })
-        try {
-            // wait for resize to be executing
-            thread.start()
-            executingLatch.await(TIMEOUT_MS, TimeUnit.MILLISECONDS)
-
-            // ensure can still call methods on group, to query/update membership
-            assertEquals(cluster.getMembers(), [])
-            assertEquals(cluster.getCurrentSize(), 0)
-            assertFalse(cluster.hasMember(cluster))
-            cluster.addMember(cluster)
-            assertTrue(cluster.removeMember(cluster))
-
-            // allow the resize to complete
-            continuationLatch.countDown()
-            thread.join(TIMEOUT_MS)
-            assertFalse(thread.isAlive())
-        } finally {
-            thread.interrupt()
-        }
-    }
-
-    @Test
-    public void testReplacesMember() {
-        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
-                .configure("initialSize", 1)
-                .configure("factory", { properties -> return new TestEntityImpl(properties) }));
-
-        cluster.start([loc])
-        Entity member = Iterables.get(cluster.members, 0);
-
-        String replacementId = cluster.replaceMember(member.getId());
-        Entity replacement = cluster.getManagementContext().getEntityManager().getEntity(replacementId);
-
-        assertEquals(cluster.members.size(), 1)
-        assertFalse(cluster.members.contains(member))
-        assertFalse(cluster.children.contains(member))
-        assertNotNull(replacement, "replacementId="+replacementId);
-        assertTrue(cluster.members.contains(replacement), "replacement="+replacement+"; members="+cluster.members);
-        assertTrue(cluster.children.contains(replacement), "replacement="+replacement+"; children="+cluster.children);
-    }
-
-    @Test
-    public void testReplaceMemberThrowsIfMemberIdDoesNotResolve() {
-        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
-                .configure("initialSize", 1)
-                .configure("factory", { properties -> return new TestEntityImpl(properties) }));
-
-        cluster.start([loc])
-        Entity member = Iterables.get(cluster.members, 0);
-
-        try {
-            cluster.replaceMember("wrong.id");
-            fail();
-        } catch (Exception e) {
-            if (Exceptions.getFirstThrowableOfType(e, NoSuchElementException.class) == null) throw e;
-            if (!Exceptions.getFirstThrowableOfType(e, NoSuchElementException.class).getMessage().contains("entity wrong.id cannot be resolved")) throw e;
-        }
-
-        assertEquals(cluster.members as Set, ImmutableSet.of(member));
-    }
-
-    @Test
-    public void testReplaceMemberThrowsIfNotMember() {
-        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
-                .configure("initialSize", 1)
-                .configure("factory", { properties -> return new TestEntityImpl(properties) }));
-
-        cluster.start([loc])
-        Entity member = Iterables.get(cluster.members, 0);
-
-        try {
-            cluster.replaceMember(app.getId());
-            fail();
-        } catch (Exception e) {
-            if (Exceptions.getFirstThrowableOfType(e, NoSuchElementException.class) == null) throw e;
-            if (!Exceptions.getFirstThrowableOfType(e, NoSuchElementException.class).getMessage().contains("is not a member")) throw e;
-        }
-
-        assertEquals(cluster.members as Set, ImmutableSet.of(member));
-    }
-
-    @Test
-    public void testReplaceMemberFailsIfCantProvisionReplacement() {
-        final int failNum = 2
-        final AtomicInteger counter = new AtomicInteger(0)
-        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
-                .configure("factory", { properties -> 
-                    int num = counter.incrementAndGet();
-                    return new FailingEntity(properties, (num==failNum))
-                }));
-
-        cluster.start([loc])
-        Entity member = Iterables.get(cluster.members, 0);
-
-        try {
-            cluster.replaceMember(member.getId());
-            fail();
-        } catch (Exception e) {
-            if (!e.toString().contains("failed to grow")) throw e;
-            if (Exceptions.getFirstThrowableOfType(e, NoSuchElementException.class) != null) throw e;
-        }
-        assertEquals(cluster.members as Set, ImmutableSet.of(member));
-    }
-
-    @Test
-    public void testReplaceMemberRemovesAndThowsIfFailToStopOld() {
-        final int failNum = 1
-        final AtomicInteger counter = new AtomicInteger(0)
-        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
-                .configure("initialSize", 1)
-                .configure("factory", { properties ->
-                    int num = counter.incrementAndGet();
-                    return new FailingEntity(properties, false, (num==failNum), IllegalStateException.class)
-                }));
-
-        cluster.start([loc])
-        Entity member = Iterables.get(cluster.members, 0);
-
-        try {
-            cluster.replaceMember(member.getId());
-            fail();
-        } catch (Exception e) {
-            if (Exceptions.getFirstThrowableOfType(e, StopFailedRuntimeException.class) == null) throw e;
-            boolean found = false;
-            for (Throwable t : Throwables.getCausalChain(e)) {
-                if (t.toString().contains("Simulating entity stop failure")) {
-                    found = true;
-                    break;
-                }
-            }
-            if (!found) throw e;
-        }
-        assertFalse(Entities.isManaged(member));
-        assertEquals(cluster.members.size(), 1);
-    }
-
-    private Throwable unwrapException(Throwable e) {
-        if (e instanceof ExecutionException) {
-            return unwrapException(e.cause)
-        } else if (e instanceof org.codehaus.groovy.runtime.InvokerInvocationException) {
-            return unwrapException(e.cause)
-        } else {
-            return e
-        }
-    }
-}
-
-class FailingEntity extends TestEntityImpl {
-    final boolean failOnStart;
-    final boolean failOnStop;
-    final Class<? extends Exception> exceptionClazz;
-
-    public FailingEntity(Map flags, boolean failOnStart) {
-        this(flags, failOnStart, false);
-    }
-    
-    public FailingEntity(Map flags, boolean failOnStart, boolean failOnStop) {
-        this(flags, failOnStart, failOnStop, IllegalStateException.class);
-    }
-    
-    public FailingEntity(Map flags, boolean failOnStart, boolean failOnStop, Class<? extends Exception> exceptionClazz) {
-        super(flags)
-        this.failOnStart = failOnStart;
-        this.failOnStop = failOnStop;
-        this.exceptionClazz = exceptionClazz;
-    }
-    
-    @Override
-    public void start(Collection<? extends Location> locs) {
-        if (failOnStart) {
-            Exception e = exceptionClazz.getConstructor(String.class).newInstance("Simulating entity start failure for test");
-            throw e;
-        }
-    }
-    
-    @Override
-    public void stop() {
-        if (failOnStop) {
-            Exception e = exceptionClazz.getConstructor(String.class).newInstance("Simulating entity stop failure for test");
-            throw e;
-        }
-    }
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/d52e7ed2/core/src/test/java/brooklyn/entity/group/DynamicClusterTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/brooklyn/entity/group/DynamicClusterTest.java b/core/src/test/java/brooklyn/entity/group/DynamicClusterTest.java
new file mode 100644
index 0000000..9fb9230
--- /dev/null
+++ b/core/src/test/java/brooklyn/entity/group/DynamicClusterTest.java
@@ -0,0 +1,815 @@
+package brooklyn.entity.group;
+
+import static org.testng.Assert.assertEquals;
+import static org.testng.Assert.assertFalse;
+import static org.testng.Assert.assertNotNull;
+import static org.testng.Assert.assertTrue;
+import static org.testng.Assert.fail;
+
+import java.util.Collection;
+import java.util.List;
+import java.util.Map;
+import java.util.NoSuchElementException;
+import java.util.Random;
+import java.util.Set;
+import java.util.concurrent.CopyOnWriteArrayList;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.concurrent.atomic.AtomicReference;
+
+import org.testng.annotations.AfterMethod;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.Test;
+
+import brooklyn.entity.Entity;
+import brooklyn.entity.basic.ApplicationBuilder;
+import brooklyn.entity.basic.Attributes;
+import brooklyn.entity.basic.BrooklynTaskTags;
+import brooklyn.entity.basic.Entities;
+import brooklyn.entity.basic.EntityFactory;
+import brooklyn.entity.basic.Lifecycle;
+import brooklyn.entity.proxying.EntitySpec;
+import brooklyn.entity.trait.Changeable;
+import brooklyn.location.Location;
+import brooklyn.location.basic.SimulatedLocation;
+import brooklyn.management.Task;
+import brooklyn.test.Asserts;
+import brooklyn.test.entity.TestApplication;
+import brooklyn.test.entity.TestEntity;
+import brooklyn.test.entity.TestEntityImpl;
+import brooklyn.util.collections.MutableMap;
+import brooklyn.util.exceptions.Exceptions;
+import brooklyn.util.time.Time;
+
+import com.google.common.base.Function;
+import com.google.common.base.Predicates;
+import com.google.common.base.Throwables;
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.ImmutableSet;
+import com.google.common.collect.Iterables;
+import com.google.common.collect.Lists;
+import com.google.common.util.concurrent.Atomics;
+
+
+public class DynamicClusterTest {
+
+    private static final int TIMEOUT_MS = 2000;
+
+    TestApplication app;
+    SimulatedLocation loc;
+    SimulatedLocation loc2;
+    Random random = new Random();
+
+    @BeforeMethod
+    public void setUp() {
+        app = ApplicationBuilder.newManagedApp(TestApplication.class);
+        loc = new SimulatedLocation();
+        loc2 = new SimulatedLocation();
+    }
+
+    @AfterMethod(alwaysRun = true)
+    public void tearDown(){
+        if (app != null) Entities.destroyAll(app.getManagementContext());
+    }
+
+    @Test
+    public void creationOkayWithoutNewEntityFactoryArgument() throws Exception {
+        app.createAndManageChild(EntitySpec.create(DynamicCluster.class));
+    }
+
+    @Test
+    public void constructionRequiresThatNewEntityArgumentIsAnEntityFactory() throws Exception {
+        try {
+            app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
+                    .configure("factory", "error"));
+            fail();
+        } catch (Exception e) {
+            if (Exceptions.getFirstThrowableOfType(e, IllegalArgumentException.class) == null) throw e;
+        }
+    }
+
+    @Test
+    public void startRequiresThatNewEntityArgumentIsGiven() throws Exception {
+        DynamicCluster c = app.createAndManageChild(EntitySpec.create(DynamicCluster.class));
+        try {
+            c.start(ImmutableList.of(loc));
+            fail();
+        } catch (Exception e) {
+            if (Exceptions.getFirstThrowableOfType(e, IllegalStateException.class) == null) throw e;
+        }
+    }
+
+    @Test
+    public void startMethodFailsIfLocationsParameterHasMoreThanOneElement() throws Exception {
+        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
+                .configure(DynamicCluster.MEMBER_SPEC, EntitySpec.create(TestEntity.class)));
+        try {
+            cluster.start(ImmutableList.of(loc, loc2));
+            fail();
+        } catch (Exception e) {
+            if (Exceptions.getFirstThrowableOfType(e, IllegalArgumentException.class) == null) throw e;
+        }
+    }
+
+    @Test
+    public void testClusterHasOneLocationAfterStarting() throws Exception {
+        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
+                .configure(DynamicCluster.MEMBER_SPEC, EntitySpec.create(TestEntity.class)));
+        cluster.start(ImmutableList.of(loc));
+        assertEquals(cluster.getLocations().size(), 1);
+        assertEquals(ImmutableList.copyOf(cluster.getLocations()), ImmutableList.of(loc));
+    }
+
+    @Test
+    public void testServiceUpAfterStartingWithNoMembers() throws Exception {
+        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
+                .configure(DynamicCluster.MEMBER_SPEC, EntitySpec.create(TestEntity.class))
+                .configure(DynamicCluster.INITIAL_SIZE, 0));
+        cluster.start(ImmutableList.of(loc));
+        assertEquals(cluster.getAttribute(Attributes.SERVICE_STATE), Lifecycle.RUNNING);
+        assertTrue(cluster.getAttribute(Attributes.SERVICE_UP));
+    }
+
+    @Test
+    public void usingEntitySpecResizeFromZeroToOneStartsANewEntityAndSetsItsParent() throws Exception {
+        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
+                .configure("memberSpec", EntitySpec.create(TestEntity.class)));
+        
+        cluster.start(ImmutableList.of(loc));
+
+        cluster.resize(1);
+        TestEntity entity = (TestEntity) Iterables.getOnlyElement(cluster.getMembers());
+        assertEquals(entity.getCount(), 1);
+        assertEquals(entity.getParent(), cluster);
+        assertEquals(entity.getApplication(), app);
+    }
+
+    @Test
+    public void resizeFromZeroToOneStartsANewEntityAndSetsItsParent() throws Exception {
+        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
+                .configure("factory", new EntityFactory() {
+                    @Override public Entity newEntity(Map flags, Entity parent) {
+                        return new TestEntityImpl(flags);
+                    }}));
+
+        cluster.start(ImmutableList.of(loc));
+
+        cluster.resize(1);
+        TestEntity entity = (TestEntity) Iterables.get(cluster.getMembers(), 0);
+        assertEquals(entity.getCounter().get(), 1);
+        assertEquals(entity.getParent(), cluster);
+        assertEquals(entity.getApplication(), app);
+    }
+
+    @Test
+    public void currentSizePropertyReflectsActualClusterSize() throws Exception {
+        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
+                .configure("factory", new EntityFactory() {
+                    @Override public Entity newEntity(Map flags, Entity parent) {
+                        return new TestEntityImpl(flags);
+                    }}));
+
+
+        assertEquals(cluster.getCurrentSize(), (Integer)0);
+
+        cluster.start(ImmutableList.of(loc));
+        assertEquals(cluster.getCurrentSize(), (Integer)1);
+        assertEquals(cluster.getAttribute(Changeable.GROUP_SIZE), (Integer)1);
+
+        int newSize = cluster.resize(0);
+        assertEquals(newSize, 0);
+        assertEquals((Integer)newSize, cluster.getCurrentSize());
+        assertEquals(newSize, cluster.getMembers().size());
+        assertEquals((Integer)newSize, cluster.getAttribute(Changeable.GROUP_SIZE));
+
+        newSize = cluster.resize(4);
+        assertEquals(newSize, 4);
+        assertEquals((Integer)newSize, cluster.getCurrentSize());
+        assertEquals(newSize, cluster.getMembers().size());
+        assertEquals((Integer)newSize, cluster.getAttribute(Changeable.GROUP_SIZE));
+
+        newSize = cluster.resize(0);
+        assertEquals(newSize, 0);
+        assertEquals((Integer)newSize, cluster.getCurrentSize());
+        assertEquals(newSize, cluster.getMembers().size());
+        assertEquals((Integer)newSize, cluster.getAttribute(Changeable.GROUP_SIZE));
+    }
+
+    @Test
+    public void clusterSizeAfterStartIsInitialSize() throws Exception {
+        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
+                .configure("factory", new EntityFactory() {
+                    @Override public Entity newEntity(Map flags, Entity parent) {
+                        return new TestEntityImpl(flags);
+                    }})
+                .configure("initialSize", 2));
+
+        cluster.start(ImmutableList.of(loc));
+        assertEquals(cluster.getCurrentSize(), (Integer)2);
+        assertEquals(cluster.getMembers().size(), 2);
+        assertEquals(cluster.getAttribute(Changeable.GROUP_SIZE), (Integer)2);
+    }
+
+    @Test
+    public void clusterLocationIsPassedOnToEntityStart() throws Exception {
+        List<SimulatedLocation> locations = ImmutableList.of(loc);
+        final AtomicReference<Collection<? extends Location>> stashedLocations = Atomics.newReference();
+        
+        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
+                .configure("factory", new EntityFactory() {
+                    @Override public Entity newEntity(Map flags, Entity parent) {
+                        return new TestEntityImpl(parent) {
+                            @Override
+                            public void start(Collection<? extends Location> loc) {
+                                super.start(loc);
+                                stashedLocations.set(loc);
+                            }
+                        };
+                    }})
+                .configure("initialSize", 1));
+
+        cluster.start(locations);
+        TestEntity entity = (TestEntity) Iterables.get(cluster.getMembers(), 0);
+        
+        assertNotNull(stashedLocations.get());
+        assertEquals(stashedLocations.get().size(), 1);
+        assertEquals(ImmutableList.copyOf(stashedLocations.get()), locations);
+    }
+
+    @Test
+    public void resizeFromOneToZeroChangesClusterSize() throws Exception {
+        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
+                .configure("factory", new EntityFactory() {
+                    @Override public Entity newEntity(Map flags, Entity parent) {
+                        return new TestEntityImpl(flags);
+                    }})
+                .configure("initialSize", 1));
+
+        cluster.start(ImmutableList.of(loc));
+        TestEntity entity = (TestEntity) Iterables.get(cluster.getMembers(), 0);
+        assertEquals(cluster.getCurrentSize(), (Integer)1);
+        assertEquals(entity.getCounter().get(), 1);
+        
+        cluster.resize(0);
+        assertEquals(cluster.getCurrentSize(), (Integer)0);
+        assertEquals(entity.getCounter().get(), 0);
+    }
+
+    @Test
+    public void concurrentResizesToSameNumberCreatesCorrectNumberOfNodes() throws Exception {
+        final int OVERHEAD_MS = 500;
+        final int STARTUP_TIME_MS = 50;
+        final AtomicInteger numStarted = new AtomicInteger(0);
+        final DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
+                .configure("factory", new EntityFactory() {
+                    @Override public Entity newEntity(Map flags, Entity parent) {
+                        Time.sleep(STARTUP_TIME_MS);
+                        numStarted.incrementAndGet();
+                        return new TestEntityImpl(flags, parent);
+                    }}));
+
+        assertEquals(cluster.getCurrentSize(), (Integer)0);
+        cluster.start(ImmutableList.of(loc));
+
+        ExecutorService executor = Executors.newCachedThreadPool();
+        final List<Throwable> throwables = new CopyOnWriteArrayList<Throwable>();
+
+        try {
+            for (int i = 0; i < 10; i++) {
+                executor.submit(new Runnable() {
+                    public void run() {
+                        try {
+                            cluster.resize(2);
+                        } catch (Throwable e) {
+                            throwables.add(e);
+                        }
+                    }});
+            }
+
+            executor.shutdown();
+            assertTrue(executor.awaitTermination(10*STARTUP_TIME_MS+OVERHEAD_MS, TimeUnit.MILLISECONDS));
+            if (throwables.size() > 0) throw Exceptions.propagate(throwables.get(0));
+            assertEquals(cluster.getCurrentSize(), (Integer)2);
+            assertEquals(cluster.getAttribute(Changeable.GROUP_SIZE), (Integer)2);
+            assertEquals(numStarted.get(), 2);
+        } finally {
+            executor.shutdownNow();
+        }
+    }
+
+    @Test(enabled = false)
+    public void stoppingTheClusterStopsTheEntity() throws Exception {
+        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
+                .configure("factory", new EntityFactory() {
+                    @Override public Entity newEntity(Map flags, Entity parent) {
+                        return new TestEntityImpl(flags);
+                    }})
+                .configure("initialSize", 1));
+
+        cluster.start(ImmutableList.of(loc));
+        TestEntity entity = (TestEntity) Iterables.get(cluster.getMembers(), 0);
+        
+        assertEquals(entity.getCounter().get(), 1);
+        cluster.stop();
+        assertEquals(entity.getCounter().get(), 0);
+    }
+
+    /**
+     * This tests the fix for ENGR-1826.
+     */
+    @Test
+    public void failingEntitiesDontBreakClusterActions() throws Exception {
+        final int failNum = 2;
+        final AtomicInteger counter = new AtomicInteger(0);
+        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
+                .configure("initialSize", 0)
+                .configure("factory", new EntityFactory() {
+                    @Override public Entity newEntity(Map flags, Entity parent) {
+                        int num = counter.incrementAndGet();
+                        return new FailingEntity(flags, (num==failNum));
+                    }}));
+
+        cluster.start(ImmutableList.of(loc));
+        cluster.resize(3);
+        assertEquals(cluster.getCurrentSize(), (Integer)2);
+        assertEquals(cluster.getMembers().size(), 2);
+        for (Entity member : cluster.getMembers()) {
+            assertFalse(((FailingEntity)member).failOnStart);
+        }
+    }
+
+    @Test
+    public void testInitialQuorumSizeSufficientForStartup() throws Exception {
+        final int failNum = 1;
+        final AtomicInteger counter = new AtomicInteger(0);
+        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
+                .configure("initialSize", 2)
+                .configure(DynamicCluster.INITIAL_QUORUM_SIZE, 1)
+                .configure("factory", new EntityFactory() {
+                    @Override public Entity newEntity(Map flags, Entity parent) {
+                        int num = counter.incrementAndGet();
+                        return new FailingEntity(flags, (num==failNum));
+                    }}));
+
+        cluster.start(ImmutableList.of(loc));
+        
+        // note that children include quarantine group; and quarantined nodes
+        assertEquals(cluster.getCurrentSize(), (Integer)1);
+        assertEquals(cluster.getMembers().size(), 1);
+        for (Entity member : cluster.getMembers()) {
+            assertFalse(((FailingEntity)member).failOnStart);
+        }
+    }
+
+    @Test
+    public void testInitialQuorumSizeDefaultsToInitialSize() throws Exception {
+        final int failNum = 1;
+        final AtomicInteger counter = new AtomicInteger(0);
+        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
+                .configure("initialSize", 2)
+                .configure("factory", new EntityFactory() {
+                    @Override public Entity newEntity(Map flags, Entity parent) {
+                        int num = counter.incrementAndGet();
+                        return new FailingEntity(flags, (num==failNum));
+                    }}));
+
+        try {
+            cluster.start(ImmutableList.of(loc));
+        } catch (Exception e) {
+            IllegalStateException unwrapped = Exceptions.getFirstThrowableOfType(e, IllegalStateException.class);
+            if (unwrapped != null && unwrapped.getMessage().contains("failed to get to initial size")) {
+                // success
+            } else {
+                throw e; // fail
+            }
+        }
+        
+        // note that children include quarantine group; and quarantined nodes
+        assertEquals(cluster.getCurrentSize(), (Integer)1);
+        assertEquals(cluster.getMembers().size(), 1);
+        for (Entity member : cluster.getMembers()) {
+            assertFalse(((FailingEntity)member).failOnStart);
+        }
+    }
+
+    @Test
+    public void testCanQuarantineFailedEntities() throws Exception {
+        final int failNum = 2;
+        final AtomicInteger counter = new AtomicInteger(0);
+        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
+                .configure("quarantineFailedEntities", true)
+                .configure("initialSize", 0)
+                .configure("factory", new EntityFactory() {
+                    @Override public Entity newEntity(Map flags, Entity parent) {
+                        int num = counter.incrementAndGet();
+                        return new FailingEntity(flags, (num==failNum));
+                    }}));
+
+        cluster.start(ImmutableList.of(loc));
+        cluster.resize(3);
+        assertEquals(cluster.getCurrentSize(), (Integer)2);
+        assertEquals(cluster.getMembers().size(), 2);
+        assertEquals(Iterables.size(Iterables.filter(cluster.getChildren(), Predicates.instanceOf(FailingEntity.class))), 3);
+        for (Entity it : cluster.getMembers()) {
+            assertFalse(((FailingEntity)it).failOnStart);
+        }
+
+        assertEquals(cluster.getAttribute(DynamicCluster.QUARANTINE_GROUP).getMembers().size(), 1);
+        for (Entity it : cluster.getAttribute(DynamicCluster.QUARANTINE_GROUP).getMembers()) {
+            assertTrue(((FailingEntity)it).failOnStart);
+        }
+    }
+
+    @Test
+    public void testDoNotQuarantineFailedEntities() throws Exception {
+        final int failNum = 2;
+        final AtomicInteger counter = new AtomicInteger(0);
+        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
+                // default is quarantineFailedEntities==true
+                .configure("quarantineFailedEntities", false)
+                .configure("initialSize", 0)
+                .configure("factory", new EntityFactory() {
+                    @Override public Entity newEntity(Map flags, Entity parent) {
+                        int num = counter.incrementAndGet();
+                        return new FailingEntity(flags, (num==failNum));
+                    }}));
+
+        cluster.start(ImmutableList.of(loc));
+        
+        // no quarantine group, as a child
+        assertEquals(cluster.getChildren().size(), 0, "children="+cluster.getChildren());
+        
+        // Failed node will not be a member or child
+        cluster.resize(3);
+        assertEquals(cluster.getCurrentSize(), (Integer)2);
+        assertEquals(cluster.getMembers().size(), 2);
+        assertEquals(cluster.getChildren().size(), 2, "children="+cluster.getChildren());
+        
+        // Failed node will not be managed either
+        assertEquals(Iterables.size(Iterables.filter(cluster.getChildren(), Predicates.instanceOf(FailingEntity.class))), 2);
+        for (Entity member : cluster.getMembers()) {
+            assertFalse(((FailingEntity)member).failOnStart);
+        }
+    }
+
+    @Test
+    public void defaultRemovalStrategyShutsDownNewestFirstWhenResizing() throws Exception {
+        TestEntity entity;
+        final int failNum = 2;
+        final List<Entity> creationOrder = Lists.newArrayList();
+        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
+                .configure("initialSize", 0)
+                .configure("factory", new EntityFactory() {
+                    @Override public Entity newEntity(Map flags, Entity parent) {
+                        Entity result = new TestEntityImpl(flags);
+                        creationOrder.add(result);
+                        return result;
+                    }}));
+
+        cluster.start(ImmutableList.of(loc));
+        cluster.resize(1);
+        cluster.resize(2);
+        assertEquals(cluster.getCurrentSize(), (Integer)2);
+        assertEquals(ImmutableSet.copyOf(cluster.getMembers()), ImmutableSet.copyOf(creationOrder), "actual="+cluster.getMembers());
+
+        // Now stop one
+        cluster.resize(1);
+        assertEquals(cluster.getCurrentSize(), (Integer)1);
+        assertEquals(ImmutableList.copyOf(cluster.getMembers()), creationOrder.subList(0, 1));
+    }
+
+    @Test
+    public void resizeLoggedAsEffectorCall() throws Exception {
+        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
+                .configure("factory", new EntityFactory() {
+                    @Override public Entity newEntity(Map flags, Entity parent) {
+                        return new TestEntityImpl(flags);
+                    }}));
+
+        app.start(ImmutableList.of(loc));
+        cluster.resize(1);
+
+        Set<Task<?>> tasks = app.getManagementContext().getExecutionManager().getTasksWithAllTags(ImmutableList.of(
+            BrooklynTaskTags.tagForContextEntity(cluster),"EFFECTOR"));
+        assertEquals(tasks.size(), 2);
+        assertTrue(Iterables.get(tasks, 0).getDescription().contains("start"));
+        assertTrue(Iterables.get(tasks, 1).getDescription().contains("resize"));
+    }
+
+    @Test
+    public void testStoppedChildIsRemoveFromGroup() throws Exception {
+        final DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
+                .configure("initialSize", 1)
+                .configure("factory", new EntityFactory() {
+                    @Override public Entity newEntity(Map flags, Entity parent) {
+                        return new TestEntityImpl(flags);
+                    }}));
+
+        cluster.start(ImmutableList.of(loc));
+
+        final TestEntity child = (TestEntity) Iterables.get(cluster.getMembers(), 0);
+        child.stop();
+        Entities.unmanage(child);
+
+        Asserts.succeedsEventually(MutableMap.of("timeout", TIMEOUT_MS), new Runnable() {
+            @Override public void run() {
+                assertFalse(cluster.getChildren().contains(child), "children="+cluster.getChildren());
+                assertEquals(cluster.getCurrentSize(), (Integer)0);
+                assertEquals(cluster.getMembers().size(), 0);
+            }});
+    }
+
+    @Test
+    public void testPluggableRemovalStrategyIsUsed() throws Exception {
+        final List<Entity> removedEntities = Lists.newArrayList();
+
+        Function<Collection<Entity>, Entity> removalStrategy = new Function<Collection<Entity>, Entity>() {
+            @Override public Entity apply(Collection<Entity> contenders) {
+                Entity choice = Iterables.get(contenders, random.nextInt(contenders.size()));
+                removedEntities.add(choice);
+                return choice;
+            }
+        };
+
+        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
+                .configure("factory", new EntityFactory() {
+                    @Override public Entity newEntity(Map flags, Entity parent) {
+                        return new TestEntityImpl(flags);
+                    }})
+                .configure("initialSize", 10)
+                .configure("removalStrategy", removalStrategy));
+
+        cluster.start(ImmutableList.of(loc));
+        Set origMembers = ImmutableSet.copyOf(cluster.getMembers());
+
+        for (int i = 10; i >= 0; i--) {
+            cluster.resize(i);
+            assertEquals(cluster.getAttribute(Changeable.GROUP_SIZE), (Integer)i);
+            assertEquals(removedEntities.size(), 10-i);
+            assertEquals(ImmutableSet.copyOf(Iterables.concat(cluster.getMembers(), removedEntities)), origMembers);
+        }
+    }
+
+    @Test
+    public void testPluggableRemovalStrategyCanBeSetAfterConstruction() throws Exception {
+        final List<Entity> removedEntities = Lists.newArrayList();
+
+        Function<Collection<Entity>, Entity> removalStrategy = new Function<Collection<Entity>, Entity>() {
+            @Override public Entity apply(Collection<Entity> contenders) {
+                Entity choice = Iterables.get(contenders, random.nextInt(contenders.size()));
+                removedEntities.add(choice);
+                return choice;
+            }
+        };
+        
+        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
+                .configure("factory", new EntityFactory() {
+                    @Override public Entity newEntity(Map flags, Entity parent) {
+                        return new TestEntityImpl(flags);
+                    }})
+                .configure("initialSize", 10));
+
+        cluster.start(ImmutableList.of(loc));
+        Set origMembers = ImmutableSet.copyOf(cluster.getMembers());
+
+        cluster.setRemovalStrategy(removalStrategy);
+
+        for (int i = 10; i >= 0; i--) {
+            cluster.resize(i);
+            assertEquals(cluster.getAttribute(Changeable.GROUP_SIZE), (Integer)i);
+            assertEquals(removedEntities.size(), 10-i);
+            assertEquals(ImmutableSet.copyOf(Iterables.concat(cluster.getMembers(), removedEntities)), origMembers);
+        }
+    }
+
+    @Test
+    public void testResizeDoesNotBlockCallsToQueryGroupMembership() throws Exception {
+        final CountDownLatch executingLatch = new CountDownLatch(1);
+        final CountDownLatch continuationLatch = new CountDownLatch(1);
+        
+        final DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
+                .configure("initialSize", 0)
+                .configure("factory", new EntityFactory() {
+                    @Override public Entity newEntity(Map flags, Entity parent) {
+                        try {
+                            executingLatch.countDown();
+                            continuationLatch.await();
+                            return new TestEntityImpl(flags);
+                        } catch (InterruptedException e) {
+                            throw Exceptions.propagate(e);
+                        }
+                    }}));
+
+        cluster.start(ImmutableList.of(loc));
+
+        Thread thread = new Thread(new Runnable() {
+                @Override public void run() {
+                    cluster.resize(1);
+                }});
+        
+        try {
+            // wait for resize to be executing
+            thread.start();
+            executingLatch.await(TIMEOUT_MS, TimeUnit.MILLISECONDS);
+
+            // ensure can still call methods on group, to query/update membership
+            assertEquals(ImmutableList.copyOf(cluster.getMembers()), ImmutableList.of());
+            assertEquals(cluster.getCurrentSize(), (Integer)0);
+            assertFalse(cluster.hasMember(cluster));
+            cluster.addMember(cluster);
+            assertTrue(cluster.removeMember(cluster));
+
+            // allow the resize to complete
+            continuationLatch.countDown();
+            thread.join(TIMEOUT_MS);
+            assertFalse(thread.isAlive());
+        } finally {
+            thread.interrupt();
+        }
+    }
+
+    @Test
+    public void testReplacesMember() throws Exception {
+        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
+                .configure("initialSize", 1)
+                .configure("factory", new EntityFactory() {
+                    @Override public Entity newEntity(Map flags, Entity parent) {
+                        return new TestEntityImpl(flags);
+                    }}));
+
+        cluster.start(ImmutableList.of(loc));
+        Entity member = Iterables.get(cluster.getMembers(), 0);
+
+        String replacementId = cluster.replaceMember(member.getId());
+        Entity replacement = app.getManagementContext().getEntityManager().getEntity(replacementId);
+
+        assertEquals(cluster.getMembers().size(), 1);
+        assertFalse(cluster.getMembers().contains(member));
+        assertFalse(cluster.getChildren().contains(member));
+        assertNotNull(replacement, "replacementId="+replacementId);
+        assertTrue(cluster.getMembers().contains(replacement), "replacement="+replacement+"; members="+cluster.getMembers());
+        assertTrue(cluster.getChildren().contains(replacement), "replacement="+replacement+"; children="+cluster.getChildren());
+    }
+
+    @Test
+    public void testReplaceMemberThrowsIfMemberIdDoesNotResolve() throws Exception {
+        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
+                .configure("initialSize", 1)
+                .configure("factory", new EntityFactory() {
+                    @Override public Entity newEntity(Map flags, Entity parent) {
+                        return new TestEntityImpl(flags);
+                    }}));
+
+        cluster.start(ImmutableList.of(loc));
+        Entity member = Iterables.get(cluster.getMembers(), 0);
+
+        try {
+            cluster.replaceMember("wrong.id");
+            fail();
+        } catch (Exception e) {
+            if (Exceptions.getFirstThrowableOfType(e, NoSuchElementException.class) == null) throw e;
+            if (!Exceptions.getFirstThrowableOfType(e, NoSuchElementException.class).getMessage().contains("entity wrong.id cannot be resolved")) throw e;
+        }
+
+        assertEquals(ImmutableSet.copyOf(cluster.getMembers()), ImmutableSet.of(member));
+    }
+
+    @Test
+    public void testReplaceMemberThrowsIfNotMember() throws Exception {
+        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
+                .configure("initialSize", 1)
+                .configure("factory", new EntityFactory() {
+                    @Override public Entity newEntity(Map flags, Entity parent) {
+                        return new TestEntityImpl(flags);
+                    }}));
+
+        cluster.start(ImmutableList.of(loc));
+        Entity member = Iterables.get(cluster.getMembers(), 0);
+
+        try {
+            cluster.replaceMember(app.getId());
+            fail();
+        } catch (Exception e) {
+            if (Exceptions.getFirstThrowableOfType(e, NoSuchElementException.class) == null) throw e;
+            if (!Exceptions.getFirstThrowableOfType(e, NoSuchElementException.class).getMessage().contains("is not a member")) throw e;
+        }
+
+        assertEquals(ImmutableSet.copyOf(cluster.getMembers()), ImmutableSet.of(member));
+    }
+
+    @Test
+    public void testReplaceMemberFailsIfCantProvisionReplacement() throws Exception {
+        final int failNum = 2;
+        final AtomicInteger counter = new AtomicInteger(0);
+        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
+                .configure("factory", new EntityFactory() {
+                    @Override public Entity newEntity(Map flags, Entity parent) {
+                        int num = counter.incrementAndGet();
+                        return new FailingEntity(flags, (num==failNum));
+                    }}));
+
+        cluster.start(ImmutableList.of(loc));
+        Entity member = Iterables.get(cluster.getMembers(), 0);
+
+        try {
+            cluster.replaceMember(member.getId());
+            fail();
+        } catch (Exception e) {
+            if (!e.toString().contains("failed to grow")) throw e;
+            if (Exceptions.getFirstThrowableOfType(e, NoSuchElementException.class) != null) throw e;
+        }
+        assertEquals(ImmutableSet.copyOf(cluster.getMembers()), ImmutableSet.of(member));
+    }
+
+    @Test
+    public void testReplaceMemberRemovesAndThowsIfFailToStopOld() throws Exception {
+        final int failNum = 1;
+        final AtomicInteger counter = new AtomicInteger(0);
+        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
+                .configure("initialSize", 1)
+                .configure("factory", new EntityFactory() {
+                    @Override public Entity newEntity(Map flags, Entity parent) {
+                        int num = counter.incrementAndGet();
+                        return new FailingEntity(flags, false, (num==failNum), IllegalStateException.class);
+                    }}));
+
+        cluster.start(ImmutableList.of(loc));
+        Entity member = Iterables.get(cluster.getMembers(), 0);
+
+        try {
+            cluster.replaceMember(member.getId());
+            fail();
+        } catch (Exception e) {
+            if (Exceptions.getFirstThrowableOfType(e, StopFailedRuntimeException.class) == null) throw e;
+            boolean found = false;
+            for (Throwable t : Throwables.getCausalChain(e)) {
+                if (t.toString().contains("Simulating entity stop failure")) {
+                    found = true;
+                    break;
+                }
+            }
+            if (!found) throw e;
+        }
+        assertFalse(Entities.isManaged(member));
+        assertEquals(cluster.getMembers().size(), 1);
+    }
+
+    private Throwable unwrapException(Throwable e) {
+        if (e instanceof ExecutionException) {
+            return unwrapException(e.getCause());
+        } else if (e instanceof org.codehaus.groovy.runtime.InvokerInvocationException) {
+            return unwrapException(e.getCause());
+        } else {
+            return e;
+        }
+    }
+
+    public static class FailingEntity extends TestEntityImpl {
+        final boolean failOnStart;
+        final boolean failOnStop;
+        final Class<? extends Exception> exceptionClazz;
+    
+        public FailingEntity(Map flags, boolean failOnStart) {
+            this(flags, failOnStart, false);
+        }
+        
+        public FailingEntity(Map flags, boolean failOnStart, boolean failOnStop) {
+            this(flags, failOnStart, failOnStop, IllegalStateException.class);
+        }
+        
+        public FailingEntity(Map flags, boolean failOnStart, boolean failOnStop, Class<? extends Exception> exceptionClazz) {
+            super(flags);
+            this.failOnStart = failOnStart;
+            this.failOnStop = failOnStop;
+            this.exceptionClazz = exceptionClazz;
+        }
+        
+        @Override
+        public void start(Collection<? extends Location> locs) {
+            if (failOnStart) {
+                try {
+                    Exception e = exceptionClazz.getConstructor(String.class).newInstance("Simulating entity start failure for test");
+                    throw e;
+                } catch (Exception e) {
+                    throw Exceptions.propagate(e);
+                }
+            }
+        }
+        
+        @Override
+        public void stop() {
+            if (failOnStop) {
+                try {
+                    Exception e = exceptionClazz.getConstructor(String.class).newInstance("Simulating entity stop failure for test");
+                    throw e;
+                } catch (Exception e) {
+                    throw Exceptions.propagate(e);
+                }
+            }
+        }
+    }
+}
\ No newline at end of file


[11/50] [abbrv] git commit: Deletes nested DynamicClusterTest.FailingEntity

Posted by ri...@apache.org.
Deletes nested DynamicClusterTest.FailingEntity

- use instead brooklyn.entity.trait.FailingEntity


Project: http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/commit/b0e541e4
Tree: http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/tree/b0e541e4
Diff: http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/diff/b0e541e4

Branch: refs/pull/1410/merge
Commit: b0e541e487af240c698e46f314c9a8271e7bc446
Parents: d52e7ed
Author: Aled Sage <al...@gmail.com>
Authored: Wed May 21 12:18:25 2014 +0100
Committer: Aled Sage <al...@gmail.com>
Committed: Wed May 21 15:52:42 2014 +0100

----------------------------------------------------------------------
 .../entity/group/DynamicClusterTest.java        | 101 +++++++------------
 1 file changed, 38 insertions(+), 63 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/b0e541e4/core/src/test/java/brooklyn/entity/group/DynamicClusterTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/brooklyn/entity/group/DynamicClusterTest.java b/core/src/test/java/brooklyn/entity/group/DynamicClusterTest.java
index 9fb9230..a59079d 100644
--- a/core/src/test/java/brooklyn/entity/group/DynamicClusterTest.java
+++ b/core/src/test/java/brooklyn/entity/group/DynamicClusterTest.java
@@ -34,6 +34,7 @@ import brooklyn.entity.basic.EntityFactory;
 import brooklyn.entity.basic.Lifecycle;
 import brooklyn.entity.proxying.EntitySpec;
 import brooklyn.entity.trait.Changeable;
+import brooklyn.entity.trait.FailingEntity;
 import brooklyn.location.Location;
 import brooklyn.location.basic.SimulatedLocation;
 import brooklyn.management.Task;
@@ -330,7 +331,10 @@ public class DynamicClusterTest {
                 .configure("factory", new EntityFactory() {
                     @Override public Entity newEntity(Map flags, Entity parent) {
                         int num = counter.incrementAndGet();
-                        return new FailingEntity(flags, (num==failNum));
+                        return app.getManagementContext().getEntityManager().createEntity(EntitySpec.create(FailingEntity.class)
+                                .configure(flags)
+                                .configure(FailingEntity.FAIL_ON_START, (num==failNum))
+                                .parent(parent));
                     }}));
 
         cluster.start(ImmutableList.of(loc));
@@ -338,7 +342,7 @@ public class DynamicClusterTest {
         assertEquals(cluster.getCurrentSize(), (Integer)2);
         assertEquals(cluster.getMembers().size(), 2);
         for (Entity member : cluster.getMembers()) {
-            assertFalse(((FailingEntity)member).failOnStart);
+            assertFalse(((FailingEntity)member).getConfig(FailingEntity.FAIL_ON_START));
         }
     }
 
@@ -352,7 +356,10 @@ public class DynamicClusterTest {
                 .configure("factory", new EntityFactory() {
                     @Override public Entity newEntity(Map flags, Entity parent) {
                         int num = counter.incrementAndGet();
-                        return new FailingEntity(flags, (num==failNum));
+                        return app.getManagementContext().getEntityManager().createEntity(EntitySpec.create(FailingEntity.class)
+                                .configure(flags)
+                                .configure(FailingEntity.FAIL_ON_START, (num==failNum))
+                                .parent(parent));
                     }}));
 
         cluster.start(ImmutableList.of(loc));
@@ -361,7 +368,7 @@ public class DynamicClusterTest {
         assertEquals(cluster.getCurrentSize(), (Integer)1);
         assertEquals(cluster.getMembers().size(), 1);
         for (Entity member : cluster.getMembers()) {
-            assertFalse(((FailingEntity)member).failOnStart);
+            assertFalse(((FailingEntity)member).getConfig(FailingEntity.FAIL_ON_START));
         }
     }
 
@@ -374,7 +381,10 @@ public class DynamicClusterTest {
                 .configure("factory", new EntityFactory() {
                     @Override public Entity newEntity(Map flags, Entity parent) {
                         int num = counter.incrementAndGet();
-                        return new FailingEntity(flags, (num==failNum));
+                        return app.getManagementContext().getEntityManager().createEntity(EntitySpec.create(FailingEntity.class)
+                                .configure(flags)
+                                .configure(FailingEntity.FAIL_ON_START, (num==failNum))
+                                .parent(parent));
                     }}));
 
         try {
@@ -392,7 +402,7 @@ public class DynamicClusterTest {
         assertEquals(cluster.getCurrentSize(), (Integer)1);
         assertEquals(cluster.getMembers().size(), 1);
         for (Entity member : cluster.getMembers()) {
-            assertFalse(((FailingEntity)member).failOnStart);
+            assertFalse(((FailingEntity)member).getConfig(FailingEntity.FAIL_ON_START));
         }
     }
 
@@ -406,7 +416,10 @@ public class DynamicClusterTest {
                 .configure("factory", new EntityFactory() {
                     @Override public Entity newEntity(Map flags, Entity parent) {
                         int num = counter.incrementAndGet();
-                        return new FailingEntity(flags, (num==failNum));
+                        return app.getManagementContext().getEntityManager().createEntity(EntitySpec.create(FailingEntity.class)
+                                .configure(flags)
+                                .configure(FailingEntity.FAIL_ON_START, (num==failNum))
+                                .parent(parent));
                     }}));
 
         cluster.start(ImmutableList.of(loc));
@@ -414,13 +427,13 @@ public class DynamicClusterTest {
         assertEquals(cluster.getCurrentSize(), (Integer)2);
         assertEquals(cluster.getMembers().size(), 2);
         assertEquals(Iterables.size(Iterables.filter(cluster.getChildren(), Predicates.instanceOf(FailingEntity.class))), 3);
-        for (Entity it : cluster.getMembers()) {
-            assertFalse(((FailingEntity)it).failOnStart);
+        for (Entity member : cluster.getMembers()) {
+            assertFalse(((FailingEntity)member).getConfig(FailingEntity.FAIL_ON_START));
         }
 
         assertEquals(cluster.getAttribute(DynamicCluster.QUARANTINE_GROUP).getMembers().size(), 1);
-        for (Entity it : cluster.getAttribute(DynamicCluster.QUARANTINE_GROUP).getMembers()) {
-            assertTrue(((FailingEntity)it).failOnStart);
+        for (Entity member : cluster.getAttribute(DynamicCluster.QUARANTINE_GROUP).getMembers()) {
+            assertTrue(((FailingEntity)member).getConfig(FailingEntity.FAIL_ON_START));
         }
     }
 
@@ -435,7 +448,10 @@ public class DynamicClusterTest {
                 .configure("factory", new EntityFactory() {
                     @Override public Entity newEntity(Map flags, Entity parent) {
                         int num = counter.incrementAndGet();
-                        return new FailingEntity(flags, (num==failNum));
+                        return app.getManagementContext().getEntityManager().createEntity(EntitySpec.create(FailingEntity.class)
+                                .configure(flags)
+                                .configure(FailingEntity.FAIL_ON_START, (num==failNum))
+                                .parent(parent));
                     }}));
 
         cluster.start(ImmutableList.of(loc));
@@ -452,14 +468,12 @@ public class DynamicClusterTest {
         // Failed node will not be managed either
         assertEquals(Iterables.size(Iterables.filter(cluster.getChildren(), Predicates.instanceOf(FailingEntity.class))), 2);
         for (Entity member : cluster.getMembers()) {
-            assertFalse(((FailingEntity)member).failOnStart);
+            assertFalse(((FailingEntity)member).getConfig(FailingEntity.FAIL_ON_START));
         }
     }
 
     @Test
     public void defaultRemovalStrategyShutsDownNewestFirstWhenResizing() throws Exception {
-        TestEntity entity;
-        final int failNum = 2;
         final List<Entity> creationOrder = Lists.newArrayList();
         DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
                 .configure("initialSize", 0)
@@ -709,7 +723,10 @@ public class DynamicClusterTest {
                 .configure("factory", new EntityFactory() {
                     @Override public Entity newEntity(Map flags, Entity parent) {
                         int num = counter.incrementAndGet();
-                        return new FailingEntity(flags, (num==failNum));
+                        return app.getManagementContext().getEntityManager().createEntity(EntitySpec.create(FailingEntity.class)
+                                .configure(flags)
+                                .configure(FailingEntity.FAIL_ON_START, (num==failNum))
+                                .parent(parent));
                     }}));
 
         cluster.start(ImmutableList.of(loc));
@@ -734,7 +751,10 @@ public class DynamicClusterTest {
                 .configure("factory", new EntityFactory() {
                     @Override public Entity newEntity(Map flags, Entity parent) {
                         int num = counter.incrementAndGet();
-                        return new FailingEntity(flags, false, (num==failNum), IllegalStateException.class);
+                        return app.getManagementContext().getEntityManager().createEntity(EntitySpec.create(FailingEntity.class)
+                                .configure(flags)
+                                .configure(FailingEntity.FAIL_ON_STOP, (num==failNum))
+                                .parent(parent));
                     }}));
 
         cluster.start(ImmutableList.of(loc));
@@ -767,49 +787,4 @@ public class DynamicClusterTest {
             return e;
         }
     }
-
-    public static class FailingEntity extends TestEntityImpl {
-        final boolean failOnStart;
-        final boolean failOnStop;
-        final Class<? extends Exception> exceptionClazz;
-    
-        public FailingEntity(Map flags, boolean failOnStart) {
-            this(flags, failOnStart, false);
-        }
-        
-        public FailingEntity(Map flags, boolean failOnStart, boolean failOnStop) {
-            this(flags, failOnStart, failOnStop, IllegalStateException.class);
-        }
-        
-        public FailingEntity(Map flags, boolean failOnStart, boolean failOnStop, Class<? extends Exception> exceptionClazz) {
-            super(flags);
-            this.failOnStart = failOnStart;
-            this.failOnStop = failOnStop;
-            this.exceptionClazz = exceptionClazz;
-        }
-        
-        @Override
-        public void start(Collection<? extends Location> locs) {
-            if (failOnStart) {
-                try {
-                    Exception e = exceptionClazz.getConstructor(String.class).newInstance("Simulating entity start failure for test");
-                    throw e;
-                } catch (Exception e) {
-                    throw Exceptions.propagate(e);
-                }
-            }
-        }
-        
-        @Override
-        public void stop() {
-            if (failOnStop) {
-                try {
-                    Exception e = exceptionClazz.getConstructor(String.class).newInstance("Simulating entity stop failure for test");
-                    throw e;
-                } catch (Exception e) {
-                    throw Exceptions.propagate(e);
-                }
-            }
-        }
-    }
-}
\ No newline at end of file
+}


[47/50] [abbrv] git commit: comments on BrooklynNode

Posted by ri...@apache.org.
comments on BrooklynNode


Project: http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/commit/99b9e19b
Tree: http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/tree/99b9e19b
Diff: http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/diff/99b9e19b

Branch: refs/pull/1414/head
Commit: 99b9e19bfbb406f30d1e6c05bcc52ccdc4acdc87
Parents: 37cf817
Author: Alex Heneveld <al...@cloudsoftcorp.com>
Authored: Wed May 21 09:28:07 2014 -0600
Committer: Alex Heneveld <al...@cloudsoftcorp.com>
Committed: Fri May 23 10:35:45 2014 -0600

----------------------------------------------------------------------
 .../src/main/java/brooklyn/entity/brooklynnode/BrooklynNode.java  | 3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/99b9e19b/software/base/src/main/java/brooklyn/entity/brooklynnode/BrooklynNode.java
----------------------------------------------------------------------
diff --git a/software/base/src/main/java/brooklyn/entity/brooklynnode/BrooklynNode.java b/software/base/src/main/java/brooklyn/entity/brooklynnode/BrooklynNode.java
index f582820..cb21307 100644
--- a/software/base/src/main/java/brooklyn/entity/brooklynnode/BrooklynNode.java
+++ b/software/base/src/main/java/brooklyn/entity/brooklynnode/BrooklynNode.java
@@ -94,7 +94,8 @@ public interface BrooklynNode extends SoftwareProcess, UsesJava {
 
     @SetFromFlag("launchCommandCreatesPidFile")
     ConfigKey<Boolean> LAUNCH_COMMAND_CREATES_PID_FILE = ConfigKeys.newBooleanConfigKey("brooklynnode.launch.command.pid.updated",
-        "Whether the launch script creates/updates the PID file, if not the entity will do so", 
+        "Whether the launch script creates/updates the PID file, if not the entity will do so, "
+        + "but note it will not necessarily kill sub-processes", 
         true);
 
     @SetFromFlag("app")


[08/50] [abbrv] git commit: Deletes nested DynamicClusterTest.FailingEntity

Posted by ri...@apache.org.
Deletes nested DynamicClusterTest.FailingEntity

- use instead brooklyn.entity.trait.FailingEntity


Project: http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/commit/b0e541e4
Tree: http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/tree/b0e541e4
Diff: http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/diff/b0e541e4

Branch: refs/pull/1408/merge
Commit: b0e541e487af240c698e46f314c9a8271e7bc446
Parents: d52e7ed
Author: Aled Sage <al...@gmail.com>
Authored: Wed May 21 12:18:25 2014 +0100
Committer: Aled Sage <al...@gmail.com>
Committed: Wed May 21 15:52:42 2014 +0100

----------------------------------------------------------------------
 .../entity/group/DynamicClusterTest.java        | 101 +++++++------------
 1 file changed, 38 insertions(+), 63 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/b0e541e4/core/src/test/java/brooklyn/entity/group/DynamicClusterTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/brooklyn/entity/group/DynamicClusterTest.java b/core/src/test/java/brooklyn/entity/group/DynamicClusterTest.java
index 9fb9230..a59079d 100644
--- a/core/src/test/java/brooklyn/entity/group/DynamicClusterTest.java
+++ b/core/src/test/java/brooklyn/entity/group/DynamicClusterTest.java
@@ -34,6 +34,7 @@ import brooklyn.entity.basic.EntityFactory;
 import brooklyn.entity.basic.Lifecycle;
 import brooklyn.entity.proxying.EntitySpec;
 import brooklyn.entity.trait.Changeable;
+import brooklyn.entity.trait.FailingEntity;
 import brooklyn.location.Location;
 import brooklyn.location.basic.SimulatedLocation;
 import brooklyn.management.Task;
@@ -330,7 +331,10 @@ public class DynamicClusterTest {
                 .configure("factory", new EntityFactory() {
                     @Override public Entity newEntity(Map flags, Entity parent) {
                         int num = counter.incrementAndGet();
-                        return new FailingEntity(flags, (num==failNum));
+                        return app.getManagementContext().getEntityManager().createEntity(EntitySpec.create(FailingEntity.class)
+                                .configure(flags)
+                                .configure(FailingEntity.FAIL_ON_START, (num==failNum))
+                                .parent(parent));
                     }}));
 
         cluster.start(ImmutableList.of(loc));
@@ -338,7 +342,7 @@ public class DynamicClusterTest {
         assertEquals(cluster.getCurrentSize(), (Integer)2);
         assertEquals(cluster.getMembers().size(), 2);
         for (Entity member : cluster.getMembers()) {
-            assertFalse(((FailingEntity)member).failOnStart);
+            assertFalse(((FailingEntity)member).getConfig(FailingEntity.FAIL_ON_START));
         }
     }
 
@@ -352,7 +356,10 @@ public class DynamicClusterTest {
                 .configure("factory", new EntityFactory() {
                     @Override public Entity newEntity(Map flags, Entity parent) {
                         int num = counter.incrementAndGet();
-                        return new FailingEntity(flags, (num==failNum));
+                        return app.getManagementContext().getEntityManager().createEntity(EntitySpec.create(FailingEntity.class)
+                                .configure(flags)
+                                .configure(FailingEntity.FAIL_ON_START, (num==failNum))
+                                .parent(parent));
                     }}));
 
         cluster.start(ImmutableList.of(loc));
@@ -361,7 +368,7 @@ public class DynamicClusterTest {
         assertEquals(cluster.getCurrentSize(), (Integer)1);
         assertEquals(cluster.getMembers().size(), 1);
         for (Entity member : cluster.getMembers()) {
-            assertFalse(((FailingEntity)member).failOnStart);
+            assertFalse(((FailingEntity)member).getConfig(FailingEntity.FAIL_ON_START));
         }
     }
 
@@ -374,7 +381,10 @@ public class DynamicClusterTest {
                 .configure("factory", new EntityFactory() {
                     @Override public Entity newEntity(Map flags, Entity parent) {
                         int num = counter.incrementAndGet();
-                        return new FailingEntity(flags, (num==failNum));
+                        return app.getManagementContext().getEntityManager().createEntity(EntitySpec.create(FailingEntity.class)
+                                .configure(flags)
+                                .configure(FailingEntity.FAIL_ON_START, (num==failNum))
+                                .parent(parent));
                     }}));
 
         try {
@@ -392,7 +402,7 @@ public class DynamicClusterTest {
         assertEquals(cluster.getCurrentSize(), (Integer)1);
         assertEquals(cluster.getMembers().size(), 1);
         for (Entity member : cluster.getMembers()) {
-            assertFalse(((FailingEntity)member).failOnStart);
+            assertFalse(((FailingEntity)member).getConfig(FailingEntity.FAIL_ON_START));
         }
     }
 
@@ -406,7 +416,10 @@ public class DynamicClusterTest {
                 .configure("factory", new EntityFactory() {
                     @Override public Entity newEntity(Map flags, Entity parent) {
                         int num = counter.incrementAndGet();
-                        return new FailingEntity(flags, (num==failNum));
+                        return app.getManagementContext().getEntityManager().createEntity(EntitySpec.create(FailingEntity.class)
+                                .configure(flags)
+                                .configure(FailingEntity.FAIL_ON_START, (num==failNum))
+                                .parent(parent));
                     }}));
 
         cluster.start(ImmutableList.of(loc));
@@ -414,13 +427,13 @@ public class DynamicClusterTest {
         assertEquals(cluster.getCurrentSize(), (Integer)2);
         assertEquals(cluster.getMembers().size(), 2);
         assertEquals(Iterables.size(Iterables.filter(cluster.getChildren(), Predicates.instanceOf(FailingEntity.class))), 3);
-        for (Entity it : cluster.getMembers()) {
-            assertFalse(((FailingEntity)it).failOnStart);
+        for (Entity member : cluster.getMembers()) {
+            assertFalse(((FailingEntity)member).getConfig(FailingEntity.FAIL_ON_START));
         }
 
         assertEquals(cluster.getAttribute(DynamicCluster.QUARANTINE_GROUP).getMembers().size(), 1);
-        for (Entity it : cluster.getAttribute(DynamicCluster.QUARANTINE_GROUP).getMembers()) {
-            assertTrue(((FailingEntity)it).failOnStart);
+        for (Entity member : cluster.getAttribute(DynamicCluster.QUARANTINE_GROUP).getMembers()) {
+            assertTrue(((FailingEntity)member).getConfig(FailingEntity.FAIL_ON_START));
         }
     }
 
@@ -435,7 +448,10 @@ public class DynamicClusterTest {
                 .configure("factory", new EntityFactory() {
                     @Override public Entity newEntity(Map flags, Entity parent) {
                         int num = counter.incrementAndGet();
-                        return new FailingEntity(flags, (num==failNum));
+                        return app.getManagementContext().getEntityManager().createEntity(EntitySpec.create(FailingEntity.class)
+                                .configure(flags)
+                                .configure(FailingEntity.FAIL_ON_START, (num==failNum))
+                                .parent(parent));
                     }}));
 
         cluster.start(ImmutableList.of(loc));
@@ -452,14 +468,12 @@ public class DynamicClusterTest {
         // Failed node will not be managed either
         assertEquals(Iterables.size(Iterables.filter(cluster.getChildren(), Predicates.instanceOf(FailingEntity.class))), 2);
         for (Entity member : cluster.getMembers()) {
-            assertFalse(((FailingEntity)member).failOnStart);
+            assertFalse(((FailingEntity)member).getConfig(FailingEntity.FAIL_ON_START));
         }
     }
 
     @Test
     public void defaultRemovalStrategyShutsDownNewestFirstWhenResizing() throws Exception {
-        TestEntity entity;
-        final int failNum = 2;
         final List<Entity> creationOrder = Lists.newArrayList();
         DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
                 .configure("initialSize", 0)
@@ -709,7 +723,10 @@ public class DynamicClusterTest {
                 .configure("factory", new EntityFactory() {
                     @Override public Entity newEntity(Map flags, Entity parent) {
                         int num = counter.incrementAndGet();
-                        return new FailingEntity(flags, (num==failNum));
+                        return app.getManagementContext().getEntityManager().createEntity(EntitySpec.create(FailingEntity.class)
+                                .configure(flags)
+                                .configure(FailingEntity.FAIL_ON_START, (num==failNum))
+                                .parent(parent));
                     }}));
 
         cluster.start(ImmutableList.of(loc));
@@ -734,7 +751,10 @@ public class DynamicClusterTest {
                 .configure("factory", new EntityFactory() {
                     @Override public Entity newEntity(Map flags, Entity parent) {
                         int num = counter.incrementAndGet();
-                        return new FailingEntity(flags, false, (num==failNum), IllegalStateException.class);
+                        return app.getManagementContext().getEntityManager().createEntity(EntitySpec.create(FailingEntity.class)
+                                .configure(flags)
+                                .configure(FailingEntity.FAIL_ON_STOP, (num==failNum))
+                                .parent(parent));
                     }}));
 
         cluster.start(ImmutableList.of(loc));
@@ -767,49 +787,4 @@ public class DynamicClusterTest {
             return e;
         }
     }
-
-    public static class FailingEntity extends TestEntityImpl {
-        final boolean failOnStart;
-        final boolean failOnStop;
-        final Class<? extends Exception> exceptionClazz;
-    
-        public FailingEntity(Map flags, boolean failOnStart) {
-            this(flags, failOnStart, false);
-        }
-        
-        public FailingEntity(Map flags, boolean failOnStart, boolean failOnStop) {
-            this(flags, failOnStart, failOnStop, IllegalStateException.class);
-        }
-        
-        public FailingEntity(Map flags, boolean failOnStart, boolean failOnStop, Class<? extends Exception> exceptionClazz) {
-            super(flags);
-            this.failOnStart = failOnStart;
-            this.failOnStop = failOnStop;
-            this.exceptionClazz = exceptionClazz;
-        }
-        
-        @Override
-        public void start(Collection<? extends Location> locs) {
-            if (failOnStart) {
-                try {
-                    Exception e = exceptionClazz.getConstructor(String.class).newInstance("Simulating entity start failure for test");
-                    throw e;
-                } catch (Exception e) {
-                    throw Exceptions.propagate(e);
-                }
-            }
-        }
-        
-        @Override
-        public void stop() {
-            if (failOnStop) {
-                try {
-                    Exception e = exceptionClazz.getConstructor(String.class).newInstance("Simulating entity stop failure for test");
-                    throw e;
-                } catch (Exception e) {
-                    throw Exceptions.propagate(e);
-                }
-            }
-        }
-    }
-}
\ No newline at end of file
+}


[18/50] [abbrv] git commit: Add enricher memento for rebind

Posted by ri...@apache.org.
Add enricher memento for rebind


Project: http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/commit/34d4f8a4
Tree: http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/tree/34d4f8a4
Diff: http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/diff/34d4f8a4

Branch: refs/pull/1413/merge
Commit: 34d4f8a40c11ef5367c3058cdfd3b89a0ecbdedc
Parents: f54024f
Author: Andrew Kennedy <an...@cloudsoftcorp.com>
Authored: Thu May 22 15:20:31 2014 +0100
Committer: Andrew Kennedy <an...@cloudsoftcorp.com>
Committed: Thu May 22 15:20:31 2014 +0100

----------------------------------------------------------------------
 .../java/brooklyn/mementos/BrooklynMemento.java |  6 ++
 .../mementos/BrooklynMementoManifest.java       |  3 +
 .../mementos/BrooklynMementoPersister.java      |  2 +
 .../java/brooklyn/mementos/EnricherMemento.java | 16 +++++
 .../java/brooklyn/mementos/EntityMemento.java   |  5 ++
 .../rebind/BasicEnricherRebindSupport.java      | 50 ++++++++++++++
 .../entity/rebind/BasicPolicyRebindSupport.java |  8 +--
 .../entity/rebind/dto/BasicEnricherMemento.java | 68 ++++++++++++++++++++
 .../entity/rebind/dto/BasicEntityMemento.java   | 10 +++
 .../entity/rebind/dto/MementosGenerators.java   | 32 ++++++++-
 .../rebind/dto/MutableBrooklynMemento.java      | 39 ++++++++++-
 11 files changed, 230 insertions(+), 9 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/34d4f8a4/api/src/main/java/brooklyn/mementos/BrooklynMemento.java
----------------------------------------------------------------------
diff --git a/api/src/main/java/brooklyn/mementos/BrooklynMemento.java b/api/src/main/java/brooklyn/mementos/BrooklynMemento.java
index a528440..1717b3c 100644
--- a/api/src/main/java/brooklyn/mementos/BrooklynMemento.java
+++ b/api/src/main/java/brooklyn/mementos/BrooklynMemento.java
@@ -25,6 +25,8 @@ public interface BrooklynMemento extends Serializable {
     
     public PolicyMemento getPolicyMemento(String id);
     
+    public EnricherMemento getEnricherMemento(String id);
+    
     public Collection<String> getApplicationIds();
     
     public Collection<String> getTopLevelLocationIds();
@@ -35,9 +37,13 @@ public interface BrooklynMemento extends Serializable {
 
     public Collection<String> getPolicyIds();
 
+    public Collection<String> getEnricherIds();
+
     public Map<String, EntityMemento> getEntityMementos();
 
     public Map<String, LocationMemento> getLocationMementos();
 
     public Map<String, PolicyMemento> getPolicyMementos();
+
+    public Map<String, EnricherMemento> getEnricherMementos();
 }

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/34d4f8a4/api/src/main/java/brooklyn/mementos/BrooklynMementoManifest.java
----------------------------------------------------------------------
diff --git a/api/src/main/java/brooklyn/mementos/BrooklynMementoManifest.java b/api/src/main/java/brooklyn/mementos/BrooklynMementoManifest.java
index 2f3e83f..0bc10c0 100644
--- a/api/src/main/java/brooklyn/mementos/BrooklynMementoManifest.java
+++ b/api/src/main/java/brooklyn/mementos/BrooklynMementoManifest.java
@@ -15,4 +15,7 @@ public interface BrooklynMementoManifest extends Serializable {
     public Map<String, String> getLocationIdToType();
 
     public Map<String, String> getPolicyIdToType();
+
+    public Map<String, String> getEnricherIdToType();
+
 }

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/34d4f8a4/api/src/main/java/brooklyn/mementos/BrooklynMementoPersister.java
----------------------------------------------------------------------
diff --git a/api/src/main/java/brooklyn/mementos/BrooklynMementoPersister.java b/api/src/main/java/brooklyn/mementos/BrooklynMementoPersister.java
index ada8135..e29e70e 100644
--- a/api/src/main/java/brooklyn/mementos/BrooklynMementoPersister.java
+++ b/api/src/main/java/brooklyn/mementos/BrooklynMementoPersister.java
@@ -49,8 +49,10 @@ public interface BrooklynMementoPersister {
         Collection<LocationMemento> locations();
         Collection<EntityMemento> entities();
         Collection<PolicyMemento> policies();
+        Collection<EnricherMemento> enrichers();
         Collection<String> removedLocationIds();
         Collection<String> removedEntityIds();
         Collection<String> removedPolicyIds();
+        Collection<String> removedEnricherIds();
     }
 }

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/34d4f8a4/api/src/main/java/brooklyn/mementos/EnricherMemento.java
----------------------------------------------------------------------
diff --git a/api/src/main/java/brooklyn/mementos/EnricherMemento.java b/api/src/main/java/brooklyn/mementos/EnricherMemento.java
new file mode 100644
index 0000000..4213d40
--- /dev/null
+++ b/api/src/main/java/brooklyn/mementos/EnricherMemento.java
@@ -0,0 +1,16 @@
+package brooklyn.mementos;
+
+import java.util.Map;
+
+import brooklyn.entity.rebind.RebindSupport;
+
+/**
+ * Represents the state of an enricher, so that it can be reconstructed (e.g. after restarting brooklyn).
+ * 
+ * @see RebindSupport
+ */
+public interface EnricherMemento extends Memento {
+
+    Map<String, Object> getFlags();
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/34d4f8a4/api/src/main/java/brooklyn/mementos/EntityMemento.java
----------------------------------------------------------------------
diff --git a/api/src/main/java/brooklyn/mementos/EntityMemento.java b/api/src/main/java/brooklyn/mementos/EntityMemento.java
index 59501e2..966bedd 100644
--- a/api/src/main/java/brooklyn/mementos/EntityMemento.java
+++ b/api/src/main/java/brooklyn/mementos/EntityMemento.java
@@ -49,5 +49,10 @@ public interface EntityMemento extends Memento, TreeNode {
      * The ids of the policies of this entity.
      */
     public Collection<String> getPolicies();
+
+    /**
+     * The ids of the enrichers of this entity.
+     */
+    public Collection<String> getEnrichers();
     
 }

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/34d4f8a4/core/src/main/java/brooklyn/entity/rebind/BasicEnricherRebindSupport.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/brooklyn/entity/rebind/BasicEnricherRebindSupport.java b/core/src/main/java/brooklyn/entity/rebind/BasicEnricherRebindSupport.java
new file mode 100644
index 0000000..9d3a50e
--- /dev/null
+++ b/core/src/main/java/brooklyn/entity/rebind/BasicEnricherRebindSupport.java
@@ -0,0 +1,50 @@
+package brooklyn.entity.rebind;
+
+import java.util.Collections;
+import java.util.Map;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import brooklyn.entity.rebind.dto.MementosGenerators;
+import brooklyn.mementos.PolicyMemento;
+import brooklyn.policy.basic.AbstractPolicy;
+
+public class BasicEnricherRebindSupport implements RebindSupport<PolicyMemento> {
+
+    private static final Logger LOG = LoggerFactory.getLogger(BasicEnricherRebindSupport.class);
+    
+    private final AbstractPolicy policy;
+    
+    public BasicEnricherRebindSupport(AbstractPolicy policy) {
+        this.policy = policy;
+    }
+    
+    @Override
+    public PolicyMemento getMemento() {
+        return getMementoWithProperties(Collections.<String,Object>emptyMap());
+    }
+
+    protected PolicyMemento getMementoWithProperties(Map<String,?> props) {
+        PolicyMemento memento = MementosGenerators.newPolicyMementoBuilder(policy).customFields(props).build();
+        if (LOG.isTraceEnabled()) LOG.trace("Creating memento for policy: {}", memento.toVerboseString());
+        return memento;
+    }
+
+    @Override
+    public void reconstruct(RebindContext rebindContext, PolicyMemento memento) {
+        if (LOG.isTraceEnabled()) LOG.trace("Reconstructing policy: {}", memento.toVerboseString());
+
+        // Note that the flags have been set in the constructor
+        policy.setName(memento.getDisplayName());
+        
+        doReconsruct(rebindContext, memento);
+    }
+
+    /**
+     * For overriding, to give custom reconsruct behaviour.
+     */
+    protected void doReconsruct(RebindContext rebindContext, PolicyMemento memento) {
+        // default is no-op
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/34d4f8a4/core/src/main/java/brooklyn/entity/rebind/BasicPolicyRebindSupport.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/brooklyn/entity/rebind/BasicPolicyRebindSupport.java b/core/src/main/java/brooklyn/entity/rebind/BasicPolicyRebindSupport.java
index acf0ebb..2c33702 100644
--- a/core/src/main/java/brooklyn/entity/rebind/BasicPolicyRebindSupport.java
+++ b/core/src/main/java/brooklyn/entity/rebind/BasicPolicyRebindSupport.java
@@ -27,15 +27,15 @@ public class BasicPolicyRebindSupport implements RebindSupport<PolicyMemento> {
 
     protected PolicyMemento getMementoWithProperties(Map<String,?> props) {
         PolicyMemento memento = MementosGenerators.newPolicyMementoBuilder(policy).customFields(props).build();
-    	if (LOG.isTraceEnabled()) LOG.trace("Creating memento for policy: {}", memento.toVerboseString());
-    	return memento;
+        if (LOG.isTraceEnabled()) LOG.trace("Creating memento for policy: {}", memento.toVerboseString());
+        return memento;
     }
 
     @Override
     public void reconstruct(RebindContext rebindContext, PolicyMemento memento) {
-    	if (LOG.isTraceEnabled()) LOG.trace("Reconstructing policy: {}", memento.toVerboseString());
+        if (LOG.isTraceEnabled()) LOG.trace("Reconstructing policy: {}", memento.toVerboseString());
 
-    	// Note that the flags have been set in the constructor
+        // Note that the flags have been set in the constructor
         policy.setName(memento.getDisplayName());
         
         doReconsruct(rebindContext, memento);

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/34d4f8a4/core/src/main/java/brooklyn/entity/rebind/dto/BasicEnricherMemento.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/brooklyn/entity/rebind/dto/BasicEnricherMemento.java b/core/src/main/java/brooklyn/entity/rebind/dto/BasicEnricherMemento.java
new file mode 100644
index 0000000..b1d7052
--- /dev/null
+++ b/core/src/main/java/brooklyn/entity/rebind/dto/BasicEnricherMemento.java
@@ -0,0 +1,68 @@
+package brooklyn.entity.rebind.dto;
+
+import java.io.Serializable;
+import java.util.Map;
+
+import brooklyn.entity.basic.Entities;
+import brooklyn.mementos.EnricherMemento;
+
+import com.google.common.base.Objects.ToStringHelper;
+import com.google.common.collect.Maps;
+
+/**
+ * The persisted state of a location.
+ *
+ * @author aled
+ */
+public class BasicEnricherMemento extends AbstractMemento implements EnricherMemento, Serializable {
+
+    private static final long serialVersionUID = -1; // FIXME
+
+    public static Builder builder() {
+        return new Builder();
+    }
+
+    public static class Builder extends AbstractMemento.Builder<Builder> {
+        protected Map<String,Object> flags = Maps.newLinkedHashMap();
+
+        public Builder from(EnricherMemento other) {
+            super.from(other);
+            flags.putAll(other.getFlags());
+            return this;
+        }
+        public Builder flags(Map<String,?> vals) {
+            flags.putAll(vals); return this;
+        }
+        public EnricherMemento build() {
+            return new BasicEnricherMemento(this);
+        }
+    }
+
+    private Map<String,Object> flags;
+    private Map<String, Object> fields;
+
+    // Trusts the builder to not mess around with mutability after calling build()
+    protected BasicEnricherMemento(Builder builder) {
+        flags = toPersistedMap(builder.flags);
+    }
+
+    @Override
+    protected void setCustomFields(Map<String, Object> fields) {
+        this.fields = toPersistedMap(fields);
+    }
+
+    @Override
+    public Map<String, Object> getCustomFields() {
+        return fromPersistedMap(fields);
+    }
+
+    @Override
+    public Map<String, Object> getFlags() {
+        return fromPersistedMap(flags);
+    }
+
+    @Override
+    protected ToStringHelper newVerboseStringHelper() {
+        return super.newVerboseStringHelper().add("flags", Entities.sanitize(getFlags()));
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/34d4f8a4/core/src/main/java/brooklyn/entity/rebind/dto/BasicEntityMemento.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/brooklyn/entity/rebind/dto/BasicEntityMemento.java b/core/src/main/java/brooklyn/entity/rebind/dto/BasicEntityMemento.java
index 7377629..9ded4f7 100644
--- a/core/src/main/java/brooklyn/entity/rebind/dto/BasicEntityMemento.java
+++ b/core/src/main/java/brooklyn/entity/rebind/dto/BasicEntityMemento.java
@@ -49,6 +49,7 @@ public class BasicEntityMemento extends AbstractTreeNodeMemento implements Entit
         protected Map<AttributeSensor<?>, Object> attributes = Maps.newLinkedHashMap();
         protected List<String> locations = Lists.newArrayList();
         protected List<String> policies = Lists.newArrayList();
+        protected List<String> enrichers = Lists.newArrayList();
         protected List<String> members = Lists.newArrayList();
         protected List<Effector<?>> effectors = Lists.newArrayList();
         
@@ -61,6 +62,7 @@ public class BasicEntityMemento extends AbstractTreeNodeMemento implements Entit
             attributes.putAll(other.getAttributes());
             locations.addAll(other.getLocations());
             policies.addAll(other.getPolicies());
+            enrichers.addAll(other.getEnrichers());
             members.addAll(other.getMembers());
             effectors.addAll(other.getEffectors());
             return this;
@@ -81,6 +83,7 @@ public class BasicEntityMemento extends AbstractTreeNodeMemento implements Entit
     private List<String> members;
     private Map<String, Object> attributes;
     private List<String> policies;
+    private List<String> enrichers;
     
     // TODO can we move some of these to entity type, or remove/re-insert those which are final statics?
     private Map<String, ConfigKey<?>> configKeys;
@@ -107,6 +110,7 @@ public class BasicEntityMemento extends AbstractTreeNodeMemento implements Entit
         
         locations = toPersistedList(builder.locations);
         policies = toPersistedList(builder.policies);
+        enrichers = toPersistedList(builder.enrichers);
         members = toPersistedList(builder.members);
         
         effectors = toPersistedList(builder.effectors);
@@ -243,6 +247,11 @@ public class BasicEntityMemento extends AbstractTreeNodeMemento implements Entit
     }
     
     @Override
+    public List<String> getEnrichers() {
+        return fromPersistedList(enrichers);
+    }
+    
+    @Override
     public List<String> getMembers() {
         return fromPersistedList(members);
     }
@@ -260,6 +269,7 @@ public class BasicEntityMemento extends AbstractTreeNodeMemento implements Entit
                 .add("configUnmatched", Entities.sanitize(getConfigUnmatched()))
                 .add("attributes", Entities.sanitize(getAttributes()))
                 .add("policies", getPolicies())
+                .add("enrichers", getEnrichers())
                 .add("locations", getLocations());
     }
 

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/34d4f8a4/core/src/main/java/brooklyn/entity/rebind/dto/MementosGenerators.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/brooklyn/entity/rebind/dto/MementosGenerators.java b/core/src/main/java/brooklyn/entity/rebind/dto/MementosGenerators.java
index 3eaada3..c77fb34 100644
--- a/core/src/main/java/brooklyn/entity/rebind/dto/MementosGenerators.java
+++ b/core/src/main/java/brooklyn/entity/rebind/dto/MementosGenerators.java
@@ -21,9 +21,11 @@ import brooklyn.location.basic.LocationInternal;
 import brooklyn.management.ManagementContext;
 import brooklyn.management.Task;
 import brooklyn.mementos.BrooklynMemento;
+import brooklyn.mementos.EnricherMemento;
 import brooklyn.mementos.EntityMemento;
 import brooklyn.mementos.LocationMemento;
 import brooklyn.mementos.PolicyMemento;
+import brooklyn.policy.Enricher;
 import brooklyn.policy.Policy;
 import brooklyn.util.collections.MutableMap;
 import brooklyn.util.config.ConfigBag;
@@ -143,9 +145,13 @@ public class MementosGenerators {
         // (e.g. AbstractController registering a AbstractMembershipTrackingPolicy)
         // Also, the entity constructor often re-creates the policy
         // Also see RebindManagerImpl.CheckpointingChangeListener.onChanged(Entity)
-//        for (Policy policy : entity.getPolicies()) {
-//            builder.policies.add(policy.getId()); 
-//        }
+        for (Policy policy : entity.getPolicies()) {
+            builder.policies.add(policy.getId()); 
+        }
+        
+        for (Enricher enricher : entity.getEnrichers()) {
+            builder.enrichers.add(enricher.getId()); 
+        }
         
         Entity parentEntity = entity.getParent();
         builder.parent = (parentEntity != null) ? parentEntity.getId() : null;
@@ -219,4 +225,24 @@ public class MementosGenerators {
         
         return builder;
     }
+    
+    /**
+     * Given an enricher, extracts its state for serialization.
+     */
+    public static EnricherMemento newEnricherMemento(Enricher enricher) {
+        return newEnricherMementoBuilder(enricher).build();
+    }
+    
+    public static BasicEnricherMemento.Builder newEnricherMementoBuilder(Enricher enricher) {
+        BasicEnricherMemento.Builder builder = BasicEnricherMemento.builder();
+        
+        builder.type = enricher.getClass().getName();
+        builder.typeClass = enricher.getClass();
+        builder.id = enricher.getId();
+        builder.displayName = enricher.getName();
+
+        builder.flags.putAll(FlagUtils.getFieldsWithFlagsExcludingModifiers(enricher, Modifier.STATIC ^ Modifier.TRANSIENT));
+        
+        return builder;
+    }
 }

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/34d4f8a4/core/src/main/java/brooklyn/entity/rebind/dto/MutableBrooklynMemento.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/brooklyn/entity/rebind/dto/MutableBrooklynMemento.java b/core/src/main/java/brooklyn/entity/rebind/dto/MutableBrooklynMemento.java
index 1b9e4e7..61bbb8c 100644
--- a/core/src/main/java/brooklyn/entity/rebind/dto/MutableBrooklynMemento.java
+++ b/core/src/main/java/brooklyn/entity/rebind/dto/MutableBrooklynMemento.java
@@ -10,6 +10,7 @@ import org.codehaus.jackson.annotate.JsonAutoDetect;
 import org.codehaus.jackson.annotate.JsonAutoDetect.Visibility;
 
 import brooklyn.mementos.BrooklynMemento;
+import brooklyn.mementos.EnricherMemento;
 import brooklyn.mementos.EntityMemento;
 import brooklyn.mementos.LocationMemento;
 import brooklyn.mementos.PolicyMemento;
@@ -36,6 +37,7 @@ public class MutableBrooklynMemento implements BrooklynMemento {
     private final Map<String, EntityMemento> entities = Maps.newLinkedHashMap();
     private final Map<String, LocationMemento> locations = Maps.newLinkedHashMap();
     private final Map<String, PolicyMemento> policies = Maps.newLinkedHashMap();
+    private final Map<String, EnricherMemento> enrichers = Maps.newLinkedHashMap();
 
     public MutableBrooklynMemento() {
     }
@@ -67,6 +69,10 @@ public class MutableBrooklynMemento implements BrooklynMemento {
         updatePolicyMementos(ImmutableSet.of(memento));
     }
     
+    public void updateEnricherMemento(EnricherMemento memento) {
+        updateEnricherMementos(ImmutableSet.of(memento));
+    }
+    
     public void updateEntityMementos(Collection<EntityMemento> mementos) {
         for (EntityMemento memento : mementos) {
             entities.put(memento.getId(), memento);
@@ -93,6 +99,12 @@ public class MutableBrooklynMemento implements BrooklynMemento {
         }
     }
     
+    public void updateEnricherMementos(Collection<EnricherMemento> mementos) {
+        for (EnricherMemento memento : mementos) {
+            enrichers.put(memento.getId(), memento);
+        }
+    }
+    
     /**
      * Removes the entities with the given ids.
      */
@@ -102,7 +114,7 @@ public class MutableBrooklynMemento implements BrooklynMemento {
     }
     
     /**
-     * Removes the entities with the given ids.
+     * Removes the locations with the given ids.
      */
     public void removeLocations(Collection<String> ids) {
         locations.keySet().removeAll(ids);
@@ -110,12 +122,19 @@ public class MutableBrooklynMemento implements BrooklynMemento {
     }
 
     /**
-     * Removes the entities with the given ids.
+     * Removes the policies with the given ids.
      */
     public void removePolicies(Collection<String> ids) {
         policies.keySet().removeAll(ids);
     }
 
+    /**
+     * Removes the enrichers with the given ids.
+     */
+    public void removeEnrichers(Collection<String> ids) {
+        enrichers.keySet().removeAll(ids);
+    }
+
     @Override
     public EntityMemento getEntityMemento(String id) {
         return entities.get(id);
@@ -130,6 +149,12 @@ public class MutableBrooklynMemento implements BrooklynMemento {
     public PolicyMemento getPolicyMemento(String id) {
         return policies.get(id);
     }
+
+    
+    @Override
+    public EnricherMemento getEnricherMemento(String id) {
+        return enrichers.get(id);
+    }
     
     @Override
     public Collection<String> getApplicationIds() {
@@ -153,6 +178,11 @@ public class MutableBrooklynMemento implements BrooklynMemento {
     }
     
     @Override
+    public Collection<String> getEnricherIds() {
+        return Collections.unmodifiableSet(enrichers.keySet());
+    }
+    
+    @Override
     public Collection<String> getTopLevelLocationIds() {
         return Collections.unmodifiableCollection(topLevelLocationIds);
     }
@@ -171,4 +201,9 @@ public class MutableBrooklynMemento implements BrooklynMemento {
     public Map<String, PolicyMemento> getPolicyMementos() {
         return ImmutableMap.copyOf(policies);
     }
+
+    @Override
+    public Map<String, EnricherMemento> getEnricherMementos() {
+        return ImmutableMap.copyOf(enrichers);
+    }
 }


[33/50] [abbrv] git commit: Merge pull request #1398 from aledsage/refactor/DynamicClusterTest-from-groovy-to-java

Posted by ri...@apache.org.
Merge pull request #1398 from aledsage/refactor/DynamicClusterTest-from-groovy-to-java

Refactor DynamicClusterTest from groovy to java (and tidies)

Project: http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/commit/cb2d0d3a
Tree: http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/tree/cb2d0d3a
Diff: http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/diff/cb2d0d3a

Branch: refs/pull/1411/merge
Commit: cb2d0d3a184095b4bfdefe73a95435f4e4beb906
Parents: 48a34e4 b0e541e
Author: Andrew Kennedy <gr...@apache.org>
Authored: Fri May 23 17:18:40 2014 +0100
Committer: Andrew Kennedy <gr...@apache.org>
Committed: Fri May 23 17:18:40 2014 +0100

----------------------------------------------------------------------
 .../entity/group/DynamicClusterTest.groovy      | 726 -----------------
 .../entity/group/DynamicClusterTest.java        | 790 +++++++++++++++++++
 2 files changed, 790 insertions(+), 726 deletions(-)
----------------------------------------------------------------------



[04/50] [abbrv] git commit: Covert DynamicClusterTest from groovy to java

Posted by ri...@apache.org.
Covert DynamicClusterTest from groovy to java


Project: http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/commit/d52e7ed2
Tree: http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/tree/d52e7ed2
Diff: http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/diff/d52e7ed2

Branch: refs/heads/master
Commit: d52e7ed2fe0c2aa623bcacee6dd4f3638e2c5647
Parents: d3d5c11
Author: Aled Sage <al...@gmail.com>
Authored: Wed May 21 12:07:53 2014 +0100
Committer: Aled Sage <al...@gmail.com>
Committed: Wed May 21 15:52:41 2014 +0100

----------------------------------------------------------------------
 .../entity/group/DynamicClusterTest.groovy      | 726 -----------------
 .../entity/group/DynamicClusterTest.java        | 815 +++++++++++++++++++
 2 files changed, 815 insertions(+), 726 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/d52e7ed2/core/src/test/java/brooklyn/entity/group/DynamicClusterTest.groovy
----------------------------------------------------------------------
diff --git a/core/src/test/java/brooklyn/entity/group/DynamicClusterTest.groovy b/core/src/test/java/brooklyn/entity/group/DynamicClusterTest.groovy
deleted file mode 100644
index 636abbc..0000000
--- a/core/src/test/java/brooklyn/entity/group/DynamicClusterTest.groovy
+++ /dev/null
@@ -1,726 +0,0 @@
-package brooklyn.entity.group
-
-import brooklyn.entity.basic.Attributes
-import brooklyn.entity.basic.Lifecycle
-
-import static org.testng.Assert.*
-
-import java.util.concurrent.CopyOnWriteArrayList
-import java.util.concurrent.CountDownLatch
-import java.util.concurrent.ExecutionException
-import java.util.concurrent.ExecutorService
-import java.util.concurrent.Executors
-import java.util.concurrent.TimeUnit
-import java.util.concurrent.atomic.AtomicInteger
-
-import org.testng.annotations.AfterMethod
-import org.testng.annotations.BeforeMethod
-import org.testng.annotations.Test
-
-import brooklyn.entity.Application
-import brooklyn.entity.Entity
-import brooklyn.entity.basic.ApplicationBuilder
-import brooklyn.entity.basic.BrooklynTaskTags
-import brooklyn.entity.basic.Entities
-import brooklyn.entity.proxying.EntitySpec
-import brooklyn.entity.trait.Changeable
-import brooklyn.location.Location
-import brooklyn.location.basic.SimulatedLocation
-import brooklyn.management.Task
-import brooklyn.test.TestUtils
-import brooklyn.test.entity.TestApplication
-import brooklyn.test.entity.TestEntity
-import brooklyn.test.entity.TestEntityImpl
-import brooklyn.util.GroovyJavaMethods
-import brooklyn.util.exceptions.Exceptions
-
-import com.google.common.base.Predicates
-import com.google.common.base.Throwables;
-import com.google.common.collect.ImmutableList
-import com.google.common.collect.ImmutableSet
-import com.google.common.collect.Iterables
-
-
-class DynamicClusterTest {
-
-    private static final int TIMEOUT_MS = 2000
-
-    TestApplication app
-    SimulatedLocation loc
-    SimulatedLocation loc2
-    Random random = new Random()
-
-    @BeforeMethod
-    public void setUp() {
-        app = ApplicationBuilder.newManagedApp(TestApplication.class);
-        loc = new SimulatedLocation()
-        loc2 = new SimulatedLocation()
-    }
-
-    @AfterMethod(alwaysRun = true)
-    public void tearDown(){
-        if (app != null) Entities.destroyAll(app.getManagementContext());
-    }
-
-    @Test
-    public void creationOkayWithoutNewEntityFactoryArgument() {
-        app.createAndManageChild(EntitySpec.create(DynamicCluster.class));
-    }
-
-    @Test
-    public void constructionRequiresThatNewEntityArgumentIsAnEntityFactory() {
-        try {
-            app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
-                    .configure("factory", "error"));
-            fail();
-        } catch (Exception e) {
-            if (Exceptions.getFirstThrowableOfType(e, IllegalArgumentException.class) == null) throw e;
-        }
-    }
-
-    @Test
-    public void startRequiresThatNewEntityArgumentIsGiven() {
-        DynamicCluster c = app.createAndManageChild(EntitySpec.create(DynamicCluster.class));
-        try {
-            c.start([loc]);
-            fail();
-        } catch (Exception e) {
-            if (Exceptions.getFirstThrowableOfType(e, IllegalStateException.class) == null) throw e;
-        }
-    }
-
-    @Test
-    public void startMethodFailsIfLocationsParameterHasMoreThanOneElement() {
-        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
-                .configure("factory", { new TestEntityImpl() }));
-        try {
-            cluster.start([ loc, loc2 ])
-            fail();
-        } catch (Exception e) {
-            if (Exceptions.getFirstThrowableOfType(e, IllegalArgumentException.class) == null) throw e;
-        }
-    }
-
-    @Test
-    public void testClusterHasOneLocationAfterStarting() {
-        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
-                .configure("factory", { new TestEntityImpl() }));
-        cluster.start([loc])
-        assertEquals(cluster.getLocations().size(), 1)
-        assertEquals(cluster.getLocations() as List, [loc])
-    }
-
-    @Test
-    public void testServiceUpAfterStartingWithNoMembers() {
-        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
-                .configure(DynamicCluster.MEMBER_SPEC, EntitySpec.create(TestEntity.class))
-                .configure(DynamicCluster.INITIAL_SIZE, 0))
-        cluster.start([loc])
-        assertEquals(cluster.getAttribute(Attributes.SERVICE_STATE), Lifecycle.RUNNING)
-        assertTrue(cluster.getAttribute(Attributes.SERVICE_UP))
-    }
-
-    @Test
-    public void usingEntitySpecResizeFromZeroToOneStartsANewEntityAndSetsItsParent() {
-        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
-                .configure("memberSpec", EntitySpec.create(TestEntity.class)));
-        
-        cluster.start([loc])
-
-        cluster.resize(1)
-        Entity entity = Iterables.getOnlyElement(cluster.getMembers());
-        assertEquals entity.count, 1
-        assertEquals entity.parent, cluster
-        assertEquals entity.application, app
-    }
-
-    @Test
-    public void resizeFromZeroToOneStartsANewEntityAndSetsItsParent() {
-        TestEntity entity
-        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
-                .configure("factory", { properties -> entity = new TestEntityImpl(properties) }));
-
-        cluster.start([loc])
-
-        cluster.resize(1)
-        assertEquals entity.counter.get(), 1
-        assertEquals entity.parent, cluster
-        assertEquals entity.application, app
-    }
-
-    @Test
-    public void currentSizePropertyReflectsActualClusterSize() {
-        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
-                .configure("factory", { properties -> return new TestEntityImpl(properties) }));
-
-        assertEquals cluster.currentSize, 0
-
-        cluster.start([loc])
-        assertEquals cluster.currentSize, 1
-        assertEquals cluster.getAttribute(Changeable.GROUP_SIZE), 1
-
-        int newSize = cluster.resize(0)
-        assertEquals newSize, 0
-        assertEquals newSize, cluster.currentSize
-        assertEquals newSize, cluster.members.size()
-        assertEquals newSize, cluster.getAttribute(Changeable.GROUP_SIZE)
-
-        newSize = cluster.resize(4)
-        assertEquals newSize, 4
-        assertEquals newSize, cluster.currentSize
-        assertEquals newSize, cluster.members.size()
-        assertEquals newSize, cluster.getAttribute(Changeable.GROUP_SIZE)
-
-        newSize = cluster.resize(0)
-        assertEquals newSize, 0
-        assertEquals newSize, cluster.currentSize
-        assertEquals newSize, cluster.members.size()
-        assertEquals newSize, cluster.getAttribute(Changeable.GROUP_SIZE)
-    }
-
-    @Test
-    public void clusterSizeAfterStartIsInitialSize() {
-        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
-                .configure("factory", { properties -> return new TestEntityImpl(properties) })
-                .configure("initialSize", 2));
-
-        cluster.start([loc])
-        assertEquals cluster.currentSize, 2
-        assertEquals cluster.members.size(), 2
-        assertEquals cluster.getAttribute(Changeable.GROUP_SIZE), 2
-    }
-
-    @Test
-    public void clusterLocationIsPassedOnToEntityStart() {
-        Collection<Location> locations = [ loc ]
-        TestEntity entity
-        def newEntity = { properties, cluster ->
-            entity = new TestEntityImpl(parent:cluster) {
-	            List<Location> stashedLocations = null
-	            @Override
-	            void start(Collection<? extends Location> loc) {
-	                super.start(loc)
-	                stashedLocations = loc
-	            }
-	        }
-        }
-        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
-                .configure("factory", newEntity)
-                .configure("initialSize", 1));
-
-        cluster.start(locations)
-
-        assertNotNull entity.stashedLocations
-        assertEquals entity.stashedLocations.size(), 1
-        assertEquals entity.stashedLocations[0], locations[0]
-    }
-
-    @Test
-    public void resizeFromOneToZeroChangesClusterSize() {
-        TestEntity entity
-        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
-                .configure("factory", { properties -> entity = new TestEntityImpl(properties) })
-                .configure("initialSize", 1));
-
-        cluster.start([loc])
-        assertEquals cluster.currentSize, 1
-        assertEquals entity.counter.get(), 1
-        cluster.resize(0)
-        assertEquals cluster.currentSize, 0
-        assertEquals entity.counter.get(), 0
-    }
-
-    @Test
-    public void concurrentResizesToSameNumberCreatesCorrectNumberOfNodes() {
-        final int OVERHEAD_MS = 500
-        final int STARTUP_TIME_MS = 50
-        final AtomicInteger numStarted = new AtomicInteger(0)
-        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
-                .configure("factory", { 
-                    Map flags, Entity cluster -> 
-                    Thread.sleep(STARTUP_TIME_MS); numStarted.incrementAndGet(); new TestEntityImpl(flags, cluster)
-                }));
-
-        assertEquals cluster.currentSize, 0
-        cluster.start([loc])
-
-        ExecutorService executor = Executors.newCachedThreadPool()
-        List<Throwable> throwables = new CopyOnWriteArrayList<Throwable>()
-
-        try {
-            for (int i in 1..10) {
-                executor.submit( {
-                    try {
-                        cluster.resize(2)
-                    } catch (Throwable e) {
-                        throwables.add(e)
-                    }
-                })
-            }
-
-            executor.shutdown()
-            assertTrue(executor.awaitTermination(10*STARTUP_TIME_MS+OVERHEAD_MS, TimeUnit.MILLISECONDS))
-            if (throwables.size() > 0) throw throwables.get(0)
-            assertEquals(cluster.currentSize, 2)
-            assertEquals(cluster.getAttribute(Changeable.GROUP_SIZE), 2)
-            assertEquals(numStarted.get(), 2)
-        } finally {
-            executor.shutdownNow();
-        }
-    }
-
-    @Test(enabled = false)
-    public void stoppingTheClusterStopsTheEntity() {
-        TestEntity entity
-        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
-                .configure("factory", { properties -> entity = new TestEntityImpl(properties) })
-                .configure("initialSize", 1));
-
-        cluster.start([loc])
-        assertEquals entity.counter.get(), 1
-        cluster.stop()
-        assertEquals entity.counter.get(), 0
-    }
-
-    /**
-     * This tests the fix for ENGR-1826.
-     */
-    @Test
-    public void failingEntitiesDontBreakClusterActions() {
-        final int failNum = 2
-        final AtomicInteger counter = new AtomicInteger(0)
-        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
-                .configure("initialSize", 0)
-                .configure("factory", { properties ->
-                    int num = counter.incrementAndGet();
-                    return new FailingEntity(properties, (num==failNum))
-                }));
-
-        cluster.start([loc])
-        cluster.resize(3)
-        assertEquals(cluster.currentSize, 2)
-        assertEquals(cluster.getMembers().size(), 2)
-        for (Entity member : cluster.getMembers()) {
-            assertFalse(((FailingEntity)member).failOnStart)
-        }
-    }
-
-    @Test
-    public void testInitialQuorumSizeSufficientForStartup() {
-        final int failNum = 1;
-        final AtomicInteger counter = new AtomicInteger(0)
-        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
-                .configure("initialSize", 2)
-                .configure(DynamicCluster.INITIAL_QUORUM_SIZE, 1)
-                .configure("factory", { properties ->
-                    int num = counter.incrementAndGet();
-                    return new FailingEntity(properties, (num==failNum))
-                }));
-
-        cluster.start([loc])
-        
-        // note that children include quarantine group; and quarantined nodes
-        assertEquals(cluster.getCurrentSize(), 1)
-        assertEquals(cluster.getMembers().size(), 1)
-        for (Entity member : cluster.getMembers()) {
-            assertFalse(((FailingEntity)member).failOnStart)
-        }
-    }
-
-    @Test
-    public void testInitialQuorumSizeDefaultsToInitialSize() throws Exception {
-        final int failNum = 1;
-        final AtomicInteger counter = new AtomicInteger(0)
-        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
-                .configure("initialSize", 2)
-                .configure("factory", { properties ->
-                    int num = counter.incrementAndGet();
-                    return new FailingEntity(properties, (num==failNum))
-                }));
-
-        try {
-            cluster.start([loc])
-        } catch (Exception e) {
-            IllegalStateException unwrapped = Exceptions.getFirstThrowableOfType(e, IllegalStateException.class);
-            if (unwrapped != null && unwrapped.getMessage().contains("failed to get to initial size")) {
-                // success
-            } else {
-                throw e; // fail
-            }
-        }
-        
-        // note that children include quarantine group; and quarantined nodes
-        assertEquals(cluster.getCurrentSize(), 1)
-        assertEquals(cluster.getMembers().size(), 1)
-        for (Entity member : cluster.getMembers()) {
-            assertFalse(((FailingEntity)member).failOnStart)
-        }
-    }
-
-    @Test
-    public void testCanQuarantineFailedEntities() {
-        final int failNum = 2
-        final AtomicInteger counter = new AtomicInteger(0)
-        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
-                .configure("quarantineFailedEntities", true)
-                .configure("initialSize", 0)
-                .configure("factory", { properties ->
-                    int num = counter.incrementAndGet();
-                    return new FailingEntity(properties, (num==failNum))
-                }));
-
-        cluster.start([loc])
-        cluster.resize(3)
-        assertEquals(cluster.currentSize, 2)
-        assertEquals(cluster.getMembers().size(), 2)
-        assertEquals(Iterables.size(Iterables.filter(cluster.getChildren(), Predicates.instanceOf(FailingEntity.class))), 3)
-        cluster.members.each {
-            assertFalse(((FailingEntity)it).failOnStart)
-        }
-
-        assertEquals(cluster.getAttribute(DynamicCluster.QUARANTINE_GROUP).members.size(), 1)
-        cluster.getAttribute(DynamicCluster.QUARANTINE_GROUP).members.each {
-            assertTrue(((FailingEntity)it).failOnStart)
-        }
-    }
-
-    @Test
-    public void testDoNotQuarantineFailedEntities() {
-        final int failNum = 2
-        final AtomicInteger counter = new AtomicInteger(0)
-        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
-                // default is quarantineFailedEntities==true
-                .configure("quarantineFailedEntities", false)
-                .configure("initialSize", 0)
-                .configure("factory", { properties ->
-                    int num = counter.incrementAndGet();
-                    return new FailingEntity(properties, (num==failNum))
-                }));
-
-        cluster.start([loc])
-        
-        // no quarantine group, as a child
-        assertEquals(cluster.getChildren().size(), 0, "children="+cluster.getChildren())
-        
-        // Failed node will not be a member or child
-        cluster.resize(3)
-        assertEquals(cluster.currentSize, 2)
-        assertEquals(cluster.getMembers().size(), 2)
-        assertEquals(cluster.getChildren().size(), 2, "children="+cluster.getChildren())
-        
-        // Failed node will not be managed either
-        assertEquals(Iterables.size(Iterables.filter(cluster.getChildren(), Predicates.instanceOf(FailingEntity.class))), 2)
-        for (Entity member : cluster.getMembers()) {
-            assertFalse(((FailingEntity)member).failOnStart)
-        }
-    }
-
-    @Test
-    public void defaultRemovalStrategyShutsDownNewestFirstWhenResizing() {
-        TestEntity entity
-        final int failNum = 2
-        final List<Entity> creationOrder = []
-        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
-                .configure("initialSize", 0)
-                .configure("factory", { properties ->
-                    Entity result = new TestEntityImpl(properties)
-                    creationOrder << result
-                    return result
-                }));
-
-        cluster.start([loc])
-        cluster.resize(1)
-        cluster.resize(2)
-        assertEquals(cluster.currentSize, 2)
-        assertEquals(ImmutableSet.copyOf(cluster.getMembers()), ImmutableSet.copyOf(creationOrder), "actual="+cluster.getMembers())
-
-        // Now stop one
-        cluster.resize(1)
-        assertEquals(cluster.currentSize, 1)
-        assertEquals(ImmutableList.copyOf(cluster.getMembers()), creationOrder.subList(0, 1))
-    }
-
-    @Test
-    public void resizeLoggedAsEffectorCall() {
-        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
-                .configure("factory", { properties -> return new TestEntityImpl(properties) }));
-
-        app.start([loc])
-        cluster.resize(1)
-
-        Set<Task> tasks = app.getManagementContext().getExecutionManager().getTasksWithAllTags([
-            BrooklynTaskTags.tagForContextEntity(cluster),"EFFECTOR"])
-        assertEquals(tasks.size(), 2)
-        assertTrue(Iterables.get(tasks, 0).getDescription().contains("start"))
-        assertTrue(Iterables.get(tasks, 1).getDescription().contains("resize"))
-    }
-
-    @Test
-    public void testStoppedChildIsRemoveFromGroup() {
-        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
-                .configure("initialSize", 1)
-                .configure("factory", { properties -> return new TestEntityImpl(properties) }));
-
-        cluster.start([loc])
-
-        TestEntity child = Iterables.get(cluster.getMembers(), 0);
-        child.stop()
-        Entities.unmanage(child)
-
-        TestUtils.executeUntilSucceeds(timeout:TIMEOUT_MS) {
-            assertFalse(cluster.getChildren().contains(child), "children="+cluster.getChildren())
-            assertEquals(cluster.currentSize, 0)
-            assertEquals(cluster.members.size(), 0)
-        }
-    }
-
-    @Test
-    public void testPluggableRemovalStrategyIsUsed() {
-        List<Entity> removedEntities = []
-
-        Closure removalStrategy = { Collection<Entity> contenders ->
-            Entity choice = Iterables.get(contenders, random.nextInt(contenders.size()))
-            removedEntities.add(choice)
-            return choice
-        }
-        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
-                .configure("factory", { properties -> return new TestEntityImpl(properties) })
-                .configure("initialSize", 10)
-                .configure("removalStrategy", removalStrategy));
-
-        cluster.start([loc])
-        Set origMembers = cluster.members as Set
-
-        for (int i = 10; i >= 0; i--) {
-            cluster.resize(i)
-            assertEquals(cluster.getAttribute(Changeable.GROUP_SIZE), i)
-            assertEquals(removedEntities.size(), 10-i)
-            assertEquals(ImmutableSet.copyOf(Iterables.concat(cluster.members, removedEntities)), origMembers)
-        }
-    }
-
-    @Test
-    public void testPluggableRemovalStrategyCanBeSetAfterConstruction() {
-        List<Entity> removedEntities = []
-
-        Closure removalStrategy = { Collection<Entity> contenders ->
-            Entity choice = Iterables.get(contenders, random.nextInt(contenders.size()))
-            removedEntities.add(choice)
-            return choice
-        }
-        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
-                .configure("factory", { properties -> return new TestEntityImpl(properties) })
-                .configure("initialSize", 10));
-
-        cluster.start([loc])
-        Set origMembers = cluster.members as Set
-
-        cluster.setRemovalStrategy(GroovyJavaMethods.functionFromClosure(removalStrategy));
-
-        for (int i = 10; i >= 0; i--) {
-            cluster.resize(i)
-            assertEquals(cluster.getAttribute(Changeable.GROUP_SIZE), i)
-            assertEquals(removedEntities.size(), 10-i)
-            assertEquals(ImmutableSet.copyOf(Iterables.concat(cluster.members, removedEntities)), origMembers)
-        }
-    }
-
-    @Test
-    public void testResizeDoesNotBlockCallsToQueryGroupMembership() {
-        CountDownLatch executingLatch = new CountDownLatch(1)
-        CountDownLatch continuationLatch = new CountDownLatch(1)
-        
-        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
-                .configure("initialSize", 0)
-                .configure("factory", { properties ->
-                        executingLatch.countDown()
-                        continuationLatch.await()
-                        return new TestEntityImpl(properties)
-                    }));
-
-        cluster.start([loc])
-
-        Thread thread = new Thread( { cluster.resize(1) })
-        try {
-            // wait for resize to be executing
-            thread.start()
-            executingLatch.await(TIMEOUT_MS, TimeUnit.MILLISECONDS)
-
-            // ensure can still call methods on group, to query/update membership
-            assertEquals(cluster.getMembers(), [])
-            assertEquals(cluster.getCurrentSize(), 0)
-            assertFalse(cluster.hasMember(cluster))
-            cluster.addMember(cluster)
-            assertTrue(cluster.removeMember(cluster))
-
-            // allow the resize to complete
-            continuationLatch.countDown()
-            thread.join(TIMEOUT_MS)
-            assertFalse(thread.isAlive())
-        } finally {
-            thread.interrupt()
-        }
-    }
-
-    @Test
-    public void testReplacesMember() {
-        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
-                .configure("initialSize", 1)
-                .configure("factory", { properties -> return new TestEntityImpl(properties) }));
-
-        cluster.start([loc])
-        Entity member = Iterables.get(cluster.members, 0);
-
-        String replacementId = cluster.replaceMember(member.getId());
-        Entity replacement = cluster.getManagementContext().getEntityManager().getEntity(replacementId);
-
-        assertEquals(cluster.members.size(), 1)
-        assertFalse(cluster.members.contains(member))
-        assertFalse(cluster.children.contains(member))
-        assertNotNull(replacement, "replacementId="+replacementId);
-        assertTrue(cluster.members.contains(replacement), "replacement="+replacement+"; members="+cluster.members);
-        assertTrue(cluster.children.contains(replacement), "replacement="+replacement+"; children="+cluster.children);
-    }
-
-    @Test
-    public void testReplaceMemberThrowsIfMemberIdDoesNotResolve() {
-        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
-                .configure("initialSize", 1)
-                .configure("factory", { properties -> return new TestEntityImpl(properties) }));
-
-        cluster.start([loc])
-        Entity member = Iterables.get(cluster.members, 0);
-
-        try {
-            cluster.replaceMember("wrong.id");
-            fail();
-        } catch (Exception e) {
-            if (Exceptions.getFirstThrowableOfType(e, NoSuchElementException.class) == null) throw e;
-            if (!Exceptions.getFirstThrowableOfType(e, NoSuchElementException.class).getMessage().contains("entity wrong.id cannot be resolved")) throw e;
-        }
-
-        assertEquals(cluster.members as Set, ImmutableSet.of(member));
-    }
-
-    @Test
-    public void testReplaceMemberThrowsIfNotMember() {
-        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
-                .configure("initialSize", 1)
-                .configure("factory", { properties -> return new TestEntityImpl(properties) }));
-
-        cluster.start([loc])
-        Entity member = Iterables.get(cluster.members, 0);
-
-        try {
-            cluster.replaceMember(app.getId());
-            fail();
-        } catch (Exception e) {
-            if (Exceptions.getFirstThrowableOfType(e, NoSuchElementException.class) == null) throw e;
-            if (!Exceptions.getFirstThrowableOfType(e, NoSuchElementException.class).getMessage().contains("is not a member")) throw e;
-        }
-
-        assertEquals(cluster.members as Set, ImmutableSet.of(member));
-    }
-
-    @Test
-    public void testReplaceMemberFailsIfCantProvisionReplacement() {
-        final int failNum = 2
-        final AtomicInteger counter = new AtomicInteger(0)
-        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
-                .configure("factory", { properties -> 
-                    int num = counter.incrementAndGet();
-                    return new FailingEntity(properties, (num==failNum))
-                }));
-
-        cluster.start([loc])
-        Entity member = Iterables.get(cluster.members, 0);
-
-        try {
-            cluster.replaceMember(member.getId());
-            fail();
-        } catch (Exception e) {
-            if (!e.toString().contains("failed to grow")) throw e;
-            if (Exceptions.getFirstThrowableOfType(e, NoSuchElementException.class) != null) throw e;
-        }
-        assertEquals(cluster.members as Set, ImmutableSet.of(member));
-    }
-
-    @Test
-    public void testReplaceMemberRemovesAndThowsIfFailToStopOld() {
-        final int failNum = 1
-        final AtomicInteger counter = new AtomicInteger(0)
-        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
-                .configure("initialSize", 1)
-                .configure("factory", { properties ->
-                    int num = counter.incrementAndGet();
-                    return new FailingEntity(properties, false, (num==failNum), IllegalStateException.class)
-                }));
-
-        cluster.start([loc])
-        Entity member = Iterables.get(cluster.members, 0);
-
-        try {
-            cluster.replaceMember(member.getId());
-            fail();
-        } catch (Exception e) {
-            if (Exceptions.getFirstThrowableOfType(e, StopFailedRuntimeException.class) == null) throw e;
-            boolean found = false;
-            for (Throwable t : Throwables.getCausalChain(e)) {
-                if (t.toString().contains("Simulating entity stop failure")) {
-                    found = true;
-                    break;
-                }
-            }
-            if (!found) throw e;
-        }
-        assertFalse(Entities.isManaged(member));
-        assertEquals(cluster.members.size(), 1);
-    }
-
-    private Throwable unwrapException(Throwable e) {
-        if (e instanceof ExecutionException) {
-            return unwrapException(e.cause)
-        } else if (e instanceof org.codehaus.groovy.runtime.InvokerInvocationException) {
-            return unwrapException(e.cause)
-        } else {
-            return e
-        }
-    }
-}
-
-class FailingEntity extends TestEntityImpl {
-    final boolean failOnStart;
-    final boolean failOnStop;
-    final Class<? extends Exception> exceptionClazz;
-
-    public FailingEntity(Map flags, boolean failOnStart) {
-        this(flags, failOnStart, false);
-    }
-    
-    public FailingEntity(Map flags, boolean failOnStart, boolean failOnStop) {
-        this(flags, failOnStart, failOnStop, IllegalStateException.class);
-    }
-    
-    public FailingEntity(Map flags, boolean failOnStart, boolean failOnStop, Class<? extends Exception> exceptionClazz) {
-        super(flags)
-        this.failOnStart = failOnStart;
-        this.failOnStop = failOnStop;
-        this.exceptionClazz = exceptionClazz;
-    }
-    
-    @Override
-    public void start(Collection<? extends Location> locs) {
-        if (failOnStart) {
-            Exception e = exceptionClazz.getConstructor(String.class).newInstance("Simulating entity start failure for test");
-            throw e;
-        }
-    }
-    
-    @Override
-    public void stop() {
-        if (failOnStop) {
-            Exception e = exceptionClazz.getConstructor(String.class).newInstance("Simulating entity stop failure for test");
-            throw e;
-        }
-    }
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/d52e7ed2/core/src/test/java/brooklyn/entity/group/DynamicClusterTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/brooklyn/entity/group/DynamicClusterTest.java b/core/src/test/java/brooklyn/entity/group/DynamicClusterTest.java
new file mode 100644
index 0000000..9fb9230
--- /dev/null
+++ b/core/src/test/java/brooklyn/entity/group/DynamicClusterTest.java
@@ -0,0 +1,815 @@
+package brooklyn.entity.group;
+
+import static org.testng.Assert.assertEquals;
+import static org.testng.Assert.assertFalse;
+import static org.testng.Assert.assertNotNull;
+import static org.testng.Assert.assertTrue;
+import static org.testng.Assert.fail;
+
+import java.util.Collection;
+import java.util.List;
+import java.util.Map;
+import java.util.NoSuchElementException;
+import java.util.Random;
+import java.util.Set;
+import java.util.concurrent.CopyOnWriteArrayList;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.concurrent.atomic.AtomicReference;
+
+import org.testng.annotations.AfterMethod;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.Test;
+
+import brooklyn.entity.Entity;
+import brooklyn.entity.basic.ApplicationBuilder;
+import brooklyn.entity.basic.Attributes;
+import brooklyn.entity.basic.BrooklynTaskTags;
+import brooklyn.entity.basic.Entities;
+import brooklyn.entity.basic.EntityFactory;
+import brooklyn.entity.basic.Lifecycle;
+import brooklyn.entity.proxying.EntitySpec;
+import brooklyn.entity.trait.Changeable;
+import brooklyn.location.Location;
+import brooklyn.location.basic.SimulatedLocation;
+import brooklyn.management.Task;
+import brooklyn.test.Asserts;
+import brooklyn.test.entity.TestApplication;
+import brooklyn.test.entity.TestEntity;
+import brooklyn.test.entity.TestEntityImpl;
+import brooklyn.util.collections.MutableMap;
+import brooklyn.util.exceptions.Exceptions;
+import brooklyn.util.time.Time;
+
+import com.google.common.base.Function;
+import com.google.common.base.Predicates;
+import com.google.common.base.Throwables;
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.ImmutableSet;
+import com.google.common.collect.Iterables;
+import com.google.common.collect.Lists;
+import com.google.common.util.concurrent.Atomics;
+
+
+public class DynamicClusterTest {
+
+    private static final int TIMEOUT_MS = 2000;
+
+    TestApplication app;
+    SimulatedLocation loc;
+    SimulatedLocation loc2;
+    Random random = new Random();
+
+    @BeforeMethod
+    public void setUp() {
+        app = ApplicationBuilder.newManagedApp(TestApplication.class);
+        loc = new SimulatedLocation();
+        loc2 = new SimulatedLocation();
+    }
+
+    @AfterMethod(alwaysRun = true)
+    public void tearDown(){
+        if (app != null) Entities.destroyAll(app.getManagementContext());
+    }
+
+    @Test
+    public void creationOkayWithoutNewEntityFactoryArgument() throws Exception {
+        app.createAndManageChild(EntitySpec.create(DynamicCluster.class));
+    }
+
+    @Test
+    public void constructionRequiresThatNewEntityArgumentIsAnEntityFactory() throws Exception {
+        try {
+            app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
+                    .configure("factory", "error"));
+            fail();
+        } catch (Exception e) {
+            if (Exceptions.getFirstThrowableOfType(e, IllegalArgumentException.class) == null) throw e;
+        }
+    }
+
+    @Test
+    public void startRequiresThatNewEntityArgumentIsGiven() throws Exception {
+        DynamicCluster c = app.createAndManageChild(EntitySpec.create(DynamicCluster.class));
+        try {
+            c.start(ImmutableList.of(loc));
+            fail();
+        } catch (Exception e) {
+            if (Exceptions.getFirstThrowableOfType(e, IllegalStateException.class) == null) throw e;
+        }
+    }
+
+    @Test
+    public void startMethodFailsIfLocationsParameterHasMoreThanOneElement() throws Exception {
+        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
+                .configure(DynamicCluster.MEMBER_SPEC, EntitySpec.create(TestEntity.class)));
+        try {
+            cluster.start(ImmutableList.of(loc, loc2));
+            fail();
+        } catch (Exception e) {
+            if (Exceptions.getFirstThrowableOfType(e, IllegalArgumentException.class) == null) throw e;
+        }
+    }
+
+    @Test
+    public void testClusterHasOneLocationAfterStarting() throws Exception {
+        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
+                .configure(DynamicCluster.MEMBER_SPEC, EntitySpec.create(TestEntity.class)));
+        cluster.start(ImmutableList.of(loc));
+        assertEquals(cluster.getLocations().size(), 1);
+        assertEquals(ImmutableList.copyOf(cluster.getLocations()), ImmutableList.of(loc));
+    }
+
+    @Test
+    public void testServiceUpAfterStartingWithNoMembers() throws Exception {
+        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
+                .configure(DynamicCluster.MEMBER_SPEC, EntitySpec.create(TestEntity.class))
+                .configure(DynamicCluster.INITIAL_SIZE, 0));
+        cluster.start(ImmutableList.of(loc));
+        assertEquals(cluster.getAttribute(Attributes.SERVICE_STATE), Lifecycle.RUNNING);
+        assertTrue(cluster.getAttribute(Attributes.SERVICE_UP));
+    }
+
+    @Test
+    public void usingEntitySpecResizeFromZeroToOneStartsANewEntityAndSetsItsParent() throws Exception {
+        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
+                .configure("memberSpec", EntitySpec.create(TestEntity.class)));
+        
+        cluster.start(ImmutableList.of(loc));
+
+        cluster.resize(1);
+        TestEntity entity = (TestEntity) Iterables.getOnlyElement(cluster.getMembers());
+        assertEquals(entity.getCount(), 1);
+        assertEquals(entity.getParent(), cluster);
+        assertEquals(entity.getApplication(), app);
+    }
+
+    @Test
+    public void resizeFromZeroToOneStartsANewEntityAndSetsItsParent() throws Exception {
+        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
+                .configure("factory", new EntityFactory() {
+                    @Override public Entity newEntity(Map flags, Entity parent) {
+                        return new TestEntityImpl(flags);
+                    }}));
+
+        cluster.start(ImmutableList.of(loc));
+
+        cluster.resize(1);
+        TestEntity entity = (TestEntity) Iterables.get(cluster.getMembers(), 0);
+        assertEquals(entity.getCounter().get(), 1);
+        assertEquals(entity.getParent(), cluster);
+        assertEquals(entity.getApplication(), app);
+    }
+
+    @Test
+    public void currentSizePropertyReflectsActualClusterSize() throws Exception {
+        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
+                .configure("factory", new EntityFactory() {
+                    @Override public Entity newEntity(Map flags, Entity parent) {
+                        return new TestEntityImpl(flags);
+                    }}));
+
+
+        assertEquals(cluster.getCurrentSize(), (Integer)0);
+
+        cluster.start(ImmutableList.of(loc));
+        assertEquals(cluster.getCurrentSize(), (Integer)1);
+        assertEquals(cluster.getAttribute(Changeable.GROUP_SIZE), (Integer)1);
+
+        int newSize = cluster.resize(0);
+        assertEquals(newSize, 0);
+        assertEquals((Integer)newSize, cluster.getCurrentSize());
+        assertEquals(newSize, cluster.getMembers().size());
+        assertEquals((Integer)newSize, cluster.getAttribute(Changeable.GROUP_SIZE));
+
+        newSize = cluster.resize(4);
+        assertEquals(newSize, 4);
+        assertEquals((Integer)newSize, cluster.getCurrentSize());
+        assertEquals(newSize, cluster.getMembers().size());
+        assertEquals((Integer)newSize, cluster.getAttribute(Changeable.GROUP_SIZE));
+
+        newSize = cluster.resize(0);
+        assertEquals(newSize, 0);
+        assertEquals((Integer)newSize, cluster.getCurrentSize());
+        assertEquals(newSize, cluster.getMembers().size());
+        assertEquals((Integer)newSize, cluster.getAttribute(Changeable.GROUP_SIZE));
+    }
+
+    @Test
+    public void clusterSizeAfterStartIsInitialSize() throws Exception {
+        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
+                .configure("factory", new EntityFactory() {
+                    @Override public Entity newEntity(Map flags, Entity parent) {
+                        return new TestEntityImpl(flags);
+                    }})
+                .configure("initialSize", 2));
+
+        cluster.start(ImmutableList.of(loc));
+        assertEquals(cluster.getCurrentSize(), (Integer)2);
+        assertEquals(cluster.getMembers().size(), 2);
+        assertEquals(cluster.getAttribute(Changeable.GROUP_SIZE), (Integer)2);
+    }
+
+    @Test
+    public void clusterLocationIsPassedOnToEntityStart() throws Exception {
+        List<SimulatedLocation> locations = ImmutableList.of(loc);
+        final AtomicReference<Collection<? extends Location>> stashedLocations = Atomics.newReference();
+        
+        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
+                .configure("factory", new EntityFactory() {
+                    @Override public Entity newEntity(Map flags, Entity parent) {
+                        return new TestEntityImpl(parent) {
+                            @Override
+                            public void start(Collection<? extends Location> loc) {
+                                super.start(loc);
+                                stashedLocations.set(loc);
+                            }
+                        };
+                    }})
+                .configure("initialSize", 1));
+
+        cluster.start(locations);
+        TestEntity entity = (TestEntity) Iterables.get(cluster.getMembers(), 0);
+        
+        assertNotNull(stashedLocations.get());
+        assertEquals(stashedLocations.get().size(), 1);
+        assertEquals(ImmutableList.copyOf(stashedLocations.get()), locations);
+    }
+
+    @Test
+    public void resizeFromOneToZeroChangesClusterSize() throws Exception {
+        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
+                .configure("factory", new EntityFactory() {
+                    @Override public Entity newEntity(Map flags, Entity parent) {
+                        return new TestEntityImpl(flags);
+                    }})
+                .configure("initialSize", 1));
+
+        cluster.start(ImmutableList.of(loc));
+        TestEntity entity = (TestEntity) Iterables.get(cluster.getMembers(), 0);
+        assertEquals(cluster.getCurrentSize(), (Integer)1);
+        assertEquals(entity.getCounter().get(), 1);
+        
+        cluster.resize(0);
+        assertEquals(cluster.getCurrentSize(), (Integer)0);
+        assertEquals(entity.getCounter().get(), 0);
+    }
+
+    @Test
+    public void concurrentResizesToSameNumberCreatesCorrectNumberOfNodes() throws Exception {
+        final int OVERHEAD_MS = 500;
+        final int STARTUP_TIME_MS = 50;
+        final AtomicInteger numStarted = new AtomicInteger(0);
+        final DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
+                .configure("factory", new EntityFactory() {
+                    @Override public Entity newEntity(Map flags, Entity parent) {
+                        Time.sleep(STARTUP_TIME_MS);
+                        numStarted.incrementAndGet();
+                        return new TestEntityImpl(flags, parent);
+                    }}));
+
+        assertEquals(cluster.getCurrentSize(), (Integer)0);
+        cluster.start(ImmutableList.of(loc));
+
+        ExecutorService executor = Executors.newCachedThreadPool();
+        final List<Throwable> throwables = new CopyOnWriteArrayList<Throwable>();
+
+        try {
+            for (int i = 0; i < 10; i++) {
+                executor.submit(new Runnable() {
+                    public void run() {
+                        try {
+                            cluster.resize(2);
+                        } catch (Throwable e) {
+                            throwables.add(e);
+                        }
+                    }});
+            }
+
+            executor.shutdown();
+            assertTrue(executor.awaitTermination(10*STARTUP_TIME_MS+OVERHEAD_MS, TimeUnit.MILLISECONDS));
+            if (throwables.size() > 0) throw Exceptions.propagate(throwables.get(0));
+            assertEquals(cluster.getCurrentSize(), (Integer)2);
+            assertEquals(cluster.getAttribute(Changeable.GROUP_SIZE), (Integer)2);
+            assertEquals(numStarted.get(), 2);
+        } finally {
+            executor.shutdownNow();
+        }
+    }
+
+    @Test(enabled = false)
+    public void stoppingTheClusterStopsTheEntity() throws Exception {
+        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
+                .configure("factory", new EntityFactory() {
+                    @Override public Entity newEntity(Map flags, Entity parent) {
+                        return new TestEntityImpl(flags);
+                    }})
+                .configure("initialSize", 1));
+
+        cluster.start(ImmutableList.of(loc));
+        TestEntity entity = (TestEntity) Iterables.get(cluster.getMembers(), 0);
+        
+        assertEquals(entity.getCounter().get(), 1);
+        cluster.stop();
+        assertEquals(entity.getCounter().get(), 0);
+    }
+
+    /**
+     * This tests the fix for ENGR-1826.
+     */
+    @Test
+    public void failingEntitiesDontBreakClusterActions() throws Exception {
+        final int failNum = 2;
+        final AtomicInteger counter = new AtomicInteger(0);
+        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
+                .configure("initialSize", 0)
+                .configure("factory", new EntityFactory() {
+                    @Override public Entity newEntity(Map flags, Entity parent) {
+                        int num = counter.incrementAndGet();
+                        return new FailingEntity(flags, (num==failNum));
+                    }}));
+
+        cluster.start(ImmutableList.of(loc));
+        cluster.resize(3);
+        assertEquals(cluster.getCurrentSize(), (Integer)2);
+        assertEquals(cluster.getMembers().size(), 2);
+        for (Entity member : cluster.getMembers()) {
+            assertFalse(((FailingEntity)member).failOnStart);
+        }
+    }
+
+    @Test
+    public void testInitialQuorumSizeSufficientForStartup() throws Exception {
+        final int failNum = 1;
+        final AtomicInteger counter = new AtomicInteger(0);
+        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
+                .configure("initialSize", 2)
+                .configure(DynamicCluster.INITIAL_QUORUM_SIZE, 1)
+                .configure("factory", new EntityFactory() {
+                    @Override public Entity newEntity(Map flags, Entity parent) {
+                        int num = counter.incrementAndGet();
+                        return new FailingEntity(flags, (num==failNum));
+                    }}));
+
+        cluster.start(ImmutableList.of(loc));
+        
+        // note that children include quarantine group; and quarantined nodes
+        assertEquals(cluster.getCurrentSize(), (Integer)1);
+        assertEquals(cluster.getMembers().size(), 1);
+        for (Entity member : cluster.getMembers()) {
+            assertFalse(((FailingEntity)member).failOnStart);
+        }
+    }
+
+    @Test
+    public void testInitialQuorumSizeDefaultsToInitialSize() throws Exception {
+        final int failNum = 1;
+        final AtomicInteger counter = new AtomicInteger(0);
+        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
+                .configure("initialSize", 2)
+                .configure("factory", new EntityFactory() {
+                    @Override public Entity newEntity(Map flags, Entity parent) {
+                        int num = counter.incrementAndGet();
+                        return new FailingEntity(flags, (num==failNum));
+                    }}));
+
+        try {
+            cluster.start(ImmutableList.of(loc));
+        } catch (Exception e) {
+            IllegalStateException unwrapped = Exceptions.getFirstThrowableOfType(e, IllegalStateException.class);
+            if (unwrapped != null && unwrapped.getMessage().contains("failed to get to initial size")) {
+                // success
+            } else {
+                throw e; // fail
+            }
+        }
+        
+        // note that children include quarantine group; and quarantined nodes
+        assertEquals(cluster.getCurrentSize(), (Integer)1);
+        assertEquals(cluster.getMembers().size(), 1);
+        for (Entity member : cluster.getMembers()) {
+            assertFalse(((FailingEntity)member).failOnStart);
+        }
+    }
+
+    @Test
+    public void testCanQuarantineFailedEntities() throws Exception {
+        final int failNum = 2;
+        final AtomicInteger counter = new AtomicInteger(0);
+        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
+                .configure("quarantineFailedEntities", true)
+                .configure("initialSize", 0)
+                .configure("factory", new EntityFactory() {
+                    @Override public Entity newEntity(Map flags, Entity parent) {
+                        int num = counter.incrementAndGet();
+                        return new FailingEntity(flags, (num==failNum));
+                    }}));
+
+        cluster.start(ImmutableList.of(loc));
+        cluster.resize(3);
+        assertEquals(cluster.getCurrentSize(), (Integer)2);
+        assertEquals(cluster.getMembers().size(), 2);
+        assertEquals(Iterables.size(Iterables.filter(cluster.getChildren(), Predicates.instanceOf(FailingEntity.class))), 3);
+        for (Entity it : cluster.getMembers()) {
+            assertFalse(((FailingEntity)it).failOnStart);
+        }
+
+        assertEquals(cluster.getAttribute(DynamicCluster.QUARANTINE_GROUP).getMembers().size(), 1);
+        for (Entity it : cluster.getAttribute(DynamicCluster.QUARANTINE_GROUP).getMembers()) {
+            assertTrue(((FailingEntity)it).failOnStart);
+        }
+    }
+
+    @Test
+    public void testDoNotQuarantineFailedEntities() throws Exception {
+        final int failNum = 2;
+        final AtomicInteger counter = new AtomicInteger(0);
+        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
+                // default is quarantineFailedEntities==true
+                .configure("quarantineFailedEntities", false)
+                .configure("initialSize", 0)
+                .configure("factory", new EntityFactory() {
+                    @Override public Entity newEntity(Map flags, Entity parent) {
+                        int num = counter.incrementAndGet();
+                        return new FailingEntity(flags, (num==failNum));
+                    }}));
+
+        cluster.start(ImmutableList.of(loc));
+        
+        // no quarantine group, as a child
+        assertEquals(cluster.getChildren().size(), 0, "children="+cluster.getChildren());
+        
+        // Failed node will not be a member or child
+        cluster.resize(3);
+        assertEquals(cluster.getCurrentSize(), (Integer)2);
+        assertEquals(cluster.getMembers().size(), 2);
+        assertEquals(cluster.getChildren().size(), 2, "children="+cluster.getChildren());
+        
+        // Failed node will not be managed either
+        assertEquals(Iterables.size(Iterables.filter(cluster.getChildren(), Predicates.instanceOf(FailingEntity.class))), 2);
+        for (Entity member : cluster.getMembers()) {
+            assertFalse(((FailingEntity)member).failOnStart);
+        }
+    }
+
+    @Test
+    public void defaultRemovalStrategyShutsDownNewestFirstWhenResizing() throws Exception {
+        TestEntity entity;
+        final int failNum = 2;
+        final List<Entity> creationOrder = Lists.newArrayList();
+        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
+                .configure("initialSize", 0)
+                .configure("factory", new EntityFactory() {
+                    @Override public Entity newEntity(Map flags, Entity parent) {
+                        Entity result = new TestEntityImpl(flags);
+                        creationOrder.add(result);
+                        return result;
+                    }}));
+
+        cluster.start(ImmutableList.of(loc));
+        cluster.resize(1);
+        cluster.resize(2);
+        assertEquals(cluster.getCurrentSize(), (Integer)2);
+        assertEquals(ImmutableSet.copyOf(cluster.getMembers()), ImmutableSet.copyOf(creationOrder), "actual="+cluster.getMembers());
+
+        // Now stop one
+        cluster.resize(1);
+        assertEquals(cluster.getCurrentSize(), (Integer)1);
+        assertEquals(ImmutableList.copyOf(cluster.getMembers()), creationOrder.subList(0, 1));
+    }
+
+    @Test
+    public void resizeLoggedAsEffectorCall() throws Exception {
+        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
+                .configure("factory", new EntityFactory() {
+                    @Override public Entity newEntity(Map flags, Entity parent) {
+                        return new TestEntityImpl(flags);
+                    }}));
+
+        app.start(ImmutableList.of(loc));
+        cluster.resize(1);
+
+        Set<Task<?>> tasks = app.getManagementContext().getExecutionManager().getTasksWithAllTags(ImmutableList.of(
+            BrooklynTaskTags.tagForContextEntity(cluster),"EFFECTOR"));
+        assertEquals(tasks.size(), 2);
+        assertTrue(Iterables.get(tasks, 0).getDescription().contains("start"));
+        assertTrue(Iterables.get(tasks, 1).getDescription().contains("resize"));
+    }
+
+    @Test
+    public void testStoppedChildIsRemoveFromGroup() throws Exception {
+        final DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
+                .configure("initialSize", 1)
+                .configure("factory", new EntityFactory() {
+                    @Override public Entity newEntity(Map flags, Entity parent) {
+                        return new TestEntityImpl(flags);
+                    }}));
+
+        cluster.start(ImmutableList.of(loc));
+
+        final TestEntity child = (TestEntity) Iterables.get(cluster.getMembers(), 0);
+        child.stop();
+        Entities.unmanage(child);
+
+        Asserts.succeedsEventually(MutableMap.of("timeout", TIMEOUT_MS), new Runnable() {
+            @Override public void run() {
+                assertFalse(cluster.getChildren().contains(child), "children="+cluster.getChildren());
+                assertEquals(cluster.getCurrentSize(), (Integer)0);
+                assertEquals(cluster.getMembers().size(), 0);
+            }});
+    }
+
+    @Test
+    public void testPluggableRemovalStrategyIsUsed() throws Exception {
+        final List<Entity> removedEntities = Lists.newArrayList();
+
+        Function<Collection<Entity>, Entity> removalStrategy = new Function<Collection<Entity>, Entity>() {
+            @Override public Entity apply(Collection<Entity> contenders) {
+                Entity choice = Iterables.get(contenders, random.nextInt(contenders.size()));
+                removedEntities.add(choice);
+                return choice;
+            }
+        };
+
+        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
+                .configure("factory", new EntityFactory() {
+                    @Override public Entity newEntity(Map flags, Entity parent) {
+                        return new TestEntityImpl(flags);
+                    }})
+                .configure("initialSize", 10)
+                .configure("removalStrategy", removalStrategy));
+
+        cluster.start(ImmutableList.of(loc));
+        Set origMembers = ImmutableSet.copyOf(cluster.getMembers());
+
+        for (int i = 10; i >= 0; i--) {
+            cluster.resize(i);
+            assertEquals(cluster.getAttribute(Changeable.GROUP_SIZE), (Integer)i);
+            assertEquals(removedEntities.size(), 10-i);
+            assertEquals(ImmutableSet.copyOf(Iterables.concat(cluster.getMembers(), removedEntities)), origMembers);
+        }
+    }
+
+    @Test
+    public void testPluggableRemovalStrategyCanBeSetAfterConstruction() throws Exception {
+        final List<Entity> removedEntities = Lists.newArrayList();
+
+        Function<Collection<Entity>, Entity> removalStrategy = new Function<Collection<Entity>, Entity>() {
+            @Override public Entity apply(Collection<Entity> contenders) {
+                Entity choice = Iterables.get(contenders, random.nextInt(contenders.size()));
+                removedEntities.add(choice);
+                return choice;
+            }
+        };
+        
+        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
+                .configure("factory", new EntityFactory() {
+                    @Override public Entity newEntity(Map flags, Entity parent) {
+                        return new TestEntityImpl(flags);
+                    }})
+                .configure("initialSize", 10));
+
+        cluster.start(ImmutableList.of(loc));
+        Set origMembers = ImmutableSet.copyOf(cluster.getMembers());
+
+        cluster.setRemovalStrategy(removalStrategy);
+
+        for (int i = 10; i >= 0; i--) {
+            cluster.resize(i);
+            assertEquals(cluster.getAttribute(Changeable.GROUP_SIZE), (Integer)i);
+            assertEquals(removedEntities.size(), 10-i);
+            assertEquals(ImmutableSet.copyOf(Iterables.concat(cluster.getMembers(), removedEntities)), origMembers);
+        }
+    }
+
+    @Test
+    public void testResizeDoesNotBlockCallsToQueryGroupMembership() throws Exception {
+        final CountDownLatch executingLatch = new CountDownLatch(1);
+        final CountDownLatch continuationLatch = new CountDownLatch(1);
+        
+        final DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
+                .configure("initialSize", 0)
+                .configure("factory", new EntityFactory() {
+                    @Override public Entity newEntity(Map flags, Entity parent) {
+                        try {
+                            executingLatch.countDown();
+                            continuationLatch.await();
+                            return new TestEntityImpl(flags);
+                        } catch (InterruptedException e) {
+                            throw Exceptions.propagate(e);
+                        }
+                    }}));
+
+        cluster.start(ImmutableList.of(loc));
+
+        Thread thread = new Thread(new Runnable() {
+                @Override public void run() {
+                    cluster.resize(1);
+                }});
+        
+        try {
+            // wait for resize to be executing
+            thread.start();
+            executingLatch.await(TIMEOUT_MS, TimeUnit.MILLISECONDS);
+
+            // ensure can still call methods on group, to query/update membership
+            assertEquals(ImmutableList.copyOf(cluster.getMembers()), ImmutableList.of());
+            assertEquals(cluster.getCurrentSize(), (Integer)0);
+            assertFalse(cluster.hasMember(cluster));
+            cluster.addMember(cluster);
+            assertTrue(cluster.removeMember(cluster));
+
+            // allow the resize to complete
+            continuationLatch.countDown();
+            thread.join(TIMEOUT_MS);
+            assertFalse(thread.isAlive());
+        } finally {
+            thread.interrupt();
+        }
+    }
+
+    @Test
+    public void testReplacesMember() throws Exception {
+        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
+                .configure("initialSize", 1)
+                .configure("factory", new EntityFactory() {
+                    @Override public Entity newEntity(Map flags, Entity parent) {
+                        return new TestEntityImpl(flags);
+                    }}));
+
+        cluster.start(ImmutableList.of(loc));
+        Entity member = Iterables.get(cluster.getMembers(), 0);
+
+        String replacementId = cluster.replaceMember(member.getId());
+        Entity replacement = app.getManagementContext().getEntityManager().getEntity(replacementId);
+
+        assertEquals(cluster.getMembers().size(), 1);
+        assertFalse(cluster.getMembers().contains(member));
+        assertFalse(cluster.getChildren().contains(member));
+        assertNotNull(replacement, "replacementId="+replacementId);
+        assertTrue(cluster.getMembers().contains(replacement), "replacement="+replacement+"; members="+cluster.getMembers());
+        assertTrue(cluster.getChildren().contains(replacement), "replacement="+replacement+"; children="+cluster.getChildren());
+    }
+
+    @Test
+    public void testReplaceMemberThrowsIfMemberIdDoesNotResolve() throws Exception {
+        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
+                .configure("initialSize", 1)
+                .configure("factory", new EntityFactory() {
+                    @Override public Entity newEntity(Map flags, Entity parent) {
+                        return new TestEntityImpl(flags);
+                    }}));
+
+        cluster.start(ImmutableList.of(loc));
+        Entity member = Iterables.get(cluster.getMembers(), 0);
+
+        try {
+            cluster.replaceMember("wrong.id");
+            fail();
+        } catch (Exception e) {
+            if (Exceptions.getFirstThrowableOfType(e, NoSuchElementException.class) == null) throw e;
+            if (!Exceptions.getFirstThrowableOfType(e, NoSuchElementException.class).getMessage().contains("entity wrong.id cannot be resolved")) throw e;
+        }
+
+        assertEquals(ImmutableSet.copyOf(cluster.getMembers()), ImmutableSet.of(member));
+    }
+
+    @Test
+    public void testReplaceMemberThrowsIfNotMember() throws Exception {
+        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
+                .configure("initialSize", 1)
+                .configure("factory", new EntityFactory() {
+                    @Override public Entity newEntity(Map flags, Entity parent) {
+                        return new TestEntityImpl(flags);
+                    }}));
+
+        cluster.start(ImmutableList.of(loc));
+        Entity member = Iterables.get(cluster.getMembers(), 0);
+
+        try {
+            cluster.replaceMember(app.getId());
+            fail();
+        } catch (Exception e) {
+            if (Exceptions.getFirstThrowableOfType(e, NoSuchElementException.class) == null) throw e;
+            if (!Exceptions.getFirstThrowableOfType(e, NoSuchElementException.class).getMessage().contains("is not a member")) throw e;
+        }
+
+        assertEquals(ImmutableSet.copyOf(cluster.getMembers()), ImmutableSet.of(member));
+    }
+
+    @Test
+    public void testReplaceMemberFailsIfCantProvisionReplacement() throws Exception {
+        final int failNum = 2;
+        final AtomicInteger counter = new AtomicInteger(0);
+        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
+                .configure("factory", new EntityFactory() {
+                    @Override public Entity newEntity(Map flags, Entity parent) {
+                        int num = counter.incrementAndGet();
+                        return new FailingEntity(flags, (num==failNum));
+                    }}));
+
+        cluster.start(ImmutableList.of(loc));
+        Entity member = Iterables.get(cluster.getMembers(), 0);
+
+        try {
+            cluster.replaceMember(member.getId());
+            fail();
+        } catch (Exception e) {
+            if (!e.toString().contains("failed to grow")) throw e;
+            if (Exceptions.getFirstThrowableOfType(e, NoSuchElementException.class) != null) throw e;
+        }
+        assertEquals(ImmutableSet.copyOf(cluster.getMembers()), ImmutableSet.of(member));
+    }
+
+    @Test
+    public void testReplaceMemberRemovesAndThowsIfFailToStopOld() throws Exception {
+        final int failNum = 1;
+        final AtomicInteger counter = new AtomicInteger(0);
+        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
+                .configure("initialSize", 1)
+                .configure("factory", new EntityFactory() {
+                    @Override public Entity newEntity(Map flags, Entity parent) {
+                        int num = counter.incrementAndGet();
+                        return new FailingEntity(flags, false, (num==failNum), IllegalStateException.class);
+                    }}));
+
+        cluster.start(ImmutableList.of(loc));
+        Entity member = Iterables.get(cluster.getMembers(), 0);
+
+        try {
+            cluster.replaceMember(member.getId());
+            fail();
+        } catch (Exception e) {
+            if (Exceptions.getFirstThrowableOfType(e, StopFailedRuntimeException.class) == null) throw e;
+            boolean found = false;
+            for (Throwable t : Throwables.getCausalChain(e)) {
+                if (t.toString().contains("Simulating entity stop failure")) {
+                    found = true;
+                    break;
+                }
+            }
+            if (!found) throw e;
+        }
+        assertFalse(Entities.isManaged(member));
+        assertEquals(cluster.getMembers().size(), 1);
+    }
+
+    private Throwable unwrapException(Throwable e) {
+        if (e instanceof ExecutionException) {
+            return unwrapException(e.getCause());
+        } else if (e instanceof org.codehaus.groovy.runtime.InvokerInvocationException) {
+            return unwrapException(e.getCause());
+        } else {
+            return e;
+        }
+    }
+
+    public static class FailingEntity extends TestEntityImpl {
+        final boolean failOnStart;
+        final boolean failOnStop;
+        final Class<? extends Exception> exceptionClazz;
+    
+        public FailingEntity(Map flags, boolean failOnStart) {
+            this(flags, failOnStart, false);
+        }
+        
+        public FailingEntity(Map flags, boolean failOnStart, boolean failOnStop) {
+            this(flags, failOnStart, failOnStop, IllegalStateException.class);
+        }
+        
+        public FailingEntity(Map flags, boolean failOnStart, boolean failOnStop, Class<? extends Exception> exceptionClazz) {
+            super(flags);
+            this.failOnStart = failOnStart;
+            this.failOnStop = failOnStop;
+            this.exceptionClazz = exceptionClazz;
+        }
+        
+        @Override
+        public void start(Collection<? extends Location> locs) {
+            if (failOnStart) {
+                try {
+                    Exception e = exceptionClazz.getConstructor(String.class).newInstance("Simulating entity start failure for test");
+                    throw e;
+                } catch (Exception e) {
+                    throw Exceptions.propagate(e);
+                }
+            }
+        }
+        
+        @Override
+        public void stop() {
+            if (failOnStop) {
+                try {
+                    Exception e = exceptionClazz.getConstructor(String.class).newInstance("Simulating entity stop failure for test");
+                    throw e;
+                } catch (Exception e) {
+                    throw Exceptions.propagate(e);
+                }
+            }
+        }
+    }
+}
\ No newline at end of file


[05/50] [abbrv] git commit: Covert DynamicClusterTest from groovy to java

Posted by ri...@apache.org.
Covert DynamicClusterTest from groovy to java


Project: http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/commit/d52e7ed2
Tree: http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/tree/d52e7ed2
Diff: http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/diff/d52e7ed2

Branch: refs/pull/1405/merge
Commit: d52e7ed2fe0c2aa623bcacee6dd4f3638e2c5647
Parents: d3d5c11
Author: Aled Sage <al...@gmail.com>
Authored: Wed May 21 12:07:53 2014 +0100
Committer: Aled Sage <al...@gmail.com>
Committed: Wed May 21 15:52:41 2014 +0100

----------------------------------------------------------------------
 .../entity/group/DynamicClusterTest.groovy      | 726 -----------------
 .../entity/group/DynamicClusterTest.java        | 815 +++++++++++++++++++
 2 files changed, 815 insertions(+), 726 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/d52e7ed2/core/src/test/java/brooklyn/entity/group/DynamicClusterTest.groovy
----------------------------------------------------------------------
diff --git a/core/src/test/java/brooklyn/entity/group/DynamicClusterTest.groovy b/core/src/test/java/brooklyn/entity/group/DynamicClusterTest.groovy
deleted file mode 100644
index 636abbc..0000000
--- a/core/src/test/java/brooklyn/entity/group/DynamicClusterTest.groovy
+++ /dev/null
@@ -1,726 +0,0 @@
-package brooklyn.entity.group
-
-import brooklyn.entity.basic.Attributes
-import brooklyn.entity.basic.Lifecycle
-
-import static org.testng.Assert.*
-
-import java.util.concurrent.CopyOnWriteArrayList
-import java.util.concurrent.CountDownLatch
-import java.util.concurrent.ExecutionException
-import java.util.concurrent.ExecutorService
-import java.util.concurrent.Executors
-import java.util.concurrent.TimeUnit
-import java.util.concurrent.atomic.AtomicInteger
-
-import org.testng.annotations.AfterMethod
-import org.testng.annotations.BeforeMethod
-import org.testng.annotations.Test
-
-import brooklyn.entity.Application
-import brooklyn.entity.Entity
-import brooklyn.entity.basic.ApplicationBuilder
-import brooklyn.entity.basic.BrooklynTaskTags
-import brooklyn.entity.basic.Entities
-import brooklyn.entity.proxying.EntitySpec
-import brooklyn.entity.trait.Changeable
-import brooklyn.location.Location
-import brooklyn.location.basic.SimulatedLocation
-import brooklyn.management.Task
-import brooklyn.test.TestUtils
-import brooklyn.test.entity.TestApplication
-import brooklyn.test.entity.TestEntity
-import brooklyn.test.entity.TestEntityImpl
-import brooklyn.util.GroovyJavaMethods
-import brooklyn.util.exceptions.Exceptions
-
-import com.google.common.base.Predicates
-import com.google.common.base.Throwables;
-import com.google.common.collect.ImmutableList
-import com.google.common.collect.ImmutableSet
-import com.google.common.collect.Iterables
-
-
-class DynamicClusterTest {
-
-    private static final int TIMEOUT_MS = 2000
-
-    TestApplication app
-    SimulatedLocation loc
-    SimulatedLocation loc2
-    Random random = new Random()
-
-    @BeforeMethod
-    public void setUp() {
-        app = ApplicationBuilder.newManagedApp(TestApplication.class);
-        loc = new SimulatedLocation()
-        loc2 = new SimulatedLocation()
-    }
-
-    @AfterMethod(alwaysRun = true)
-    public void tearDown(){
-        if (app != null) Entities.destroyAll(app.getManagementContext());
-    }
-
-    @Test
-    public void creationOkayWithoutNewEntityFactoryArgument() {
-        app.createAndManageChild(EntitySpec.create(DynamicCluster.class));
-    }
-
-    @Test
-    public void constructionRequiresThatNewEntityArgumentIsAnEntityFactory() {
-        try {
-            app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
-                    .configure("factory", "error"));
-            fail();
-        } catch (Exception e) {
-            if (Exceptions.getFirstThrowableOfType(e, IllegalArgumentException.class) == null) throw e;
-        }
-    }
-
-    @Test
-    public void startRequiresThatNewEntityArgumentIsGiven() {
-        DynamicCluster c = app.createAndManageChild(EntitySpec.create(DynamicCluster.class));
-        try {
-            c.start([loc]);
-            fail();
-        } catch (Exception e) {
-            if (Exceptions.getFirstThrowableOfType(e, IllegalStateException.class) == null) throw e;
-        }
-    }
-
-    @Test
-    public void startMethodFailsIfLocationsParameterHasMoreThanOneElement() {
-        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
-                .configure("factory", { new TestEntityImpl() }));
-        try {
-            cluster.start([ loc, loc2 ])
-            fail();
-        } catch (Exception e) {
-            if (Exceptions.getFirstThrowableOfType(e, IllegalArgumentException.class) == null) throw e;
-        }
-    }
-
-    @Test
-    public void testClusterHasOneLocationAfterStarting() {
-        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
-                .configure("factory", { new TestEntityImpl() }));
-        cluster.start([loc])
-        assertEquals(cluster.getLocations().size(), 1)
-        assertEquals(cluster.getLocations() as List, [loc])
-    }
-
-    @Test
-    public void testServiceUpAfterStartingWithNoMembers() {
-        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
-                .configure(DynamicCluster.MEMBER_SPEC, EntitySpec.create(TestEntity.class))
-                .configure(DynamicCluster.INITIAL_SIZE, 0))
-        cluster.start([loc])
-        assertEquals(cluster.getAttribute(Attributes.SERVICE_STATE), Lifecycle.RUNNING)
-        assertTrue(cluster.getAttribute(Attributes.SERVICE_UP))
-    }
-
-    @Test
-    public void usingEntitySpecResizeFromZeroToOneStartsANewEntityAndSetsItsParent() {
-        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
-                .configure("memberSpec", EntitySpec.create(TestEntity.class)));
-        
-        cluster.start([loc])
-
-        cluster.resize(1)
-        Entity entity = Iterables.getOnlyElement(cluster.getMembers());
-        assertEquals entity.count, 1
-        assertEquals entity.parent, cluster
-        assertEquals entity.application, app
-    }
-
-    @Test
-    public void resizeFromZeroToOneStartsANewEntityAndSetsItsParent() {
-        TestEntity entity
-        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
-                .configure("factory", { properties -> entity = new TestEntityImpl(properties) }));
-
-        cluster.start([loc])
-
-        cluster.resize(1)
-        assertEquals entity.counter.get(), 1
-        assertEquals entity.parent, cluster
-        assertEquals entity.application, app
-    }
-
-    @Test
-    public void currentSizePropertyReflectsActualClusterSize() {
-        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
-                .configure("factory", { properties -> return new TestEntityImpl(properties) }));
-
-        assertEquals cluster.currentSize, 0
-
-        cluster.start([loc])
-        assertEquals cluster.currentSize, 1
-        assertEquals cluster.getAttribute(Changeable.GROUP_SIZE), 1
-
-        int newSize = cluster.resize(0)
-        assertEquals newSize, 0
-        assertEquals newSize, cluster.currentSize
-        assertEquals newSize, cluster.members.size()
-        assertEquals newSize, cluster.getAttribute(Changeable.GROUP_SIZE)
-
-        newSize = cluster.resize(4)
-        assertEquals newSize, 4
-        assertEquals newSize, cluster.currentSize
-        assertEquals newSize, cluster.members.size()
-        assertEquals newSize, cluster.getAttribute(Changeable.GROUP_SIZE)
-
-        newSize = cluster.resize(0)
-        assertEquals newSize, 0
-        assertEquals newSize, cluster.currentSize
-        assertEquals newSize, cluster.members.size()
-        assertEquals newSize, cluster.getAttribute(Changeable.GROUP_SIZE)
-    }
-
-    @Test
-    public void clusterSizeAfterStartIsInitialSize() {
-        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
-                .configure("factory", { properties -> return new TestEntityImpl(properties) })
-                .configure("initialSize", 2));
-
-        cluster.start([loc])
-        assertEquals cluster.currentSize, 2
-        assertEquals cluster.members.size(), 2
-        assertEquals cluster.getAttribute(Changeable.GROUP_SIZE), 2
-    }
-
-    @Test
-    public void clusterLocationIsPassedOnToEntityStart() {
-        Collection<Location> locations = [ loc ]
-        TestEntity entity
-        def newEntity = { properties, cluster ->
-            entity = new TestEntityImpl(parent:cluster) {
-	            List<Location> stashedLocations = null
-	            @Override
-	            void start(Collection<? extends Location> loc) {
-	                super.start(loc)
-	                stashedLocations = loc
-	            }
-	        }
-        }
-        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
-                .configure("factory", newEntity)
-                .configure("initialSize", 1));
-
-        cluster.start(locations)
-
-        assertNotNull entity.stashedLocations
-        assertEquals entity.stashedLocations.size(), 1
-        assertEquals entity.stashedLocations[0], locations[0]
-    }
-
-    @Test
-    public void resizeFromOneToZeroChangesClusterSize() {
-        TestEntity entity
-        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
-                .configure("factory", { properties -> entity = new TestEntityImpl(properties) })
-                .configure("initialSize", 1));
-
-        cluster.start([loc])
-        assertEquals cluster.currentSize, 1
-        assertEquals entity.counter.get(), 1
-        cluster.resize(0)
-        assertEquals cluster.currentSize, 0
-        assertEquals entity.counter.get(), 0
-    }
-
-    @Test
-    public void concurrentResizesToSameNumberCreatesCorrectNumberOfNodes() {
-        final int OVERHEAD_MS = 500
-        final int STARTUP_TIME_MS = 50
-        final AtomicInteger numStarted = new AtomicInteger(0)
-        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
-                .configure("factory", { 
-                    Map flags, Entity cluster -> 
-                    Thread.sleep(STARTUP_TIME_MS); numStarted.incrementAndGet(); new TestEntityImpl(flags, cluster)
-                }));
-
-        assertEquals cluster.currentSize, 0
-        cluster.start([loc])
-
-        ExecutorService executor = Executors.newCachedThreadPool()
-        List<Throwable> throwables = new CopyOnWriteArrayList<Throwable>()
-
-        try {
-            for (int i in 1..10) {
-                executor.submit( {
-                    try {
-                        cluster.resize(2)
-                    } catch (Throwable e) {
-                        throwables.add(e)
-                    }
-                })
-            }
-
-            executor.shutdown()
-            assertTrue(executor.awaitTermination(10*STARTUP_TIME_MS+OVERHEAD_MS, TimeUnit.MILLISECONDS))
-            if (throwables.size() > 0) throw throwables.get(0)
-            assertEquals(cluster.currentSize, 2)
-            assertEquals(cluster.getAttribute(Changeable.GROUP_SIZE), 2)
-            assertEquals(numStarted.get(), 2)
-        } finally {
-            executor.shutdownNow();
-        }
-    }
-
-    @Test(enabled = false)
-    public void stoppingTheClusterStopsTheEntity() {
-        TestEntity entity
-        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
-                .configure("factory", { properties -> entity = new TestEntityImpl(properties) })
-                .configure("initialSize", 1));
-
-        cluster.start([loc])
-        assertEquals entity.counter.get(), 1
-        cluster.stop()
-        assertEquals entity.counter.get(), 0
-    }
-
-    /**
-     * This tests the fix for ENGR-1826.
-     */
-    @Test
-    public void failingEntitiesDontBreakClusterActions() {
-        final int failNum = 2
-        final AtomicInteger counter = new AtomicInteger(0)
-        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
-                .configure("initialSize", 0)
-                .configure("factory", { properties ->
-                    int num = counter.incrementAndGet();
-                    return new FailingEntity(properties, (num==failNum))
-                }));
-
-        cluster.start([loc])
-        cluster.resize(3)
-        assertEquals(cluster.currentSize, 2)
-        assertEquals(cluster.getMembers().size(), 2)
-        for (Entity member : cluster.getMembers()) {
-            assertFalse(((FailingEntity)member).failOnStart)
-        }
-    }
-
-    @Test
-    public void testInitialQuorumSizeSufficientForStartup() {
-        final int failNum = 1;
-        final AtomicInteger counter = new AtomicInteger(0)
-        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
-                .configure("initialSize", 2)
-                .configure(DynamicCluster.INITIAL_QUORUM_SIZE, 1)
-                .configure("factory", { properties ->
-                    int num = counter.incrementAndGet();
-                    return new FailingEntity(properties, (num==failNum))
-                }));
-
-        cluster.start([loc])
-        
-        // note that children include quarantine group; and quarantined nodes
-        assertEquals(cluster.getCurrentSize(), 1)
-        assertEquals(cluster.getMembers().size(), 1)
-        for (Entity member : cluster.getMembers()) {
-            assertFalse(((FailingEntity)member).failOnStart)
-        }
-    }
-
-    @Test
-    public void testInitialQuorumSizeDefaultsToInitialSize() throws Exception {
-        final int failNum = 1;
-        final AtomicInteger counter = new AtomicInteger(0)
-        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
-                .configure("initialSize", 2)
-                .configure("factory", { properties ->
-                    int num = counter.incrementAndGet();
-                    return new FailingEntity(properties, (num==failNum))
-                }));
-
-        try {
-            cluster.start([loc])
-        } catch (Exception e) {
-            IllegalStateException unwrapped = Exceptions.getFirstThrowableOfType(e, IllegalStateException.class);
-            if (unwrapped != null && unwrapped.getMessage().contains("failed to get to initial size")) {
-                // success
-            } else {
-                throw e; // fail
-            }
-        }
-        
-        // note that children include quarantine group; and quarantined nodes
-        assertEquals(cluster.getCurrentSize(), 1)
-        assertEquals(cluster.getMembers().size(), 1)
-        for (Entity member : cluster.getMembers()) {
-            assertFalse(((FailingEntity)member).failOnStart)
-        }
-    }
-
-    @Test
-    public void testCanQuarantineFailedEntities() {
-        final int failNum = 2
-        final AtomicInteger counter = new AtomicInteger(0)
-        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
-                .configure("quarantineFailedEntities", true)
-                .configure("initialSize", 0)
-                .configure("factory", { properties ->
-                    int num = counter.incrementAndGet();
-                    return new FailingEntity(properties, (num==failNum))
-                }));
-
-        cluster.start([loc])
-        cluster.resize(3)
-        assertEquals(cluster.currentSize, 2)
-        assertEquals(cluster.getMembers().size(), 2)
-        assertEquals(Iterables.size(Iterables.filter(cluster.getChildren(), Predicates.instanceOf(FailingEntity.class))), 3)
-        cluster.members.each {
-            assertFalse(((FailingEntity)it).failOnStart)
-        }
-
-        assertEquals(cluster.getAttribute(DynamicCluster.QUARANTINE_GROUP).members.size(), 1)
-        cluster.getAttribute(DynamicCluster.QUARANTINE_GROUP).members.each {
-            assertTrue(((FailingEntity)it).failOnStart)
-        }
-    }
-
-    @Test
-    public void testDoNotQuarantineFailedEntities() {
-        final int failNum = 2
-        final AtomicInteger counter = new AtomicInteger(0)
-        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
-                // default is quarantineFailedEntities==true
-                .configure("quarantineFailedEntities", false)
-                .configure("initialSize", 0)
-                .configure("factory", { properties ->
-                    int num = counter.incrementAndGet();
-                    return new FailingEntity(properties, (num==failNum))
-                }));
-
-        cluster.start([loc])
-        
-        // no quarantine group, as a child
-        assertEquals(cluster.getChildren().size(), 0, "children="+cluster.getChildren())
-        
-        // Failed node will not be a member or child
-        cluster.resize(3)
-        assertEquals(cluster.currentSize, 2)
-        assertEquals(cluster.getMembers().size(), 2)
-        assertEquals(cluster.getChildren().size(), 2, "children="+cluster.getChildren())
-        
-        // Failed node will not be managed either
-        assertEquals(Iterables.size(Iterables.filter(cluster.getChildren(), Predicates.instanceOf(FailingEntity.class))), 2)
-        for (Entity member : cluster.getMembers()) {
-            assertFalse(((FailingEntity)member).failOnStart)
-        }
-    }
-
-    @Test
-    public void defaultRemovalStrategyShutsDownNewestFirstWhenResizing() {
-        TestEntity entity
-        final int failNum = 2
-        final List<Entity> creationOrder = []
-        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
-                .configure("initialSize", 0)
-                .configure("factory", { properties ->
-                    Entity result = new TestEntityImpl(properties)
-                    creationOrder << result
-                    return result
-                }));
-
-        cluster.start([loc])
-        cluster.resize(1)
-        cluster.resize(2)
-        assertEquals(cluster.currentSize, 2)
-        assertEquals(ImmutableSet.copyOf(cluster.getMembers()), ImmutableSet.copyOf(creationOrder), "actual="+cluster.getMembers())
-
-        // Now stop one
-        cluster.resize(1)
-        assertEquals(cluster.currentSize, 1)
-        assertEquals(ImmutableList.copyOf(cluster.getMembers()), creationOrder.subList(0, 1))
-    }
-
-    @Test
-    public void resizeLoggedAsEffectorCall() {
-        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
-                .configure("factory", { properties -> return new TestEntityImpl(properties) }));
-
-        app.start([loc])
-        cluster.resize(1)
-
-        Set<Task> tasks = app.getManagementContext().getExecutionManager().getTasksWithAllTags([
-            BrooklynTaskTags.tagForContextEntity(cluster),"EFFECTOR"])
-        assertEquals(tasks.size(), 2)
-        assertTrue(Iterables.get(tasks, 0).getDescription().contains("start"))
-        assertTrue(Iterables.get(tasks, 1).getDescription().contains("resize"))
-    }
-
-    @Test
-    public void testStoppedChildIsRemoveFromGroup() {
-        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
-                .configure("initialSize", 1)
-                .configure("factory", { properties -> return new TestEntityImpl(properties) }));
-
-        cluster.start([loc])
-
-        TestEntity child = Iterables.get(cluster.getMembers(), 0);
-        child.stop()
-        Entities.unmanage(child)
-
-        TestUtils.executeUntilSucceeds(timeout:TIMEOUT_MS) {
-            assertFalse(cluster.getChildren().contains(child), "children="+cluster.getChildren())
-            assertEquals(cluster.currentSize, 0)
-            assertEquals(cluster.members.size(), 0)
-        }
-    }
-
-    @Test
-    public void testPluggableRemovalStrategyIsUsed() {
-        List<Entity> removedEntities = []
-
-        Closure removalStrategy = { Collection<Entity> contenders ->
-            Entity choice = Iterables.get(contenders, random.nextInt(contenders.size()))
-            removedEntities.add(choice)
-            return choice
-        }
-        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
-                .configure("factory", { properties -> return new TestEntityImpl(properties) })
-                .configure("initialSize", 10)
-                .configure("removalStrategy", removalStrategy));
-
-        cluster.start([loc])
-        Set origMembers = cluster.members as Set
-
-        for (int i = 10; i >= 0; i--) {
-            cluster.resize(i)
-            assertEquals(cluster.getAttribute(Changeable.GROUP_SIZE), i)
-            assertEquals(removedEntities.size(), 10-i)
-            assertEquals(ImmutableSet.copyOf(Iterables.concat(cluster.members, removedEntities)), origMembers)
-        }
-    }
-
-    @Test
-    public void testPluggableRemovalStrategyCanBeSetAfterConstruction() {
-        List<Entity> removedEntities = []
-
-        Closure removalStrategy = { Collection<Entity> contenders ->
-            Entity choice = Iterables.get(contenders, random.nextInt(contenders.size()))
-            removedEntities.add(choice)
-            return choice
-        }
-        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
-                .configure("factory", { properties -> return new TestEntityImpl(properties) })
-                .configure("initialSize", 10));
-
-        cluster.start([loc])
-        Set origMembers = cluster.members as Set
-
-        cluster.setRemovalStrategy(GroovyJavaMethods.functionFromClosure(removalStrategy));
-
-        for (int i = 10; i >= 0; i--) {
-            cluster.resize(i)
-            assertEquals(cluster.getAttribute(Changeable.GROUP_SIZE), i)
-            assertEquals(removedEntities.size(), 10-i)
-            assertEquals(ImmutableSet.copyOf(Iterables.concat(cluster.members, removedEntities)), origMembers)
-        }
-    }
-
-    @Test
-    public void testResizeDoesNotBlockCallsToQueryGroupMembership() {
-        CountDownLatch executingLatch = new CountDownLatch(1)
-        CountDownLatch continuationLatch = new CountDownLatch(1)
-        
-        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
-                .configure("initialSize", 0)
-                .configure("factory", { properties ->
-                        executingLatch.countDown()
-                        continuationLatch.await()
-                        return new TestEntityImpl(properties)
-                    }));
-
-        cluster.start([loc])
-
-        Thread thread = new Thread( { cluster.resize(1) })
-        try {
-            // wait for resize to be executing
-            thread.start()
-            executingLatch.await(TIMEOUT_MS, TimeUnit.MILLISECONDS)
-
-            // ensure can still call methods on group, to query/update membership
-            assertEquals(cluster.getMembers(), [])
-            assertEquals(cluster.getCurrentSize(), 0)
-            assertFalse(cluster.hasMember(cluster))
-            cluster.addMember(cluster)
-            assertTrue(cluster.removeMember(cluster))
-
-            // allow the resize to complete
-            continuationLatch.countDown()
-            thread.join(TIMEOUT_MS)
-            assertFalse(thread.isAlive())
-        } finally {
-            thread.interrupt()
-        }
-    }
-
-    @Test
-    public void testReplacesMember() {
-        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
-                .configure("initialSize", 1)
-                .configure("factory", { properties -> return new TestEntityImpl(properties) }));
-
-        cluster.start([loc])
-        Entity member = Iterables.get(cluster.members, 0);
-
-        String replacementId = cluster.replaceMember(member.getId());
-        Entity replacement = cluster.getManagementContext().getEntityManager().getEntity(replacementId);
-
-        assertEquals(cluster.members.size(), 1)
-        assertFalse(cluster.members.contains(member))
-        assertFalse(cluster.children.contains(member))
-        assertNotNull(replacement, "replacementId="+replacementId);
-        assertTrue(cluster.members.contains(replacement), "replacement="+replacement+"; members="+cluster.members);
-        assertTrue(cluster.children.contains(replacement), "replacement="+replacement+"; children="+cluster.children);
-    }
-
-    @Test
-    public void testReplaceMemberThrowsIfMemberIdDoesNotResolve() {
-        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
-                .configure("initialSize", 1)
-                .configure("factory", { properties -> return new TestEntityImpl(properties) }));
-
-        cluster.start([loc])
-        Entity member = Iterables.get(cluster.members, 0);
-
-        try {
-            cluster.replaceMember("wrong.id");
-            fail();
-        } catch (Exception e) {
-            if (Exceptions.getFirstThrowableOfType(e, NoSuchElementException.class) == null) throw e;
-            if (!Exceptions.getFirstThrowableOfType(e, NoSuchElementException.class).getMessage().contains("entity wrong.id cannot be resolved")) throw e;
-        }
-
-        assertEquals(cluster.members as Set, ImmutableSet.of(member));
-    }
-
-    @Test
-    public void testReplaceMemberThrowsIfNotMember() {
-        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
-                .configure("initialSize", 1)
-                .configure("factory", { properties -> return new TestEntityImpl(properties) }));
-
-        cluster.start([loc])
-        Entity member = Iterables.get(cluster.members, 0);
-
-        try {
-            cluster.replaceMember(app.getId());
-            fail();
-        } catch (Exception e) {
-            if (Exceptions.getFirstThrowableOfType(e, NoSuchElementException.class) == null) throw e;
-            if (!Exceptions.getFirstThrowableOfType(e, NoSuchElementException.class).getMessage().contains("is not a member")) throw e;
-        }
-
-        assertEquals(cluster.members as Set, ImmutableSet.of(member));
-    }
-
-    @Test
-    public void testReplaceMemberFailsIfCantProvisionReplacement() {
-        final int failNum = 2
-        final AtomicInteger counter = new AtomicInteger(0)
-        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
-                .configure("factory", { properties -> 
-                    int num = counter.incrementAndGet();
-                    return new FailingEntity(properties, (num==failNum))
-                }));
-
-        cluster.start([loc])
-        Entity member = Iterables.get(cluster.members, 0);
-
-        try {
-            cluster.replaceMember(member.getId());
-            fail();
-        } catch (Exception e) {
-            if (!e.toString().contains("failed to grow")) throw e;
-            if (Exceptions.getFirstThrowableOfType(e, NoSuchElementException.class) != null) throw e;
-        }
-        assertEquals(cluster.members as Set, ImmutableSet.of(member));
-    }
-
-    @Test
-    public void testReplaceMemberRemovesAndThowsIfFailToStopOld() {
-        final int failNum = 1
-        final AtomicInteger counter = new AtomicInteger(0)
-        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
-                .configure("initialSize", 1)
-                .configure("factory", { properties ->
-                    int num = counter.incrementAndGet();
-                    return new FailingEntity(properties, false, (num==failNum), IllegalStateException.class)
-                }));
-
-        cluster.start([loc])
-        Entity member = Iterables.get(cluster.members, 0);
-
-        try {
-            cluster.replaceMember(member.getId());
-            fail();
-        } catch (Exception e) {
-            if (Exceptions.getFirstThrowableOfType(e, StopFailedRuntimeException.class) == null) throw e;
-            boolean found = false;
-            for (Throwable t : Throwables.getCausalChain(e)) {
-                if (t.toString().contains("Simulating entity stop failure")) {
-                    found = true;
-                    break;
-                }
-            }
-            if (!found) throw e;
-        }
-        assertFalse(Entities.isManaged(member));
-        assertEquals(cluster.members.size(), 1);
-    }
-
-    private Throwable unwrapException(Throwable e) {
-        if (e instanceof ExecutionException) {
-            return unwrapException(e.cause)
-        } else if (e instanceof org.codehaus.groovy.runtime.InvokerInvocationException) {
-            return unwrapException(e.cause)
-        } else {
-            return e
-        }
-    }
-}
-
-class FailingEntity extends TestEntityImpl {
-    final boolean failOnStart;
-    final boolean failOnStop;
-    final Class<? extends Exception> exceptionClazz;
-
-    public FailingEntity(Map flags, boolean failOnStart) {
-        this(flags, failOnStart, false);
-    }
-    
-    public FailingEntity(Map flags, boolean failOnStart, boolean failOnStop) {
-        this(flags, failOnStart, failOnStop, IllegalStateException.class);
-    }
-    
-    public FailingEntity(Map flags, boolean failOnStart, boolean failOnStop, Class<? extends Exception> exceptionClazz) {
-        super(flags)
-        this.failOnStart = failOnStart;
-        this.failOnStop = failOnStop;
-        this.exceptionClazz = exceptionClazz;
-    }
-    
-    @Override
-    public void start(Collection<? extends Location> locs) {
-        if (failOnStart) {
-            Exception e = exceptionClazz.getConstructor(String.class).newInstance("Simulating entity start failure for test");
-            throw e;
-        }
-    }
-    
-    @Override
-    public void stop() {
-        if (failOnStop) {
-            Exception e = exceptionClazz.getConstructor(String.class).newInstance("Simulating entity stop failure for test");
-            throw e;
-        }
-    }
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/d52e7ed2/core/src/test/java/brooklyn/entity/group/DynamicClusterTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/brooklyn/entity/group/DynamicClusterTest.java b/core/src/test/java/brooklyn/entity/group/DynamicClusterTest.java
new file mode 100644
index 0000000..9fb9230
--- /dev/null
+++ b/core/src/test/java/brooklyn/entity/group/DynamicClusterTest.java
@@ -0,0 +1,815 @@
+package brooklyn.entity.group;
+
+import static org.testng.Assert.assertEquals;
+import static org.testng.Assert.assertFalse;
+import static org.testng.Assert.assertNotNull;
+import static org.testng.Assert.assertTrue;
+import static org.testng.Assert.fail;
+
+import java.util.Collection;
+import java.util.List;
+import java.util.Map;
+import java.util.NoSuchElementException;
+import java.util.Random;
+import java.util.Set;
+import java.util.concurrent.CopyOnWriteArrayList;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.concurrent.atomic.AtomicReference;
+
+import org.testng.annotations.AfterMethod;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.Test;
+
+import brooklyn.entity.Entity;
+import brooklyn.entity.basic.ApplicationBuilder;
+import brooklyn.entity.basic.Attributes;
+import brooklyn.entity.basic.BrooklynTaskTags;
+import brooklyn.entity.basic.Entities;
+import brooklyn.entity.basic.EntityFactory;
+import brooklyn.entity.basic.Lifecycle;
+import brooklyn.entity.proxying.EntitySpec;
+import brooklyn.entity.trait.Changeable;
+import brooklyn.location.Location;
+import brooklyn.location.basic.SimulatedLocation;
+import brooklyn.management.Task;
+import brooklyn.test.Asserts;
+import brooklyn.test.entity.TestApplication;
+import brooklyn.test.entity.TestEntity;
+import brooklyn.test.entity.TestEntityImpl;
+import brooklyn.util.collections.MutableMap;
+import brooklyn.util.exceptions.Exceptions;
+import brooklyn.util.time.Time;
+
+import com.google.common.base.Function;
+import com.google.common.base.Predicates;
+import com.google.common.base.Throwables;
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.ImmutableSet;
+import com.google.common.collect.Iterables;
+import com.google.common.collect.Lists;
+import com.google.common.util.concurrent.Atomics;
+
+
+public class DynamicClusterTest {
+
+    private static final int TIMEOUT_MS = 2000;
+
+    TestApplication app;
+    SimulatedLocation loc;
+    SimulatedLocation loc2;
+    Random random = new Random();
+
+    @BeforeMethod
+    public void setUp() {
+        app = ApplicationBuilder.newManagedApp(TestApplication.class);
+        loc = new SimulatedLocation();
+        loc2 = new SimulatedLocation();
+    }
+
+    @AfterMethod(alwaysRun = true)
+    public void tearDown(){
+        if (app != null) Entities.destroyAll(app.getManagementContext());
+    }
+
+    @Test
+    public void creationOkayWithoutNewEntityFactoryArgument() throws Exception {
+        app.createAndManageChild(EntitySpec.create(DynamicCluster.class));
+    }
+
+    @Test
+    public void constructionRequiresThatNewEntityArgumentIsAnEntityFactory() throws Exception {
+        try {
+            app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
+                    .configure("factory", "error"));
+            fail();
+        } catch (Exception e) {
+            if (Exceptions.getFirstThrowableOfType(e, IllegalArgumentException.class) == null) throw e;
+        }
+    }
+
+    @Test
+    public void startRequiresThatNewEntityArgumentIsGiven() throws Exception {
+        DynamicCluster c = app.createAndManageChild(EntitySpec.create(DynamicCluster.class));
+        try {
+            c.start(ImmutableList.of(loc));
+            fail();
+        } catch (Exception e) {
+            if (Exceptions.getFirstThrowableOfType(e, IllegalStateException.class) == null) throw e;
+        }
+    }
+
+    @Test
+    public void startMethodFailsIfLocationsParameterHasMoreThanOneElement() throws Exception {
+        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
+                .configure(DynamicCluster.MEMBER_SPEC, EntitySpec.create(TestEntity.class)));
+        try {
+            cluster.start(ImmutableList.of(loc, loc2));
+            fail();
+        } catch (Exception e) {
+            if (Exceptions.getFirstThrowableOfType(e, IllegalArgumentException.class) == null) throw e;
+        }
+    }
+
+    @Test
+    public void testClusterHasOneLocationAfterStarting() throws Exception {
+        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
+                .configure(DynamicCluster.MEMBER_SPEC, EntitySpec.create(TestEntity.class)));
+        cluster.start(ImmutableList.of(loc));
+        assertEquals(cluster.getLocations().size(), 1);
+        assertEquals(ImmutableList.copyOf(cluster.getLocations()), ImmutableList.of(loc));
+    }
+
+    @Test
+    public void testServiceUpAfterStartingWithNoMembers() throws Exception {
+        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
+                .configure(DynamicCluster.MEMBER_SPEC, EntitySpec.create(TestEntity.class))
+                .configure(DynamicCluster.INITIAL_SIZE, 0));
+        cluster.start(ImmutableList.of(loc));
+        assertEquals(cluster.getAttribute(Attributes.SERVICE_STATE), Lifecycle.RUNNING);
+        assertTrue(cluster.getAttribute(Attributes.SERVICE_UP));
+    }
+
+    @Test
+    public void usingEntitySpecResizeFromZeroToOneStartsANewEntityAndSetsItsParent() throws Exception {
+        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
+                .configure("memberSpec", EntitySpec.create(TestEntity.class)));
+        
+        cluster.start(ImmutableList.of(loc));
+
+        cluster.resize(1);
+        TestEntity entity = (TestEntity) Iterables.getOnlyElement(cluster.getMembers());
+        assertEquals(entity.getCount(), 1);
+        assertEquals(entity.getParent(), cluster);
+        assertEquals(entity.getApplication(), app);
+    }
+
+    @Test
+    public void resizeFromZeroToOneStartsANewEntityAndSetsItsParent() throws Exception {
+        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
+                .configure("factory", new EntityFactory() {
+                    @Override public Entity newEntity(Map flags, Entity parent) {
+                        return new TestEntityImpl(flags);
+                    }}));
+
+        cluster.start(ImmutableList.of(loc));
+
+        cluster.resize(1);
+        TestEntity entity = (TestEntity) Iterables.get(cluster.getMembers(), 0);
+        assertEquals(entity.getCounter().get(), 1);
+        assertEquals(entity.getParent(), cluster);
+        assertEquals(entity.getApplication(), app);
+    }
+
+    @Test
+    public void currentSizePropertyReflectsActualClusterSize() throws Exception {
+        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
+                .configure("factory", new EntityFactory() {
+                    @Override public Entity newEntity(Map flags, Entity parent) {
+                        return new TestEntityImpl(flags);
+                    }}));
+
+
+        assertEquals(cluster.getCurrentSize(), (Integer)0);
+
+        cluster.start(ImmutableList.of(loc));
+        assertEquals(cluster.getCurrentSize(), (Integer)1);
+        assertEquals(cluster.getAttribute(Changeable.GROUP_SIZE), (Integer)1);
+
+        int newSize = cluster.resize(0);
+        assertEquals(newSize, 0);
+        assertEquals((Integer)newSize, cluster.getCurrentSize());
+        assertEquals(newSize, cluster.getMembers().size());
+        assertEquals((Integer)newSize, cluster.getAttribute(Changeable.GROUP_SIZE));
+
+        newSize = cluster.resize(4);
+        assertEquals(newSize, 4);
+        assertEquals((Integer)newSize, cluster.getCurrentSize());
+        assertEquals(newSize, cluster.getMembers().size());
+        assertEquals((Integer)newSize, cluster.getAttribute(Changeable.GROUP_SIZE));
+
+        newSize = cluster.resize(0);
+        assertEquals(newSize, 0);
+        assertEquals((Integer)newSize, cluster.getCurrentSize());
+        assertEquals(newSize, cluster.getMembers().size());
+        assertEquals((Integer)newSize, cluster.getAttribute(Changeable.GROUP_SIZE));
+    }
+
+    @Test
+    public void clusterSizeAfterStartIsInitialSize() throws Exception {
+        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
+                .configure("factory", new EntityFactory() {
+                    @Override public Entity newEntity(Map flags, Entity parent) {
+                        return new TestEntityImpl(flags);
+                    }})
+                .configure("initialSize", 2));
+
+        cluster.start(ImmutableList.of(loc));
+        assertEquals(cluster.getCurrentSize(), (Integer)2);
+        assertEquals(cluster.getMembers().size(), 2);
+        assertEquals(cluster.getAttribute(Changeable.GROUP_SIZE), (Integer)2);
+    }
+
+    @Test
+    public void clusterLocationIsPassedOnToEntityStart() throws Exception {
+        List<SimulatedLocation> locations = ImmutableList.of(loc);
+        final AtomicReference<Collection<? extends Location>> stashedLocations = Atomics.newReference();
+        
+        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
+                .configure("factory", new EntityFactory() {
+                    @Override public Entity newEntity(Map flags, Entity parent) {
+                        return new TestEntityImpl(parent) {
+                            @Override
+                            public void start(Collection<? extends Location> loc) {
+                                super.start(loc);
+                                stashedLocations.set(loc);
+                            }
+                        };
+                    }})
+                .configure("initialSize", 1));
+
+        cluster.start(locations);
+        TestEntity entity = (TestEntity) Iterables.get(cluster.getMembers(), 0);
+        
+        assertNotNull(stashedLocations.get());
+        assertEquals(stashedLocations.get().size(), 1);
+        assertEquals(ImmutableList.copyOf(stashedLocations.get()), locations);
+    }
+
+    @Test
+    public void resizeFromOneToZeroChangesClusterSize() throws Exception {
+        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
+                .configure("factory", new EntityFactory() {
+                    @Override public Entity newEntity(Map flags, Entity parent) {
+                        return new TestEntityImpl(flags);
+                    }})
+                .configure("initialSize", 1));
+
+        cluster.start(ImmutableList.of(loc));
+        TestEntity entity = (TestEntity) Iterables.get(cluster.getMembers(), 0);
+        assertEquals(cluster.getCurrentSize(), (Integer)1);
+        assertEquals(entity.getCounter().get(), 1);
+        
+        cluster.resize(0);
+        assertEquals(cluster.getCurrentSize(), (Integer)0);
+        assertEquals(entity.getCounter().get(), 0);
+    }
+
+    @Test
+    public void concurrentResizesToSameNumberCreatesCorrectNumberOfNodes() throws Exception {
+        final int OVERHEAD_MS = 500;
+        final int STARTUP_TIME_MS = 50;
+        final AtomicInteger numStarted = new AtomicInteger(0);
+        final DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
+                .configure("factory", new EntityFactory() {
+                    @Override public Entity newEntity(Map flags, Entity parent) {
+                        Time.sleep(STARTUP_TIME_MS);
+                        numStarted.incrementAndGet();
+                        return new TestEntityImpl(flags, parent);
+                    }}));
+
+        assertEquals(cluster.getCurrentSize(), (Integer)0);
+        cluster.start(ImmutableList.of(loc));
+
+        ExecutorService executor = Executors.newCachedThreadPool();
+        final List<Throwable> throwables = new CopyOnWriteArrayList<Throwable>();
+
+        try {
+            for (int i = 0; i < 10; i++) {
+                executor.submit(new Runnable() {
+                    public void run() {
+                        try {
+                            cluster.resize(2);
+                        } catch (Throwable e) {
+                            throwables.add(e);
+                        }
+                    }});
+            }
+
+            executor.shutdown();
+            assertTrue(executor.awaitTermination(10*STARTUP_TIME_MS+OVERHEAD_MS, TimeUnit.MILLISECONDS));
+            if (throwables.size() > 0) throw Exceptions.propagate(throwables.get(0));
+            assertEquals(cluster.getCurrentSize(), (Integer)2);
+            assertEquals(cluster.getAttribute(Changeable.GROUP_SIZE), (Integer)2);
+            assertEquals(numStarted.get(), 2);
+        } finally {
+            executor.shutdownNow();
+        }
+    }
+
+    @Test(enabled = false)
+    public void stoppingTheClusterStopsTheEntity() throws Exception {
+        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
+                .configure("factory", new EntityFactory() {
+                    @Override public Entity newEntity(Map flags, Entity parent) {
+                        return new TestEntityImpl(flags);
+                    }})
+                .configure("initialSize", 1));
+
+        cluster.start(ImmutableList.of(loc));
+        TestEntity entity = (TestEntity) Iterables.get(cluster.getMembers(), 0);
+        
+        assertEquals(entity.getCounter().get(), 1);
+        cluster.stop();
+        assertEquals(entity.getCounter().get(), 0);
+    }
+
+    /**
+     * This tests the fix for ENGR-1826.
+     */
+    @Test
+    public void failingEntitiesDontBreakClusterActions() throws Exception {
+        final int failNum = 2;
+        final AtomicInteger counter = new AtomicInteger(0);
+        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
+                .configure("initialSize", 0)
+                .configure("factory", new EntityFactory() {
+                    @Override public Entity newEntity(Map flags, Entity parent) {
+                        int num = counter.incrementAndGet();
+                        return new FailingEntity(flags, (num==failNum));
+                    }}));
+
+        cluster.start(ImmutableList.of(loc));
+        cluster.resize(3);
+        assertEquals(cluster.getCurrentSize(), (Integer)2);
+        assertEquals(cluster.getMembers().size(), 2);
+        for (Entity member : cluster.getMembers()) {
+            assertFalse(((FailingEntity)member).failOnStart);
+        }
+    }
+
+    @Test
+    public void testInitialQuorumSizeSufficientForStartup() throws Exception {
+        final int failNum = 1;
+        final AtomicInteger counter = new AtomicInteger(0);
+        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
+                .configure("initialSize", 2)
+                .configure(DynamicCluster.INITIAL_QUORUM_SIZE, 1)
+                .configure("factory", new EntityFactory() {
+                    @Override public Entity newEntity(Map flags, Entity parent) {
+                        int num = counter.incrementAndGet();
+                        return new FailingEntity(flags, (num==failNum));
+                    }}));
+
+        cluster.start(ImmutableList.of(loc));
+        
+        // note that children include quarantine group; and quarantined nodes
+        assertEquals(cluster.getCurrentSize(), (Integer)1);
+        assertEquals(cluster.getMembers().size(), 1);
+        for (Entity member : cluster.getMembers()) {
+            assertFalse(((FailingEntity)member).failOnStart);
+        }
+    }
+
+    @Test
+    public void testInitialQuorumSizeDefaultsToInitialSize() throws Exception {
+        final int failNum = 1;
+        final AtomicInteger counter = new AtomicInteger(0);
+        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
+                .configure("initialSize", 2)
+                .configure("factory", new EntityFactory() {
+                    @Override public Entity newEntity(Map flags, Entity parent) {
+                        int num = counter.incrementAndGet();
+                        return new FailingEntity(flags, (num==failNum));
+                    }}));
+
+        try {
+            cluster.start(ImmutableList.of(loc));
+        } catch (Exception e) {
+            IllegalStateException unwrapped = Exceptions.getFirstThrowableOfType(e, IllegalStateException.class);
+            if (unwrapped != null && unwrapped.getMessage().contains("failed to get to initial size")) {
+                // success
+            } else {
+                throw e; // fail
+            }
+        }
+        
+        // note that children include quarantine group; and quarantined nodes
+        assertEquals(cluster.getCurrentSize(), (Integer)1);
+        assertEquals(cluster.getMembers().size(), 1);
+        for (Entity member : cluster.getMembers()) {
+            assertFalse(((FailingEntity)member).failOnStart);
+        }
+    }
+
+    @Test
+    public void testCanQuarantineFailedEntities() throws Exception {
+        final int failNum = 2;
+        final AtomicInteger counter = new AtomicInteger(0);
+        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
+                .configure("quarantineFailedEntities", true)
+                .configure("initialSize", 0)
+                .configure("factory", new EntityFactory() {
+                    @Override public Entity newEntity(Map flags, Entity parent) {
+                        int num = counter.incrementAndGet();
+                        return new FailingEntity(flags, (num==failNum));
+                    }}));
+
+        cluster.start(ImmutableList.of(loc));
+        cluster.resize(3);
+        assertEquals(cluster.getCurrentSize(), (Integer)2);
+        assertEquals(cluster.getMembers().size(), 2);
+        assertEquals(Iterables.size(Iterables.filter(cluster.getChildren(), Predicates.instanceOf(FailingEntity.class))), 3);
+        for (Entity it : cluster.getMembers()) {
+            assertFalse(((FailingEntity)it).failOnStart);
+        }
+
+        assertEquals(cluster.getAttribute(DynamicCluster.QUARANTINE_GROUP).getMembers().size(), 1);
+        for (Entity it : cluster.getAttribute(DynamicCluster.QUARANTINE_GROUP).getMembers()) {
+            assertTrue(((FailingEntity)it).failOnStart);
+        }
+    }
+
+    @Test
+    public void testDoNotQuarantineFailedEntities() throws Exception {
+        final int failNum = 2;
+        final AtomicInteger counter = new AtomicInteger(0);
+        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
+                // default is quarantineFailedEntities==true
+                .configure("quarantineFailedEntities", false)
+                .configure("initialSize", 0)
+                .configure("factory", new EntityFactory() {
+                    @Override public Entity newEntity(Map flags, Entity parent) {
+                        int num = counter.incrementAndGet();
+                        return new FailingEntity(flags, (num==failNum));
+                    }}));
+
+        cluster.start(ImmutableList.of(loc));
+        
+        // no quarantine group, as a child
+        assertEquals(cluster.getChildren().size(), 0, "children="+cluster.getChildren());
+        
+        // Failed node will not be a member or child
+        cluster.resize(3);
+        assertEquals(cluster.getCurrentSize(), (Integer)2);
+        assertEquals(cluster.getMembers().size(), 2);
+        assertEquals(cluster.getChildren().size(), 2, "children="+cluster.getChildren());
+        
+        // Failed node will not be managed either
+        assertEquals(Iterables.size(Iterables.filter(cluster.getChildren(), Predicates.instanceOf(FailingEntity.class))), 2);
+        for (Entity member : cluster.getMembers()) {
+            assertFalse(((FailingEntity)member).failOnStart);
+        }
+    }
+
+    @Test
+    public void defaultRemovalStrategyShutsDownNewestFirstWhenResizing() throws Exception {
+        TestEntity entity;
+        final int failNum = 2;
+        final List<Entity> creationOrder = Lists.newArrayList();
+        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
+                .configure("initialSize", 0)
+                .configure("factory", new EntityFactory() {
+                    @Override public Entity newEntity(Map flags, Entity parent) {
+                        Entity result = new TestEntityImpl(flags);
+                        creationOrder.add(result);
+                        return result;
+                    }}));
+
+        cluster.start(ImmutableList.of(loc));
+        cluster.resize(1);
+        cluster.resize(2);
+        assertEquals(cluster.getCurrentSize(), (Integer)2);
+        assertEquals(ImmutableSet.copyOf(cluster.getMembers()), ImmutableSet.copyOf(creationOrder), "actual="+cluster.getMembers());
+
+        // Now stop one
+        cluster.resize(1);
+        assertEquals(cluster.getCurrentSize(), (Integer)1);
+        assertEquals(ImmutableList.copyOf(cluster.getMembers()), creationOrder.subList(0, 1));
+    }
+
+    @Test
+    public void resizeLoggedAsEffectorCall() throws Exception {
+        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
+                .configure("factory", new EntityFactory() {
+                    @Override public Entity newEntity(Map flags, Entity parent) {
+                        return new TestEntityImpl(flags);
+                    }}));
+
+        app.start(ImmutableList.of(loc));
+        cluster.resize(1);
+
+        Set<Task<?>> tasks = app.getManagementContext().getExecutionManager().getTasksWithAllTags(ImmutableList.of(
+            BrooklynTaskTags.tagForContextEntity(cluster),"EFFECTOR"));
+        assertEquals(tasks.size(), 2);
+        assertTrue(Iterables.get(tasks, 0).getDescription().contains("start"));
+        assertTrue(Iterables.get(tasks, 1).getDescription().contains("resize"));
+    }
+
+    @Test
+    public void testStoppedChildIsRemoveFromGroup() throws Exception {
+        final DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
+                .configure("initialSize", 1)
+                .configure("factory", new EntityFactory() {
+                    @Override public Entity newEntity(Map flags, Entity parent) {
+                        return new TestEntityImpl(flags);
+                    }}));
+
+        cluster.start(ImmutableList.of(loc));
+
+        final TestEntity child = (TestEntity) Iterables.get(cluster.getMembers(), 0);
+        child.stop();
+        Entities.unmanage(child);
+
+        Asserts.succeedsEventually(MutableMap.of("timeout", TIMEOUT_MS), new Runnable() {
+            @Override public void run() {
+                assertFalse(cluster.getChildren().contains(child), "children="+cluster.getChildren());
+                assertEquals(cluster.getCurrentSize(), (Integer)0);
+                assertEquals(cluster.getMembers().size(), 0);
+            }});
+    }
+
+    @Test
+    public void testPluggableRemovalStrategyIsUsed() throws Exception {
+        final List<Entity> removedEntities = Lists.newArrayList();
+
+        Function<Collection<Entity>, Entity> removalStrategy = new Function<Collection<Entity>, Entity>() {
+            @Override public Entity apply(Collection<Entity> contenders) {
+                Entity choice = Iterables.get(contenders, random.nextInt(contenders.size()));
+                removedEntities.add(choice);
+                return choice;
+            }
+        };
+
+        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
+                .configure("factory", new EntityFactory() {
+                    @Override public Entity newEntity(Map flags, Entity parent) {
+                        return new TestEntityImpl(flags);
+                    }})
+                .configure("initialSize", 10)
+                .configure("removalStrategy", removalStrategy));
+
+        cluster.start(ImmutableList.of(loc));
+        Set origMembers = ImmutableSet.copyOf(cluster.getMembers());
+
+        for (int i = 10; i >= 0; i--) {
+            cluster.resize(i);
+            assertEquals(cluster.getAttribute(Changeable.GROUP_SIZE), (Integer)i);
+            assertEquals(removedEntities.size(), 10-i);
+            assertEquals(ImmutableSet.copyOf(Iterables.concat(cluster.getMembers(), removedEntities)), origMembers);
+        }
+    }
+
+    @Test
+    public void testPluggableRemovalStrategyCanBeSetAfterConstruction() throws Exception {
+        final List<Entity> removedEntities = Lists.newArrayList();
+
+        Function<Collection<Entity>, Entity> removalStrategy = new Function<Collection<Entity>, Entity>() {
+            @Override public Entity apply(Collection<Entity> contenders) {
+                Entity choice = Iterables.get(contenders, random.nextInt(contenders.size()));
+                removedEntities.add(choice);
+                return choice;
+            }
+        };
+        
+        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
+                .configure("factory", new EntityFactory() {
+                    @Override public Entity newEntity(Map flags, Entity parent) {
+                        return new TestEntityImpl(flags);
+                    }})
+                .configure("initialSize", 10));
+
+        cluster.start(ImmutableList.of(loc));
+        Set origMembers = ImmutableSet.copyOf(cluster.getMembers());
+
+        cluster.setRemovalStrategy(removalStrategy);
+
+        for (int i = 10; i >= 0; i--) {
+            cluster.resize(i);
+            assertEquals(cluster.getAttribute(Changeable.GROUP_SIZE), (Integer)i);
+            assertEquals(removedEntities.size(), 10-i);
+            assertEquals(ImmutableSet.copyOf(Iterables.concat(cluster.getMembers(), removedEntities)), origMembers);
+        }
+    }
+
+    @Test
+    public void testResizeDoesNotBlockCallsToQueryGroupMembership() throws Exception {
+        final CountDownLatch executingLatch = new CountDownLatch(1);
+        final CountDownLatch continuationLatch = new CountDownLatch(1);
+        
+        final DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
+                .configure("initialSize", 0)
+                .configure("factory", new EntityFactory() {
+                    @Override public Entity newEntity(Map flags, Entity parent) {
+                        try {
+                            executingLatch.countDown();
+                            continuationLatch.await();
+                            return new TestEntityImpl(flags);
+                        } catch (InterruptedException e) {
+                            throw Exceptions.propagate(e);
+                        }
+                    }}));
+
+        cluster.start(ImmutableList.of(loc));
+
+        Thread thread = new Thread(new Runnable() {
+                @Override public void run() {
+                    cluster.resize(1);
+                }});
+        
+        try {
+            // wait for resize to be executing
+            thread.start();
+            executingLatch.await(TIMEOUT_MS, TimeUnit.MILLISECONDS);
+
+            // ensure can still call methods on group, to query/update membership
+            assertEquals(ImmutableList.copyOf(cluster.getMembers()), ImmutableList.of());
+            assertEquals(cluster.getCurrentSize(), (Integer)0);
+            assertFalse(cluster.hasMember(cluster));
+            cluster.addMember(cluster);
+            assertTrue(cluster.removeMember(cluster));
+
+            // allow the resize to complete
+            continuationLatch.countDown();
+            thread.join(TIMEOUT_MS);
+            assertFalse(thread.isAlive());
+        } finally {
+            thread.interrupt();
+        }
+    }
+
+    @Test
+    public void testReplacesMember() throws Exception {
+        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
+                .configure("initialSize", 1)
+                .configure("factory", new EntityFactory() {
+                    @Override public Entity newEntity(Map flags, Entity parent) {
+                        return new TestEntityImpl(flags);
+                    }}));
+
+        cluster.start(ImmutableList.of(loc));
+        Entity member = Iterables.get(cluster.getMembers(), 0);
+
+        String replacementId = cluster.replaceMember(member.getId());
+        Entity replacement = app.getManagementContext().getEntityManager().getEntity(replacementId);
+
+        assertEquals(cluster.getMembers().size(), 1);
+        assertFalse(cluster.getMembers().contains(member));
+        assertFalse(cluster.getChildren().contains(member));
+        assertNotNull(replacement, "replacementId="+replacementId);
+        assertTrue(cluster.getMembers().contains(replacement), "replacement="+replacement+"; members="+cluster.getMembers());
+        assertTrue(cluster.getChildren().contains(replacement), "replacement="+replacement+"; children="+cluster.getChildren());
+    }
+
+    @Test
+    public void testReplaceMemberThrowsIfMemberIdDoesNotResolve() throws Exception {
+        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
+                .configure("initialSize", 1)
+                .configure("factory", new EntityFactory() {
+                    @Override public Entity newEntity(Map flags, Entity parent) {
+                        return new TestEntityImpl(flags);
+                    }}));
+
+        cluster.start(ImmutableList.of(loc));
+        Entity member = Iterables.get(cluster.getMembers(), 0);
+
+        try {
+            cluster.replaceMember("wrong.id");
+            fail();
+        } catch (Exception e) {
+            if (Exceptions.getFirstThrowableOfType(e, NoSuchElementException.class) == null) throw e;
+            if (!Exceptions.getFirstThrowableOfType(e, NoSuchElementException.class).getMessage().contains("entity wrong.id cannot be resolved")) throw e;
+        }
+
+        assertEquals(ImmutableSet.copyOf(cluster.getMembers()), ImmutableSet.of(member));
+    }
+
+    @Test
+    public void testReplaceMemberThrowsIfNotMember() throws Exception {
+        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
+                .configure("initialSize", 1)
+                .configure("factory", new EntityFactory() {
+                    @Override public Entity newEntity(Map flags, Entity parent) {
+                        return new TestEntityImpl(flags);
+                    }}));
+
+        cluster.start(ImmutableList.of(loc));
+        Entity member = Iterables.get(cluster.getMembers(), 0);
+
+        try {
+            cluster.replaceMember(app.getId());
+            fail();
+        } catch (Exception e) {
+            if (Exceptions.getFirstThrowableOfType(e, NoSuchElementException.class) == null) throw e;
+            if (!Exceptions.getFirstThrowableOfType(e, NoSuchElementException.class).getMessage().contains("is not a member")) throw e;
+        }
+
+        assertEquals(ImmutableSet.copyOf(cluster.getMembers()), ImmutableSet.of(member));
+    }
+
+    @Test
+    public void testReplaceMemberFailsIfCantProvisionReplacement() throws Exception {
+        final int failNum = 2;
+        final AtomicInteger counter = new AtomicInteger(0);
+        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
+                .configure("factory", new EntityFactory() {
+                    @Override public Entity newEntity(Map flags, Entity parent) {
+                        int num = counter.incrementAndGet();
+                        return new FailingEntity(flags, (num==failNum));
+                    }}));
+
+        cluster.start(ImmutableList.of(loc));
+        Entity member = Iterables.get(cluster.getMembers(), 0);
+
+        try {
+            cluster.replaceMember(member.getId());
+            fail();
+        } catch (Exception e) {
+            if (!e.toString().contains("failed to grow")) throw e;
+            if (Exceptions.getFirstThrowableOfType(e, NoSuchElementException.class) != null) throw e;
+        }
+        assertEquals(ImmutableSet.copyOf(cluster.getMembers()), ImmutableSet.of(member));
+    }
+
+    @Test
+    public void testReplaceMemberRemovesAndThowsIfFailToStopOld() throws Exception {
+        final int failNum = 1;
+        final AtomicInteger counter = new AtomicInteger(0);
+        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
+                .configure("initialSize", 1)
+                .configure("factory", new EntityFactory() {
+                    @Override public Entity newEntity(Map flags, Entity parent) {
+                        int num = counter.incrementAndGet();
+                        return new FailingEntity(flags, false, (num==failNum), IllegalStateException.class);
+                    }}));
+
+        cluster.start(ImmutableList.of(loc));
+        Entity member = Iterables.get(cluster.getMembers(), 0);
+
+        try {
+            cluster.replaceMember(member.getId());
+            fail();
+        } catch (Exception e) {
+            if (Exceptions.getFirstThrowableOfType(e, StopFailedRuntimeException.class) == null) throw e;
+            boolean found = false;
+            for (Throwable t : Throwables.getCausalChain(e)) {
+                if (t.toString().contains("Simulating entity stop failure")) {
+                    found = true;
+                    break;
+                }
+            }
+            if (!found) throw e;
+        }
+        assertFalse(Entities.isManaged(member));
+        assertEquals(cluster.getMembers().size(), 1);
+    }
+
+    private Throwable unwrapException(Throwable e) {
+        if (e instanceof ExecutionException) {
+            return unwrapException(e.getCause());
+        } else if (e instanceof org.codehaus.groovy.runtime.InvokerInvocationException) {
+            return unwrapException(e.getCause());
+        } else {
+            return e;
+        }
+    }
+
+    public static class FailingEntity extends TestEntityImpl {
+        final boolean failOnStart;
+        final boolean failOnStop;
+        final Class<? extends Exception> exceptionClazz;
+    
+        public FailingEntity(Map flags, boolean failOnStart) {
+            this(flags, failOnStart, false);
+        }
+        
+        public FailingEntity(Map flags, boolean failOnStart, boolean failOnStop) {
+            this(flags, failOnStart, failOnStop, IllegalStateException.class);
+        }
+        
+        public FailingEntity(Map flags, boolean failOnStart, boolean failOnStop, Class<? extends Exception> exceptionClazz) {
+            super(flags);
+            this.failOnStart = failOnStart;
+            this.failOnStop = failOnStop;
+            this.exceptionClazz = exceptionClazz;
+        }
+        
+        @Override
+        public void start(Collection<? extends Location> locs) {
+            if (failOnStart) {
+                try {
+                    Exception e = exceptionClazz.getConstructor(String.class).newInstance("Simulating entity start failure for test");
+                    throw e;
+                } catch (Exception e) {
+                    throw Exceptions.propagate(e);
+                }
+            }
+        }
+        
+        @Override
+        public void stop() {
+            if (failOnStop) {
+                try {
+                    Exception e = exceptionClazz.getConstructor(String.class).newInstance("Simulating entity stop failure for test");
+                    throw e;
+                } catch (Exception e) {
+                    throw Exceptions.propagate(e);
+                }
+            }
+        }
+    }
+}
\ No newline at end of file


[30/50] [abbrv] git commit: Merge pull request #1398 from aledsage/refactor/DynamicClusterTest-from-groovy-to-java

Posted by ri...@apache.org.
Merge pull request #1398 from aledsage/refactor/DynamicClusterTest-from-groovy-to-java

Refactor DynamicClusterTest from groovy to java (and tidies)

Project: http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/commit/cb2d0d3a
Tree: http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/tree/cb2d0d3a
Diff: http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/diff/cb2d0d3a

Branch: refs/pull/1405/merge
Commit: cb2d0d3a184095b4bfdefe73a95435f4e4beb906
Parents: 48a34e4 b0e541e
Author: Andrew Kennedy <gr...@apache.org>
Authored: Fri May 23 17:18:40 2014 +0100
Committer: Andrew Kennedy <gr...@apache.org>
Committed: Fri May 23 17:18:40 2014 +0100

----------------------------------------------------------------------
 .../entity/group/DynamicClusterTest.groovy      | 726 -----------------
 .../entity/group/DynamicClusterTest.java        | 790 +++++++++++++++++++
 2 files changed, 790 insertions(+), 726 deletions(-)
----------------------------------------------------------------------



[20/50] [abbrv] git commit: More enricher and policy persistance changes

Posted by ri...@apache.org.
More enricher and policy persistance changes


Project: http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/commit/80532a5b
Tree: http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/tree/80532a5b
Diff: http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/diff/80532a5b

Branch: refs/pull/1413/merge
Commit: 80532a5bcea8334f1c012657448e302230d7247d
Parents: 34d4f8a
Author: Andrew Kennedy <an...@cloudsoftcorp.com>
Authored: Thu May 22 17:24:03 2014 +0100
Committer: Andrew Kennedy <an...@cloudsoftcorp.com>
Committed: Thu May 22 17:57:52 2014 +0100

----------------------------------------------------------------------
 .../brooklyn/entity/rebind/ChangeListener.java  |  4 ++
 .../brooklyn/entity/rebind/RebindContext.java   | 12 ++--
 .../mementos/BrooklynMementoPersister.java      |  4 ++
 api/src/main/java/brooklyn/policy/Enricher.java | 17 +++--
 .../enricher/basic/AbstractEnricher.java        |  8 +++
 .../rebind/BasicEnricherRebindSupport.java      | 28 ++++----
 .../entity/rebind/BasicEntityRebindSupport.java | 20 +++++-
 .../rebind/ImmediateDeltaChangeListener.java    | 10 +++
 .../rebind/PeriodicDeltaChangeListener.java     | 35 +++++++--
 .../entity/rebind/PersisterDeltaImpl.java       | 13 ++++
 .../entity/rebind/RebindContextImpl.java        | 11 +++
 .../entity/rebind/RebindManagerImpl.java        | 76 +++++++++++++++++++-
 .../entity/rebind/dto/BrooklynMementoImpl.java  | 25 +++++++
 .../rebind/dto/BrooklynMementoManifestImpl.java | 14 ++++
 .../AbstractBrooklynMementoPersister.java       |  6 ++
 .../BrooklynMementoPersisterInMemory.java       | 12 ++++
 .../BrooklynMementoPersisterToMultiFile.java    | 71 +++++++++++++++---
 .../rebind/persister/XmlMementoSerializer.java  | 31 +++++++-
 .../internal/EntityChangeListener.java          |  2 +-
 .../internal/EntityManagementSupport.java       |  2 +
 .../persister/XmlMementoSerializerTest.java     | 75 ++++++++++++-------
 21 files changed, 408 insertions(+), 68 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/80532a5b/api/src/main/java/brooklyn/entity/rebind/ChangeListener.java
----------------------------------------------------------------------
diff --git a/api/src/main/java/brooklyn/entity/rebind/ChangeListener.java b/api/src/main/java/brooklyn/entity/rebind/ChangeListener.java
index ffc15da..ee17ec8 100644
--- a/api/src/main/java/brooklyn/entity/rebind/ChangeListener.java
+++ b/api/src/main/java/brooklyn/entity/rebind/ChangeListener.java
@@ -2,6 +2,7 @@ package brooklyn.entity.rebind;
 
 import brooklyn.entity.Entity;
 import brooklyn.location.Location;
+import brooklyn.policy.Enricher;
 import brooklyn.policy.Policy;
 
 /**
@@ -22,6 +23,7 @@ public interface ChangeListener {
         @Override public void onUnmanaged(Location location) {}
         @Override public void onChanged(Location location) {}
         @Override public void onChanged(Policy policy) {}
+        @Override public void onChanged(Enricher enricher) {}
     };
     
     void onManaged(Entity entity);
@@ -37,4 +39,6 @@ public interface ChangeListener {
     void onChanged(Location location);
     
     void onChanged(Policy policy);
+    
+    void onChanged(Enricher enricher);
 }

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/80532a5b/api/src/main/java/brooklyn/entity/rebind/RebindContext.java
----------------------------------------------------------------------
diff --git a/api/src/main/java/brooklyn/entity/rebind/RebindContext.java b/api/src/main/java/brooklyn/entity/rebind/RebindContext.java
index 264b8b0..2d8e364 100644
--- a/api/src/main/java/brooklyn/entity/rebind/RebindContext.java
+++ b/api/src/main/java/brooklyn/entity/rebind/RebindContext.java
@@ -2,6 +2,7 @@ package brooklyn.entity.rebind;
 
 import brooklyn.entity.Entity;
 import brooklyn.location.Location;
+import brooklyn.policy.Enricher;
 import brooklyn.policy.Policy;
 
 /**
@@ -15,11 +16,14 @@ import brooklyn.policy.Policy;
  */
 public interface RebindContext {
 
-    public Entity getEntity(String id);
+    Entity getEntity(String id);
 
-    public Location getLocation(String id);
+    Location getLocation(String id);
 
-    public Policy getPolicy(String id);
+    Policy getPolicy(String id);
+
+    Enricher getEnricher(String id);
+
+    Class<?> loadClass(String typeName) throws ClassNotFoundException;
 
-    public Class<?> loadClass(String typeName) throws ClassNotFoundException;
 }

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/80532a5b/api/src/main/java/brooklyn/mementos/BrooklynMementoPersister.java
----------------------------------------------------------------------
diff --git a/api/src/main/java/brooklyn/mementos/BrooklynMementoPersister.java b/api/src/main/java/brooklyn/mementos/BrooklynMementoPersister.java
index e29e70e..18f9b14 100644
--- a/api/src/main/java/brooklyn/mementos/BrooklynMementoPersister.java
+++ b/api/src/main/java/brooklyn/mementos/BrooklynMementoPersister.java
@@ -8,6 +8,8 @@ import java.util.concurrent.TimeoutException;
 import brooklyn.entity.Entity;
 import brooklyn.entity.rebind.RebindManager;
 import brooklyn.location.Location;
+import brooklyn.policy.Enricher;
+import brooklyn.policy.Policy;
 import brooklyn.util.time.Duration;
 
 import com.google.common.annotations.VisibleForTesting;
@@ -21,6 +23,8 @@ public interface BrooklynMementoPersister {
     public static interface LookupContext {
         Entity lookupEntity(Class<?> type, String id);
         Location lookupLocation(Class<?> type, String id);
+        Policy lookupPolicy(Class<?> type, String id);
+        Enricher lookupEnricher(Class<?> type, String id);
     }
 
     BrooklynMementoManifest loadMementoManifest() throws IOException;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/80532a5b/api/src/main/java/brooklyn/policy/Enricher.java
----------------------------------------------------------------------
diff --git a/api/src/main/java/brooklyn/policy/Enricher.java b/api/src/main/java/brooklyn/policy/Enricher.java
index ab6b546..6be006d 100644
--- a/api/src/main/java/brooklyn/policy/Enricher.java
+++ b/api/src/main/java/brooklyn/policy/Enricher.java
@@ -3,16 +3,19 @@ package brooklyn.policy;
 import java.util.Map;
 
 import brooklyn.config.ConfigKey;
+import brooklyn.entity.rebind.RebindSupport;
+import brooklyn.entity.rebind.Rebindable;
+import brooklyn.mementos.EnricherMemento;
 
 import com.google.common.annotations.Beta;
 
 /**
  * Publishes metrics for an entity, e.g. aggregating information from other sensors/entities.
- * 
- * Has some similarities to {@link Policy}. However, enrichers specifically do not invoke 
+ *
+ * Has some similarities to {@link Policy}. However, enrichers specifically do not invoke
  * effectors and should only function to publish new metrics.
  */
-public interface Enricher extends EntityAdjunct {
+public interface Enricher extends EntityAdjunct, Rebindable {
     /**
      * A unique id for this enricher.
      */
@@ -32,8 +35,12 @@ public interface Enricher extends EntityAdjunct {
     EnricherType getEnricherType();
 
     <T> T getConfig(ConfigKey<T> key);
-    
+
     <T> T setConfig(ConfigKey<T> key, T val);
-    
+
     Map<ConfigKey<?>, Object> getAllConfig();
+
+    @Override
+    RebindSupport<EnricherMemento> getRebindSupport();
+
 }

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/80532a5b/core/src/main/java/brooklyn/enricher/basic/AbstractEnricher.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/brooklyn/enricher/basic/AbstractEnricher.java b/core/src/main/java/brooklyn/enricher/basic/AbstractEnricher.java
index a83b1fc..4346be5 100644
--- a/core/src/main/java/brooklyn/enricher/basic/AbstractEnricher.java
+++ b/core/src/main/java/brooklyn/enricher/basic/AbstractEnricher.java
@@ -2,6 +2,9 @@ package brooklyn.enricher.basic;
 
 import java.util.Map;
 
+import brooklyn.entity.rebind.BasicEnricherRebindSupport;
+import brooklyn.entity.rebind.RebindSupport;
+import brooklyn.mementos.EnricherMemento;
 import brooklyn.policy.Enricher;
 import brooklyn.policy.EnricherType;
 import brooklyn.policy.basic.AbstractEntityAdjunct;
@@ -28,6 +31,11 @@ public abstract class AbstractEnricher extends AbstractEntityAdjunct implements
             init();
         }
     }
+
+    @Override
+    public RebindSupport<EnricherMemento> getRebindSupport() {
+        return new BasicEnricherRebindSupport(this);
+    }
     
     @Override
     public EnricherType getEnricherType() {

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/80532a5b/core/src/main/java/brooklyn/entity/rebind/BasicEnricherRebindSupport.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/brooklyn/entity/rebind/BasicEnricherRebindSupport.java b/core/src/main/java/brooklyn/entity/rebind/BasicEnricherRebindSupport.java
index 9d3a50e..3fca1b8 100644
--- a/core/src/main/java/brooklyn/entity/rebind/BasicEnricherRebindSupport.java
+++ b/core/src/main/java/brooklyn/entity/rebind/BasicEnricherRebindSupport.java
@@ -7,36 +7,36 @@ import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
 import brooklyn.entity.rebind.dto.MementosGenerators;
-import brooklyn.mementos.PolicyMemento;
-import brooklyn.policy.basic.AbstractPolicy;
+import brooklyn.mementos.EnricherMemento;
+import brooklyn.enricher.basic.AbstractEnricher;
 
-public class BasicEnricherRebindSupport implements RebindSupport<PolicyMemento> {
+public class BasicEnricherRebindSupport implements RebindSupport<EnricherMemento> {
 
     private static final Logger LOG = LoggerFactory.getLogger(BasicEnricherRebindSupport.class);
     
-    private final AbstractPolicy policy;
+    private final AbstractEnricher enricher;
     
-    public BasicEnricherRebindSupport(AbstractPolicy policy) {
-        this.policy = policy;
+    public BasicEnricherRebindSupport(AbstractEnricher enricher) {
+        this.enricher = enricher;
     }
     
     @Override
-    public PolicyMemento getMemento() {
+    public EnricherMemento getMemento() {
         return getMementoWithProperties(Collections.<String,Object>emptyMap());
     }
 
-    protected PolicyMemento getMementoWithProperties(Map<String,?> props) {
-        PolicyMemento memento = MementosGenerators.newPolicyMementoBuilder(policy).customFields(props).build();
-        if (LOG.isTraceEnabled()) LOG.trace("Creating memento for policy: {}", memento.toVerboseString());
+    protected EnricherMemento getMementoWithProperties(Map<String,?> props) {
+        EnricherMemento memento = MementosGenerators.newEnricherMementoBuilder(enricher).customFields(props).build();
+        if (LOG.isTraceEnabled()) LOG.trace("Creating memento for enricher: {}", memento.toVerboseString());
         return memento;
     }
 
     @Override
-    public void reconstruct(RebindContext rebindContext, PolicyMemento memento) {
-        if (LOG.isTraceEnabled()) LOG.trace("Reconstructing policy: {}", memento.toVerboseString());
+    public void reconstruct(RebindContext rebindContext, EnricherMemento memento) {
+        if (LOG.isTraceEnabled()) LOG.trace("Reconstructing enricher: {}", memento.toVerboseString());
 
         // Note that the flags have been set in the constructor
-        policy.setName(memento.getDisplayName());
+        enricher.setName(memento.getDisplayName());
         
         doReconsruct(rebindContext, memento);
     }
@@ -44,7 +44,7 @@ public class BasicEnricherRebindSupport implements RebindSupport<PolicyMemento>
     /**
      * For overriding, to give custom reconsruct behaviour.
      */
-    protected void doReconsruct(RebindContext rebindContext, PolicyMemento memento) {
+    protected void doReconsruct(RebindContext rebindContext, EnricherMemento memento) {
         // default is no-op
     }
 }

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/80532a5b/core/src/main/java/brooklyn/entity/rebind/BasicEntityRebindSupport.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/brooklyn/entity/rebind/BasicEntityRebindSupport.java b/core/src/main/java/brooklyn/entity/rebind/BasicEntityRebindSupport.java
index 90df2f4..e19c2fa 100644
--- a/core/src/main/java/brooklyn/entity/rebind/BasicEntityRebindSupport.java
+++ b/core/src/main/java/brooklyn/entity/rebind/BasicEntityRebindSupport.java
@@ -9,6 +9,7 @@ import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
 import brooklyn.config.ConfigKey;
+import brooklyn.enricher.basic.AbstractEnricher;
 import brooklyn.entity.Effector;
 import brooklyn.entity.Entity;
 import brooklyn.entity.Group;
@@ -40,14 +41,14 @@ public class BasicEntityRebindSupport implements RebindSupport<EntityMemento> {
 
     protected EntityMemento getMementoWithProperties(Map<String,?> props) {
         EntityMemento memento = MementosGenerators.newEntityMementoBuilder(entity).customFields(props).build();
-    	if (LOG.isTraceEnabled()) LOG.trace("Creating memento for entity: {}", memento.toVerboseString());
-    	return memento;
+        if (LOG.isTraceEnabled()) LOG.trace("Creating memento for entity: {}", memento.toVerboseString());
+        return memento;
     }
 
     @SuppressWarnings("unchecked")
     @Override
     public void reconstruct(RebindContext rebindContext, EntityMemento memento) {
-    	if (LOG.isTraceEnabled()) LOG.trace("Reconstructing entity: {}", memento.toVerboseString());
+        if (LOG.isTraceEnabled()) LOG.trace("Reconstructing entity: {}", memento.toVerboseString());
 
         // Note that the id should have been set in the constructor; it is immutable
         entity.setDisplayName(memento.getDisplayName());
@@ -82,6 +83,7 @@ public class BasicEntityRebindSupport implements RebindSupport<EntityMemento> {
         setParent(rebindContext, memento);
         addChildren(rebindContext, memento);
         addPolicies(rebindContext, memento);
+        addEnrichers(rebindContext, memento);
         addMembers(rebindContext, memento);
         addLocations(rebindContext, memento);
 
@@ -158,4 +160,16 @@ public class BasicEntityRebindSupport implements RebindSupport<EntityMemento> {
             }
         }
     }
+    
+    protected void addEnrichers(RebindContext rebindContext, EntityMemento memento) {
+        for (String enricherId : memento.getEnrichers()) {
+            AbstractEnricher enricher = (AbstractEnricher) rebindContext.getEnricher(enricherId);
+            if (enricher != null) {
+                entity.addEnricher(enricher);
+            } else {
+                LOG.warn("Enricher not found; discarding policy {} of entity {}({})",
+                        new Object[] {enricherId, memento.getType(), memento.getId()});
+            }
+        }
+    }
 }

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/80532a5b/core/src/main/java/brooklyn/entity/rebind/ImmediateDeltaChangeListener.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/brooklyn/entity/rebind/ImmediateDeltaChangeListener.java b/core/src/main/java/brooklyn/entity/rebind/ImmediateDeltaChangeListener.java
index 077be32..a33bb12 100644
--- a/core/src/main/java/brooklyn/entity/rebind/ImmediateDeltaChangeListener.java
+++ b/core/src/main/java/brooklyn/entity/rebind/ImmediateDeltaChangeListener.java
@@ -9,6 +9,7 @@ import brooklyn.location.Location;
 import brooklyn.location.basic.LocationInternal;
 import brooklyn.mementos.BrooklynMementoPersister;
 import brooklyn.mementos.LocationMemento;
+import brooklyn.policy.Enricher;
 import brooklyn.policy.Policy;
 
 import com.google.common.collect.Maps;
@@ -126,4 +127,13 @@ public class ImmediateDeltaChangeListener implements ChangeListener {
             persister.delta(delta);
         }
     }
+    
+    @Override
+    public void onChanged(Enricher enricher) {
+        if (running && persister != null) {
+            PersisterDeltaImpl delta = new PersisterDeltaImpl();
+            delta.enrichers.add(enricher.getRebindSupport().getMemento());
+            persister.delta(delta);
+        }
+    }
 }

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/80532a5b/core/src/main/java/brooklyn/entity/rebind/PeriodicDeltaChangeListener.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/brooklyn/entity/rebind/PeriodicDeltaChangeListener.java b/core/src/main/java/brooklyn/entity/rebind/PeriodicDeltaChangeListener.java
index 1a7a8fc..d7cc8e6 100644
--- a/core/src/main/java/brooklyn/entity/rebind/PeriodicDeltaChangeListener.java
+++ b/core/src/main/java/brooklyn/entity/rebind/PeriodicDeltaChangeListener.java
@@ -16,6 +16,7 @@ import brooklyn.location.basic.LocationInternal;
 import brooklyn.management.ExecutionManager;
 import brooklyn.management.Task;
 import brooklyn.mementos.BrooklynMementoPersister;
+import brooklyn.policy.Enricher;
 import brooklyn.policy.Policy;
 import brooklyn.util.exceptions.Exceptions;
 import brooklyn.util.task.BasicTask;
@@ -47,13 +48,15 @@ public class PeriodicDeltaChangeListener implements ChangeListener {
         Set<Location> locations = Sets.newLinkedHashSet();
         Set<Entity> entities = Sets.newLinkedHashSet();
         Set<Policy> policies = Sets.newLinkedHashSet();
+        Set<Enricher> enrichers = Sets.newLinkedHashSet();
         Set<String> removedLocationIds = Sets.newLinkedHashSet();
         Set<String> removedEntityIds = Sets.newLinkedHashSet();
         Set<String> removedPolicyIds = Sets.newLinkedHashSet();
+        Set<String> removedEnricherIds = Sets.newLinkedHashSet();
         
         public boolean isEmpty() {
-            return locations.isEmpty() && entities.isEmpty() && policies.isEmpty() && 
-                    removedEntityIds.isEmpty() && removedLocationIds.isEmpty() && removedPolicyIds.isEmpty();
+            return locations.isEmpty() && entities.isEmpty() && policies.isEmpty() && enrichers.isEmpty() &&
+                    removedEntityIds.isEmpty() && removedLocationIds.isEmpty() && removedPolicyIds.isEmpty() && removedEnricherIds.isEmpty();
         }
     }
     
@@ -196,12 +199,20 @@ public class PeriodicDeltaChangeListener implements ChangeListener {
                         try {
                             persisterDelta.policies.add(policy.getRebindSupport().getMemento());
                         } catch (Exception e) {
-                            handleGenerateMementoException(e, "location "+policy.getClass().getSimpleName()+"("+policy.getId()+")");
+                            handleGenerateMementoException(e, "policy "+policy.getClass().getSimpleName()+"("+policy.getId()+")");
+                        }
+                    }
+                    for (Enricher enricher : prevDeltaCollector.enrichers) {
+                        try {
+                            persisterDelta.enrichers.add(enricher.getRebindSupport().getMemento());
+                        } catch (Exception e) {
+                            handleGenerateMementoException(e, "enricher "+enricher.getClass().getSimpleName()+"("+enricher.getId()+")");
                         }
                     }
                     persisterDelta.removedLocationIds = prevDeltaCollector.removedLocationIds;
                     persisterDelta.removedEntityIds = prevDeltaCollector.removedEntityIds;
                     persisterDelta.removedPolicyIds = prevDeltaCollector.removedPolicyIds;
+                    persisterDelta.removedEnricherIds = prevDeltaCollector.removedEnricherIds;
                     
                     /*
                      * Need to guarantee "happens before", with any thread that subsequently reads
@@ -268,9 +279,13 @@ public class PeriodicDeltaChangeListener implements ChangeListener {
             // (e.g. AbstractController registering a AbstractMembershipTrackingPolicy)
             // Also, the entity constructor often re-creates the policy.
             // Also see MementosGenerator.newEntityMementoBuilder()
-//            for (Policy policy : entity.getPolicies()) {
-//                delta.policies.add(policy);
-//            }
+            for (Policy policy : entity.getPolicies()) {
+                deltaCollector.policies.add(policy);
+            }
+
+            for (Enricher enricher : entity.getEnrichers()) {
+                deltaCollector.enrichers.add(enricher);
+            }
         }
     }
     
@@ -307,4 +322,12 @@ public class PeriodicDeltaChangeListener implements ChangeListener {
             deltaCollector.policies.add(policy);
         }
     }
+    
+    @Override
+    public synchronized void onChanged(Enricher enricher) {
+        if (LOG.isTraceEnabled()) LOG.trace("onChanged: {}", enricher);
+        if (!isStopped()) {
+            deltaCollector.enrichers.add(enricher);
+        }
+    }
 }

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/80532a5b/core/src/main/java/brooklyn/entity/rebind/PersisterDeltaImpl.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/brooklyn/entity/rebind/PersisterDeltaImpl.java b/core/src/main/java/brooklyn/entity/rebind/PersisterDeltaImpl.java
index b3a3d7f..0950f81 100644
--- a/core/src/main/java/brooklyn/entity/rebind/PersisterDeltaImpl.java
+++ b/core/src/main/java/brooklyn/entity/rebind/PersisterDeltaImpl.java
@@ -3,6 +3,7 @@ package brooklyn.entity.rebind;
 import java.util.Collection;
 
 import brooklyn.mementos.BrooklynMementoPersister.Delta;
+import brooklyn.mementos.EnricherMemento;
 import brooklyn.mementos.EntityMemento;
 import brooklyn.mementos.LocationMemento;
 import brooklyn.mementos.PolicyMemento;
@@ -13,9 +14,11 @@ class PersisterDeltaImpl implements Delta {
     Collection<LocationMemento> locations = Sets.newLinkedHashSet();
     Collection<EntityMemento> entities = Sets.newLinkedHashSet();
     Collection<PolicyMemento> policies = Sets.newLinkedHashSet();
+    Collection<EnricherMemento> enrichers = Sets.newLinkedHashSet();
     Collection <String> removedLocationIds = Sets.newLinkedHashSet();
     Collection <String> removedEntityIds = Sets.newLinkedHashSet();
     Collection <String> removedPolicyIds = Sets.newLinkedHashSet();
+    Collection <String> removedEnricherIds = Sets.newLinkedHashSet();
     
     @Override
     public Collection<LocationMemento> locations() {
@@ -33,6 +36,11 @@ class PersisterDeltaImpl implements Delta {
     }
 
     @Override
+    public Collection<EnricherMemento> enrichers() {
+        return enrichers;
+    }
+
+    @Override
     public Collection<String> removedLocationIds() {
         return removedLocationIds;
     }
@@ -46,4 +54,9 @@ class PersisterDeltaImpl implements Delta {
     public Collection<String> removedPolicyIds() {
         return removedPolicyIds;
     }
+    
+    @Override
+    public Collection<String> removedEnricherIds() {
+        return removedEnricherIds;
+    }
 }

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/80532a5b/core/src/main/java/brooklyn/entity/rebind/RebindContextImpl.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/brooklyn/entity/rebind/RebindContextImpl.java b/core/src/main/java/brooklyn/entity/rebind/RebindContextImpl.java
index 90a3bb4..30c88ab 100644
--- a/core/src/main/java/brooklyn/entity/rebind/RebindContextImpl.java
+++ b/core/src/main/java/brooklyn/entity/rebind/RebindContextImpl.java
@@ -4,6 +4,7 @@ import java.util.Map;
 
 import brooklyn.entity.Entity;
 import brooklyn.location.Location;
+import brooklyn.policy.Enricher;
 import brooklyn.policy.Policy;
 
 import com.google.common.collect.Maps;
@@ -13,6 +14,7 @@ public class RebindContextImpl implements RebindContext {
     private final Map<String, Entity> entities = Maps.newLinkedHashMap();
     private final Map<String, Location> locations = Maps.newLinkedHashMap();
     private final Map<String, Policy> policies = Maps.newLinkedHashMap();
+    private final Map<String, Enricher> enrichers = Maps.newLinkedHashMap();
     private final ClassLoader classLoader;
     
     public RebindContextImpl(ClassLoader classLoader) {
@@ -31,6 +33,10 @@ public class RebindContextImpl implements RebindContext {
         policies.put(id, policy);
     }
     
+    public void registerEnricher(String id, Enricher enricher) {
+        enrichers.put(id, enricher);
+    }
+    
     @Override
     public Entity getEntity(String id) {
         return entities.get(id);
@@ -47,6 +53,11 @@ public class RebindContextImpl implements RebindContext {
     }
     
     @Override
+    public Enricher getEnricher(String id) {
+        return enrichers.get(id);
+    }
+    
+    @Override
     public Class<?> loadClass(String className) throws ClassNotFoundException {
         return classLoader.loadClass(className);
     }

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/80532a5b/core/src/main/java/brooklyn/entity/rebind/RebindManagerImpl.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/brooklyn/entity/rebind/RebindManagerImpl.java b/core/src/main/java/brooklyn/entity/rebind/RebindManagerImpl.java
index 821a42d..4b0ce65 100644
--- a/core/src/main/java/brooklyn/entity/rebind/RebindManagerImpl.java
+++ b/core/src/main/java/brooklyn/entity/rebind/RebindManagerImpl.java
@@ -28,10 +28,12 @@ import brooklyn.mementos.BrooklynMemento;
 import brooklyn.mementos.BrooklynMementoManifest;
 import brooklyn.mementos.BrooklynMementoPersister;
 import brooklyn.mementos.BrooklynMementoPersister.LookupContext;
+import brooklyn.mementos.EnricherMemento;
 import brooklyn.mementos.EntityMemento;
 import brooklyn.mementos.LocationMemento;
 import brooklyn.mementos.PolicyMemento;
 import brooklyn.mementos.TreeNode;
+import brooklyn.policy.Enricher;
 import brooklyn.policy.Policy;
 import brooklyn.util.collections.MutableMap;
 import brooklyn.util.exceptions.Exceptions;
@@ -155,6 +157,7 @@ public class RebindManagerImpl implements RebindManager {
             Map<String,Entity> entities = Maps.newLinkedHashMap();
             Map<String,Location> locations = Maps.newLinkedHashMap();
             Map<String,Policy> policies = Maps.newLinkedHashMap();
+            Map<String,Enricher> enrichers = Maps.newLinkedHashMap();
             
             final RebindContextImpl rebindContext = new RebindContextImpl(classLoader);
     
@@ -186,6 +189,32 @@ public class RebindManagerImpl implements RebindManager {
                     }
                     return result;
                 }
+                @Override public Policy lookupPolicy(Class<?> type, String id) {
+                    Policy result = rebindContext.getPolicy(id);
+                    if (result == null) {
+                        if (removeDanglingRefs) {
+                            LOG.warn("No policy found with id "+id+"; returning null");
+                        } else {
+                            throw new IllegalStateException("No policy found with id "+id);
+                        }
+                    } else if (type != null && !type.isInstance(result)) {
+                        LOG.warn("Policy with id "+id+" does not match type "+type+"; returning "+result);
+                    }
+                    return result;
+                }
+                @Override public Enricher lookupEnricher(Class<?> type, String id) {
+                    Enricher result = rebindContext.getEnricher(id);
+                    if (result == null) {
+                        if (removeDanglingRefs) {
+                            LOG.warn("No enricher found with id "+id+"; returning null");
+                        } else {
+                            throw new IllegalStateException("No enricher found with id "+id);
+                        }
+                    } else if (type != null && !type.isInstance(result)) {
+                        LOG.warn("Enricher with id "+id+" does not match type "+type+"; returning "+result);
+                    }
+                    return result;
+                }
             };
             
             // Two-phase deserialization.
@@ -234,6 +263,16 @@ public class RebindManagerImpl implements RebindManager {
                 rebindContext.registerPolicy(policyMemento.getId(), policy);
             }
             
+            // Instantiate enrichers
+            LOG.info("RebindManager instantiating enrichers: {}", memento.getEnricherIds());
+            for (EnricherMemento enricherMemento : memento.getEnricherMementos().values()) {
+                if (LOG.isDebugEnabled()) LOG.debug("RebindManager instantiating policy {}", enricherMemento);
+                
+                Enricher enricher = newEnricher(enricherMemento, reflections);
+                enrichers.put(enricherMemento.getId(), enricher);
+                rebindContext.registerEnricher(enricherMemento.getId(), enricher);
+            }
+            
             // Reconstruct locations
             LOG.info("RebindManager reconstructing locations");
             for (LocationMemento locMemento : sortParentFirst(memento.getLocationMementos()).values()) {
@@ -242,7 +281,7 @@ public class RebindManagerImpl implements RebindManager {
     
                 ((LocationInternal)location).getRebindSupport().reconstruct(rebindContext, locMemento);
             }
-    
+
             // Reconstruct policies
             LOG.info("RebindManager reconstructing policies");
             for (PolicyMemento policyMemento : memento.getPolicyMementos().values()) {
@@ -251,6 +290,15 @@ public class RebindManagerImpl implements RebindManager {
     
                 policy.getRebindSupport().reconstruct(rebindContext, policyMemento);
             }
+
+            // Reconstruct enrichers
+            LOG.info("RebindManager reconstructing enrichers");
+            for (EnricherMemento enricherMemento : memento.getEnricherMementos().values()) {
+                Enricher enricher = rebindContext.getEnricher(enricherMemento.getId());
+                if (LOG.isDebugEnabled()) LOG.debug("RebindManager reconstructing enricher {}", enricherMemento);
+    
+                enricher.getRebindSupport().reconstruct(rebindContext, enricherMemento);
+            }
     
             // Reconstruct entities
             LOG.info("RebindManager reconstructing entities");
@@ -423,7 +471,6 @@ public class RebindManagerImpl implements RebindManager {
         // note 'used' config keys get marked in BasicLocationRebindSupport
     }
 
-
     /**
      * Constructs a new policy, passing to its constructor the policy id and all of memento.getFlags().
      */
@@ -440,6 +487,22 @@ public class RebindManagerImpl implements RebindManager {
         return (Policy) invokeConstructor(reflections, policyClazz, new Object[] {flags});
     }
 
+    /**
+     * Constructs a new enricher, passing to its constructor the enricher id and all of memento.getFlags().
+     */
+    private Enricher newEnricher(EnricherMemento memento, Reflections reflections) {
+        String id = memento.getId();
+        String enricherType = checkNotNull(memento.getType(), "enricherType of "+id);
+        Class<?> enricherClazz = reflections.loadClass(enricherType);
+
+        Map<String, Object> flags = MutableMap.<String, Object>builder()
+                .put("id", id)
+                .putAll(memento.getFlags())
+                .build();
+
+        return (Enricher) invokeConstructor(reflections, enricherClazz, new Object[] {flags});
+    }
+
     private <T> T invokeConstructor(Reflections reflections, Class<T> clazz, Object[]... possibleArgs) {
         for (Object[] args : possibleArgs) {
             try {
@@ -533,5 +596,14 @@ public class RebindManagerImpl implements RebindManager {
                 LOG.error("Error persisting mememento onChanged("+policy+"); continuing.", t);
             }
         }
+        
+        @Override
+        public void onChanged(Enricher enricher) {
+            try {
+                delegate.onChanged(enricher);
+            } catch (Throwable t) {
+                LOG.error("Error persisting mememento onChanged("+enricher+"); continuing.", t);
+            }
+        }
     }
 }

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/80532a5b/core/src/main/java/brooklyn/entity/rebind/dto/BrooklynMementoImpl.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/brooklyn/entity/rebind/dto/BrooklynMementoImpl.java b/core/src/main/java/brooklyn/entity/rebind/dto/BrooklynMementoImpl.java
index 7704659..b75a112 100644
--- a/core/src/main/java/brooklyn/entity/rebind/dto/BrooklynMementoImpl.java
+++ b/core/src/main/java/brooklyn/entity/rebind/dto/BrooklynMementoImpl.java
@@ -8,6 +8,7 @@ import java.util.Map;
 
 import brooklyn.BrooklynVersion;
 import brooklyn.mementos.BrooklynMemento;
+import brooklyn.mementos.EnricherMemento;
 import brooklyn.mementos.EntityMemento;
 import brooklyn.mementos.LocationMemento;
 import brooklyn.mementos.PolicyMemento;
@@ -31,6 +32,7 @@ public class BrooklynMementoImpl implements BrooklynMemento, Serializable {
         protected final Map<String, EntityMemento> entities = Maps.newLinkedHashMap();
         protected final Map<String, LocationMemento> locations = Maps.newLinkedHashMap();
         protected final Map<String, PolicyMemento> policies = Maps.newLinkedHashMap();
+        protected final Map<String, EnricherMemento> enrichers = Maps.newLinkedHashMap();
         
         public Builder brooklynVersion(String val) {
             brooklynVersion = val; return this;
@@ -53,6 +55,9 @@ public class BrooklynMementoImpl implements BrooklynMemento, Serializable {
         public Builder policy(PolicyMemento val) {
             policies.put(val.getId(), val); return this;
         }
+        public Builder enricher(EnricherMemento val) {
+            enrichers.put(val.getId(), val); return this;
+        }
         public Builder entity(EntityMemento val) {
             entities.put(val.getId(), val); return this;
         }
@@ -62,6 +67,9 @@ public class BrooklynMementoImpl implements BrooklynMemento, Serializable {
         public Builder policies(Map<String, PolicyMemento> vals) {
             policies.putAll(vals); return this;
         }
+        public Builder enricheres(Map<String, EnricherMemento> vals) {
+            enrichers.putAll(vals); return this;
+        }
         public BrooklynMemento build() {
             return new BrooklynMementoImpl(this);
         }
@@ -74,6 +82,7 @@ public class BrooklynMementoImpl implements BrooklynMemento, Serializable {
     private Map<String, EntityMemento> entities;
     private Map<String, LocationMemento> locations;
     private Map<String, PolicyMemento> policies;
+    private Map<String, EnricherMemento> enrichers;
     
     private BrooklynMementoImpl(Builder builder) {
         brooklynVersion = builder.brooklynVersion;
@@ -82,6 +91,7 @@ public class BrooklynMementoImpl implements BrooklynMemento, Serializable {
         entities = builder.entities;
         locations = builder.locations;
         policies = builder.policies;
+        enrichers = builder.enrichers;
     }
 
     @Override
@@ -98,6 +108,11 @@ public class BrooklynMementoImpl implements BrooklynMemento, Serializable {
     public PolicyMemento getPolicyMemento(String id) {
         return policies.get(id);
     }
+    
+    @Override
+    public EnricherMemento getEnricherMemento(String id) {
+        return enrichers.get(id);
+    }
 
     @Override
     public Collection<String> getApplicationIds() {
@@ -120,6 +135,11 @@ public class BrooklynMementoImpl implements BrooklynMemento, Serializable {
     }
     
     @Override
+    public Collection<String> getEnricherIds() {
+        return Collections.unmodifiableSet(enrichers.keySet());
+    }
+    
+    @Override
     public Collection<String> getTopLevelLocationIds() {
         return Collections.unmodifiableList(topLevelLocationIds);
     }
@@ -137,4 +157,9 @@ public class BrooklynMementoImpl implements BrooklynMemento, Serializable {
     public Map<String, PolicyMemento> getPolicyMementos() {
         return Collections.unmodifiableMap(policies);
     }
+
+    @Override
+    public Map<String, EnricherMemento> getEnricherMementos() {
+        return Collections.unmodifiableMap(enrichers);
+    }
 }

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/80532a5b/core/src/main/java/brooklyn/entity/rebind/dto/BrooklynMementoManifestImpl.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/brooklyn/entity/rebind/dto/BrooklynMementoManifestImpl.java b/core/src/main/java/brooklyn/entity/rebind/dto/BrooklynMementoManifestImpl.java
index fdfc1e0..e517f15 100644
--- a/core/src/main/java/brooklyn/entity/rebind/dto/BrooklynMementoManifestImpl.java
+++ b/core/src/main/java/brooklyn/entity/rebind/dto/BrooklynMementoManifestImpl.java
@@ -21,6 +21,7 @@ public class BrooklynMementoManifestImpl implements BrooklynMementoManifest, Ser
         protected final Map<String, String> entityIdToType = Maps.newLinkedHashMap();
         protected final Map<String, String> locationIdToType = Maps.newLinkedHashMap();
         protected final Map<String, String> policyIdToType = Maps.newLinkedHashMap();
+        protected final Map<String, String> enricherIdToType = Maps.newLinkedHashMap();
         
         public Builder brooklynVersion(String val) {
             brooklynVersion = val; return this;
@@ -43,6 +44,12 @@ public class BrooklynMementoManifestImpl implements BrooklynMementoManifest, Ser
         public Builder policies(Map<String, String> vals) {
             policyIdToType.putAll(vals); return this;
         }
+        public Builder enricher(String id, String type) {
+            enricherIdToType.put(id, type); return this;
+        }
+        public Builder enrichers(Map<String, String> vals) {
+            enricherIdToType.putAll(vals); return this;
+        }
         public BrooklynMementoManifest build() {
             return new BrooklynMementoManifestImpl(this);
         }
@@ -51,11 +58,13 @@ public class BrooklynMementoManifestImpl implements BrooklynMementoManifest, Ser
     private Map<String, String> entityIdToType;
     private Map<String, String> locationIdToType;
     private Map<String, String> policyIdToType;
+    private Map<String, String> enricherIdToType;
     
     private BrooklynMementoManifestImpl(Builder builder) {
         entityIdToType = builder.entityIdToType;
         locationIdToType = builder.locationIdToType;
         policyIdToType = builder.policyIdToType;
+        enricherIdToType = builder.enricherIdToType;
     }
 
     @Override
@@ -72,4 +81,9 @@ public class BrooklynMementoManifestImpl implements BrooklynMementoManifest, Ser
     public Map<String, String> getPolicyIdToType() {
         return Collections.unmodifiableMap(policyIdToType);
     }
+
+    @Override
+    public Map<String, String> getEnricherIdToType() {
+        return Collections.unmodifiableMap(enricherIdToType);
+    }
 }

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/80532a5b/core/src/main/java/brooklyn/entity/rebind/persister/AbstractBrooklynMementoPersister.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/brooklyn/entity/rebind/persister/AbstractBrooklynMementoPersister.java b/core/src/main/java/brooklyn/entity/rebind/persister/AbstractBrooklynMementoPersister.java
index 00ad013..1ba1cd1 100644
--- a/core/src/main/java/brooklyn/entity/rebind/persister/AbstractBrooklynMementoPersister.java
+++ b/core/src/main/java/brooklyn/entity/rebind/persister/AbstractBrooklynMementoPersister.java
@@ -6,6 +6,7 @@ import brooklyn.entity.rebind.dto.MutableBrooklynMemento;
 import brooklyn.mementos.BrooklynMemento;
 import brooklyn.mementos.BrooklynMementoManifest;
 import brooklyn.mementos.BrooklynMementoPersister;
+import brooklyn.mementos.EnricherMemento;
 import brooklyn.mementos.EntityMemento;
 import brooklyn.mementos.LocationMemento;
 import brooklyn.mementos.PolicyMemento;
@@ -36,6 +37,9 @@ public abstract class AbstractBrooklynMementoPersister implements BrooklynMement
         for (PolicyMemento entity : memento.getPolicyMementos().values()) {
             builder.policy(entity.getId(), entity.getType());
         }
+        for (EnricherMemento entity : memento.getEnricherMementos().values()) {
+            builder.enricher(entity.getId(), entity.getType());
+        }
         return builder.build();
     }
     
@@ -54,8 +58,10 @@ public abstract class AbstractBrooklynMementoPersister implements BrooklynMement
         memento.removeEntities(delta.removedEntityIds());
         memento.removeLocations(delta.removedLocationIds());
         memento.removePolicies(delta.removedPolicyIds());
+        memento.removeEnrichers(delta.removedEnricherIds());
         memento.updateEntityMementos(delta.entities());
         memento.updateLocationMementos(delta.locations());
         memento.updatePolicyMementos(delta.policies());
+        memento.updateEnricherMementos(delta.enrichers());
     }
 }

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/80532a5b/core/src/main/java/brooklyn/entity/rebind/persister/BrooklynMementoPersisterInMemory.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/brooklyn/entity/rebind/persister/BrooklynMementoPersisterInMemory.java b/core/src/main/java/brooklyn/entity/rebind/persister/BrooklynMementoPersisterInMemory.java
index 19b88d6..fe55213 100644
--- a/core/src/main/java/brooklyn/entity/rebind/persister/BrooklynMementoPersisterInMemory.java
+++ b/core/src/main/java/brooklyn/entity/rebind/persister/BrooklynMementoPersisterInMemory.java
@@ -16,6 +16,8 @@ import brooklyn.entity.proxying.EntityProxy;
 import brooklyn.location.Location;
 import brooklyn.location.basic.LocationInternal;
 import brooklyn.mementos.BrooklynMemento;
+import brooklyn.policy.Enricher;
+import brooklyn.policy.Policy;
 import brooklyn.util.collections.MutableList;
 import brooklyn.util.os.Os;
 import brooklyn.util.time.Duration;
@@ -85,6 +87,16 @@ public class BrooklynMementoPersisterInMemory extends AbstractBrooklynMementoPer
                         if (type != null) types.add(type);
                         return (Location) newDummy(types);
                     }
+                    @Override public Policy lookupPolicy(Class<?> type, String id) {
+                        List<Class<?>> types = MutableList.<Class<?>>of(Policy.class);
+                        if (type != null) types.add(type);
+                        return (Policy) newDummy(types);
+                    }
+                    @Override public Enricher lookupEnricher(Class<?> type, String id) {
+                        List<Class<?>> types = MutableList.<Class<?>>of(Enricher.class);
+                        if (type != null) types.add(type);
+                        return (Enricher) newDummy(types);
+                    }
                     private Object newDummy(List<Class<?>> types) {
                         return java.lang.reflect.Proxy.newProxyInstance(
                             classLoader,

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/80532a5b/core/src/main/java/brooklyn/entity/rebind/persister/BrooklynMementoPersisterToMultiFile.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/brooklyn/entity/rebind/persister/BrooklynMementoPersisterToMultiFile.java b/core/src/main/java/brooklyn/entity/rebind/persister/BrooklynMementoPersisterToMultiFile.java
index a39bbfd..2b5f012 100644
--- a/core/src/main/java/brooklyn/entity/rebind/persister/BrooklynMementoPersisterToMultiFile.java
+++ b/core/src/main/java/brooklyn/entity/rebind/persister/BrooklynMementoPersisterToMultiFile.java
@@ -19,6 +19,7 @@ import brooklyn.entity.rebind.dto.BrooklynMementoManifestImpl;
 import brooklyn.mementos.BrooklynMemento;
 import brooklyn.mementos.BrooklynMementoManifest;
 import brooklyn.mementos.BrooklynMementoPersister;
+import brooklyn.mementos.EnricherMemento;
 import brooklyn.mementos.EntityMemento;
 import brooklyn.mementos.LocationMemento;
 import brooklyn.mementos.PolicyMemento;
@@ -44,10 +45,12 @@ public class BrooklynMementoPersisterToMultiFile implements BrooklynMementoPersi
     private final File entitiesDir;
     private final File locationsDir;
     private final File policiesDir;
+    private final File enrichersDir;
 
     private final ConcurrentMap<String, MementoFileWriter<EntityMemento>> entityWriters = new ConcurrentHashMap<String, MementoFileWriter<EntityMemento>>();
     private final ConcurrentMap<String, MementoFileWriter<LocationMemento>> locationWriters = new ConcurrentHashMap<String, MementoFileWriter<LocationMemento>>();
     private final ConcurrentMap<String, MementoFileWriter<PolicyMemento>> policyWriters = new ConcurrentHashMap<String, MementoFileWriter<PolicyMemento>>();
+    private final ConcurrentMap<String, MementoFileWriter<EnricherMemento>> enricherWriters = new ConcurrentHashMap<String, MementoFileWriter<EnricherMemento>>();
     
     private final MementoSerializer<Object> serializer;
 
@@ -77,6 +80,10 @@ public class BrooklynMementoPersisterToMultiFile implements BrooklynMementoPersi
         policiesDir = new File(dir, "policies");
         policiesDir.mkdir();
         checkDirIsAccessible(policiesDir);
+        
+        enrichersDir = new File(dir, "enrichers");
+        enrichersDir.mkdir();
+        checkDirIsAccessible(enrichersDir);
 
         File planeDir = new File(dir, "plane");
         planeDir.mkdir();
@@ -114,9 +121,10 @@ public class BrooklynMementoPersisterToMultiFile implements BrooklynMementoPersi
         File[] entityFiles = entitiesDir.listFiles(fileFilter);
         File[] locationFiles = locationsDir.listFiles(fileFilter);
         File[] policyFiles = policiesDir.listFiles(fileFilter);
+        File[] enricherFiles = enrichersDir.listFiles(fileFilter);
 
-        LOG.info("Loading memento manifest from {}; {} entities, {} locations, {} policies", 
-                new Object[] {dir, entityFiles.length, locationFiles.length, policyFiles.length});
+        LOG.info("Loading memento manifest from {}; {} entities, {} locations, {} policies, {} policies", 
+                new Object[] {dir, entityFiles.length, locationFiles.length, policyFiles.length, enricherFiles.length});
         
         BrooklynMementoManifestImpl.Builder builder = BrooklynMementoManifestImpl.builder();
         
@@ -139,6 +147,12 @@ public class BrooklynMementoPersisterToMultiFile implements BrooklynMementoPersi
                 String type = (String) XmlUtil.xpath(contents, "/policy/type");
                 builder.policy(id, type);
             }
+            for (File file : enricherFiles) {
+                String contents = readFile(file);
+                String id = (String) XmlUtil.xpath(contents, "/enricher/id");
+                String type = (String) XmlUtil.xpath(contents, "/enricher/type");
+                builder.enricher(id, type);
+            }
             
             if (LOG.isDebugEnabled()) LOG.debug("Loaded memento manifest; took {}", Time.makeTimeStringRounded(stopwatch.elapsed(TimeUnit.MILLISECONDS))); 
             return builder.build();
@@ -164,9 +178,10 @@ public class BrooklynMementoPersisterToMultiFile implements BrooklynMementoPersi
         File[] entityFiles = entitiesDir.listFiles(fileFilter);
         File[] locationFiles = locationsDir.listFiles(fileFilter);
         File[] policyFiles = policiesDir.listFiles(fileFilter);
+        File[] enricherFiles = enrichersDir.listFiles(fileFilter);
 
-        LOG.info("Loading memento from {}; {} entities, {} locations, {} policies", 
-                new Object[] {dir, entityFiles.length, locationFiles.length, policyFiles.length});
+        LOG.info("Loading memento from {}; {} entities, {} locations, {} policies and {} enrichers", 
+                new Object[] {dir, entityFiles.length, locationFiles.length, policyFiles.length}, enricherFiles.length);
         
         BrooklynMementoImpl.Builder builder = BrooklynMementoImpl.builder();
         
@@ -199,6 +214,14 @@ public class BrooklynMementoPersisterToMultiFile implements BrooklynMementoPersi
                     builder.policy(memento);
                 }
             }
+            for (File file : enricherFiles) {
+                EnricherMemento memento = (EnricherMemento) serializer.fromString(readFile(file));
+                if (memento == null) {
+                    LOG.warn("No enricher-memento deserialized from file "+file+"; ignoring and continuing");
+                } else {
+                    builder.enricher(memento);
+                }
+            }
             
             if (LOG.isDebugEnabled()) LOG.debug("Loaded memento; took {}", Time.makeTimeStringRounded(stopwatch.elapsed(TimeUnit.MILLISECONDS))); 
             return builder.build();
@@ -225,6 +248,9 @@ public class BrooklynMementoPersisterToMultiFile implements BrooklynMementoPersi
         for (PolicyMemento m : newMemento.getPolicyMementos().values()) {
             persist(m);
         }
+        for (EnricherMemento m : newMemento.getEnricherMementos().values()) {
+            persist(m);
+        }
     }
     
     @Override
@@ -233,10 +259,10 @@ public class BrooklynMementoPersisterToMultiFile implements BrooklynMementoPersi
             if (LOG.isDebugEnabled()) LOG.debug("Ignoring checkpointed delta of memento, because not running");
             return;
         }
-        if (LOG.isTraceEnabled()) LOG.trace("Checkpointed delta of memento; updating {} entities, {} locations and {} policies; " +
-        		"removing {} entities, {} locations and {} policies", 
-                new Object[] {delta.entities(), delta.locations(), delta.policies(),
-                delta.removedEntityIds(), delta.removedLocationIds(), delta.removedPolicyIds()});
+        if (LOG.isTraceEnabled()) LOG.trace("Checkpointed delta of memento; updating {} entities, {} locations, {} policies and {} enrichers; " +
+        		"removing {} entities, {} locations {} policies and {} enrichers", 
+                new Object[] {delta.entities(), delta.locations(), delta.policies(), delta.enrichers(),
+                delta.removedEntityIds(), delta.removedLocationIds(), delta.removedPolicyIds(), delta.removedEnricherIds()});
         
         for (EntityMemento entity : delta.entities()) {
             persist(entity);
@@ -247,6 +273,9 @@ public class BrooklynMementoPersisterToMultiFile implements BrooklynMementoPersi
         for (PolicyMemento policy : delta.policies()) {
             persist(policy);
         }
+        for (EnricherMemento enricher : delta.enrichers()) {
+            persist(enricher);
+        }
         for (String id : delta.removedEntityIds()) {
             deleteEntity(id);
         }
@@ -256,6 +285,9 @@ public class BrooklynMementoPersisterToMultiFile implements BrooklynMementoPersi
         for (String id : delta.removedPolicyIds()) {
             deletePolicy(id);
         }
+        for (String id : delta.removedEnricherIds()) {
+            deleteEnricher(id);
+        }
     }
 
     @VisibleForTesting
@@ -279,6 +311,9 @@ public class BrooklynMementoPersisterToMultiFile implements BrooklynMementoPersi
         for (MementoFileWriter<?> writer : policyWriters.values()) {
             writer.waitForWriteCompleted(timeout);
         }
+        for (MementoFileWriter<?> writer : enricherWriters.values()) {
+            writer.waitForWriteCompleted(timeout);
+        }
     }
 
     // TODO Promote somewhere sensible; share code with BrooklynLauncher.checkPersistenceDirAccessible
@@ -322,6 +357,15 @@ public class BrooklynMementoPersisterToMultiFile implements BrooklynMementoPersi
         }
         writer.write(policy);
     }
+    
+    private void persist(EnricherMemento enricher) {
+        MementoFileWriter<EnricherMemento> writer = enricherWriters.get(enricher.getId());
+        if (writer == null) {
+            enricherWriters.putIfAbsent(enricher.getId(), new MementoFileWriter<EnricherMemento>(getFileFor(enricher), executor, serializer));
+            writer = enricherWriters.get(enricher.getId());
+        }
+        writer.write(enricher);
+    }
 
     private void deleteEntity(String id) {
         MementoFileWriter<EntityMemento> writer = entityWriters.get(id);
@@ -343,6 +387,13 @@ public class BrooklynMementoPersisterToMultiFile implements BrooklynMementoPersi
             writer.delete();
         }
     }
+    
+    private void deleteEnricher(String id) {
+        MementoFileWriter<EnricherMemento> writer = enricherWriters.get(id);
+        if (writer != null) {
+            writer.delete();
+        }
+    }
 
     private File getFileFor(EntityMemento entity) {
         return new File(entitiesDir, entity.getId());
@@ -355,4 +406,8 @@ public class BrooklynMementoPersisterToMultiFile implements BrooklynMementoPersi
     private File getFileFor(PolicyMemento policy) {
         return new File(policiesDir, policy.getId());
     }
+    
+    private File getFileFor(EnricherMemento enricher) {
+        return new File(enrichersDir, enricher.getId());
+    }
 }

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/80532a5b/core/src/main/java/brooklyn/entity/rebind/persister/XmlMementoSerializer.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/brooklyn/entity/rebind/persister/XmlMementoSerializer.java b/core/src/main/java/brooklyn/entity/rebind/persister/XmlMementoSerializer.java
index 8b44234..02da444 100644
--- a/core/src/main/java/brooklyn/entity/rebind/persister/XmlMementoSerializer.java
+++ b/core/src/main/java/brooklyn/entity/rebind/persister/XmlMementoSerializer.java
@@ -15,8 +15,10 @@ import brooklyn.entity.basic.BasicParameterType;
 import brooklyn.entity.effector.EffectorAndBody;
 import brooklyn.entity.effector.EffectorTasks.EffectorBodyTaskFactory;
 import brooklyn.entity.effector.EffectorTasks.EffectorTaskFactory;
+import brooklyn.entity.rebind.dto.BasicEnricherMemento;
 import brooklyn.entity.rebind.dto.BasicEntityMemento;
 import brooklyn.entity.rebind.dto.BasicLocationMemento;
+import brooklyn.entity.rebind.dto.BasicPolicyMemento;
 import brooklyn.entity.rebind.dto.MutableBrooklynMemento;
 import brooklyn.entity.trait.Identifiable;
 import brooklyn.event.basic.BasicAttributeSensor;
@@ -24,6 +26,8 @@ import brooklyn.event.basic.BasicConfigKey;
 import brooklyn.location.Location;
 import brooklyn.management.Task;
 import brooklyn.mementos.BrooklynMementoPersister.LookupContext;
+import brooklyn.policy.Enricher;
+import brooklyn.policy.Policy;
 import brooklyn.util.exceptions.Exceptions;
 import brooklyn.util.xstream.XmlSerializer;
 
@@ -57,6 +61,8 @@ public class XmlMementoSerializer<T> extends XmlSerializer<T> implements Memento
         
         xstream.alias("entity", BasicEntityMemento.class);
         xstream.alias("location", BasicLocationMemento.class);
+        xstream.alias("policy", BasicPolicyMemento.class);
+        xstream.alias("enricher", BasicEnricherMemento.class);
         xstream.alias("configKey", BasicConfigKey.class);
         xstream.alias("attributeSensor", BasicAttributeSensor.class);
         
@@ -67,11 +73,14 @@ public class XmlMementoSerializer<T> extends XmlSerializer<T> implements Memento
         
         xstream.alias("entityRef", Entity.class);
         xstream.alias("locationRef", Location.class);
+        xstream.alias("policyRef", Policy.class);
+        xstream.alias("enricherRef", Enricher.class);
 
         xstream.registerConverter(new LocationConverter());
+        xstream.registerConverter(new PolicyConverter());
+        xstream.registerConverter(new EnricherConverter());
         xstream.registerConverter(new EntityConverter());
         xstream.registerConverter(new TaskConverter(xstream.getMapper()));
-        // TODO policies/enrichers serialization/deserialization?!
     }
     
     // Warning: this is called in the super-class constuctor, so before this constructor!
@@ -187,6 +196,26 @@ public class XmlMementoSerializer<T> extends XmlSerializer<T> implements Memento
             return lookupContext.lookupLocation(type, id);
         }
     }
+
+    public class PolicyConverter extends IdentifiableConverter<Policy> {
+        PolicyConverter() {
+            super(Policy.class);
+        }
+        @Override
+        protected Policy lookup(Class<?> type, String id) {
+            return lookupContext.lookupPolicy(type, id);
+        }
+    }
+
+    public class EnricherConverter extends IdentifiableConverter<Enricher> {
+        EnricherConverter() {
+            super(Enricher.class);
+        }
+        @Override
+        protected Enricher lookup(Class<?> type, String id) {
+            return lookupContext.lookupEnricher(type, id);
+        }
+    }
     
     public class EntityConverter extends IdentifiableConverter<Entity> {
         EntityConverter() {

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/80532a5b/core/src/main/java/brooklyn/management/internal/EntityChangeListener.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/brooklyn/management/internal/EntityChangeListener.java b/core/src/main/java/brooklyn/management/internal/EntityChangeListener.java
index 197b5ae..36a6324 100644
--- a/core/src/main/java/brooklyn/management/internal/EntityChangeListener.java
+++ b/core/src/main/java/brooklyn/management/internal/EntityChangeListener.java
@@ -30,7 +30,7 @@ public interface EntityChangeListener {
 
     void onChildrenChanged();
 
-    void onPoliciesChanged();
+    void onPoliciesChanged(); // TODO
 
     void onEffectorStarting(Effector<?> effector);
     

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/80532a5b/core/src/main/java/brooklyn/management/internal/EntityManagementSupport.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/brooklyn/management/internal/EntityManagementSupport.java b/core/src/main/java/brooklyn/management/internal/EntityManagementSupport.java
index c9b974b..6d65648 100644
--- a/core/src/main/java/brooklyn/management/internal/EntityManagementSupport.java
+++ b/core/src/main/java/brooklyn/management/internal/EntityManagementSupport.java
@@ -344,7 +344,9 @@ public class EntityManagementSupport {
         }
         @Override
         public void onAttributeChanged(AttributeSensor<?> attribute) {
+            // if important persist, otherwiise ignore
             getManagementContext().getRebindManager().getChangeListener().onChanged(entity);
+            // getManagementContext().getRebindManager().getAttributeChangeListener().onChanged(entity, attribute);
         }
         @Override
         public void onConfigChanged(ConfigKey<?> key) {

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/80532a5b/core/src/test/java/brooklyn/entity/rebind/persister/XmlMementoSerializerTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/brooklyn/entity/rebind/persister/XmlMementoSerializerTest.java b/core/src/test/java/brooklyn/entity/rebind/persister/XmlMementoSerializerTest.java
index 02e06fb..47d525b 100644
--- a/core/src/test/java/brooklyn/entity/rebind/persister/XmlMementoSerializerTest.java
+++ b/core/src/test/java/brooklyn/entity/rebind/persister/XmlMementoSerializerTest.java
@@ -22,6 +22,8 @@ import brooklyn.location.Location;
 import brooklyn.location.LocationSpec;
 import brooklyn.management.ManagementContext;
 import brooklyn.mementos.BrooklynMementoPersister.LookupContext;
+import brooklyn.policy.Enricher;
+import brooklyn.policy.Policy;
 import brooklyn.test.entity.TestApplication;
 import brooklyn.util.collections.MutableList;
 import brooklyn.util.collections.MutableMap;
@@ -43,76 +45,76 @@ public class XmlMementoSerializerTest {
     public void setUp() throws Exception {
         serializer = new XmlMementoSerializer<Object>(XmlMementoSerializerTest.class.getClassLoader());
     }
-    
+
     @Test
     public void testMutableSet() throws Exception {
         Set<?> obj = MutableSet.of("123");
         assertSerializeAndDeserialize(obj);
     }
-    
+
     @Test
     public void testLinkedHashSet() throws Exception {
         Set<String> obj = new LinkedHashSet<String>();
         obj.add("123");
         assertSerializeAndDeserialize(obj);
     }
-    
+
     @Test
     public void testImmutableSet() throws Exception {
         Set<String> obj = ImmutableSet.of("123");
         assertSerializeAndDeserialize(obj);
     }
-    
+
     @Test
     public void testMutableList() throws Exception {
         List<?> obj = MutableList.of("123");
         assertSerializeAndDeserialize(obj);
     }
-    
+
     @Test
     public void testLinkedList() throws Exception {
         List<String> obj = new LinkedList<String>();
         obj.add("123");
         assertSerializeAndDeserialize(obj);
     }
-    
+
     @Test
     public void testImmutableList() throws Exception {
         List<String> obj = ImmutableList.of("123");
         assertSerializeAndDeserialize(obj);
     }
-    
+
     @Test
     public void testMutableMap() throws Exception {
         Map<?,?> obj = MutableMap.of("mykey", "myval");
         assertSerializeAndDeserialize(obj);
     }
-    
+
     @Test
     public void testLinkedHashMap() throws Exception {
         Map<String,String> obj = new LinkedHashMap<String,String>();
         obj.put("mykey", "myval");
         assertSerializeAndDeserialize(obj);
     }
-    
+
     @Test
     public void testImmutableMap() throws Exception {
         Map<?,?> obj = ImmutableMap.of("mykey", "myval");
         assertSerializeAndDeserialize(obj);
     }
-    
+
     @Test
     public void testEntity() throws Exception {
         final TestApplication app = ApplicationBuilder.newManagedApp(TestApplication.class);
         ManagementContext managementContext = app.getManagementContext();
         try {
-            serializer.setLookupContext(new LookupContextImpl(ImmutableMap.of(app.getId(), app), ImmutableMap.<String,Location>of()));
+            serializer.setLookupContext(new LookupContextImpl(ImmutableMap.of(app.getId(), app), ImmutableMap.<String,Location>of(), ImmutableMap.<String,Policy>of(), ImmutableMap.<String,Enricher>of()));
             assertSerializeAndDeserialize(app);
         } finally {
             Entities.destroyAll(managementContext);
         }
     }
-    
+
     @Test
     public void testLocation() throws Exception {
         TestApplication app = ApplicationBuilder.newManagedApp(TestApplication.class);
@@ -120,41 +122,41 @@ public class XmlMementoSerializerTest {
         try {
             @SuppressWarnings("deprecation")
             final Location loc = managementContext.getLocationManager().createLocation(LocationSpec.create(brooklyn.location.basic.SimulatedLocation.class));
-            serializer.setLookupContext(new LookupContextImpl(ImmutableMap.<String,Entity>of(), ImmutableMap.of(loc.getId(), loc)));
+            serializer.setLookupContext(new LookupContextImpl(ImmutableMap.<String,Entity>of(), ImmutableMap.of(loc.getId(), loc), ImmutableMap.<String,Policy>of(), ImmutableMap.<String,Enricher>of()));
             assertSerializeAndDeserialize(loc);
         } finally {
             Entities.destroyAll(managementContext);
         }
     }
-    
+
     @Test
     public void testFieldReffingEntity() throws Exception {
         final TestApplication app = ApplicationBuilder.newManagedApp(TestApplication.class);
         ReffingEntity reffer = new ReffingEntity(app);
         ManagementContext managementContext = app.getManagementContext();
         try {
-            serializer.setLookupContext(new LookupContextImpl(ImmutableMap.of(app.getId(), app), ImmutableMap.<String,Location>of()));
+            serializer.setLookupContext(new LookupContextImpl(ImmutableMap.of(app.getId(), app), ImmutableMap.<String,Location>of(), ImmutableMap.<String,Policy>of(), ImmutableMap.<String,Enricher>of()));
             ReffingEntity reffer2 = assertSerializeAndDeserialize(reffer);
             assertEquals(reffer2.entity, app);
         } finally {
             Entities.destroyAll(managementContext);
         }
     }
-    
+
     @Test
     public void testUntypedFieldReffingEntity() throws Exception {
         final TestApplication app = ApplicationBuilder.newManagedApp(TestApplication.class);
         ReffingEntity reffer = new ReffingEntity((Object)app);
         ManagementContext managementContext = app.getManagementContext();
         try {
-            serializer.setLookupContext(new LookupContextImpl(ImmutableMap.of(app.getId(), app), ImmutableMap.<String,Location>of()));
+            serializer.setLookupContext(new LookupContextImpl(ImmutableMap.of(app.getId(), app), ImmutableMap.<String,Location>of(), ImmutableMap.<String,Policy>of(), ImmutableMap.<String,Enricher>of()));
             ReffingEntity reffer2 = assertSerializeAndDeserialize(reffer);
             assertEquals(reffer2.obj, app);
         } finally {
             Entities.destroyAll(managementContext);
         }
     }
-    
+
     public static class ReffingEntity {
         public Entity entity;
         public Object obj;
@@ -173,7 +175,7 @@ public class XmlMementoSerializerTest {
             return Objects.hashCode(entity, obj);
         }
     }
-    
+
     @SuppressWarnings("unchecked")
     private <T> T assertSerializeAndDeserialize(T obj) throws Exception {
         String serializedForm = serializer.toString(obj);
@@ -182,14 +184,19 @@ public class XmlMementoSerializerTest {
         assertEquals(deserialized, obj, "serializedForm="+serializedForm);
         return (T) deserialized;
     }
-    
+
     static class LookupContextImpl implements LookupContext {
         private final Map<String, ? extends Entity> entities;
         private final Map<String, ? extends Location> locations;
-        
-        LookupContextImpl(Map<String,? extends Entity> entities, Map<String,? extends Location> locations) {
+        private final Map<String, ? extends Policy> policies;
+        private final Map<String, ? extends Enricher> enrichers;
+
+        LookupContextImpl(Map<String,? extends Entity> entities, Map<String,? extends Location> locations,
+                Map<String,? extends Policy> policies, Map<String,? extends Enricher> enrichers) {
             this.entities = entities;
             this.locations = locations;
+            this.policies = policies;
+            this.enrichers = enrichers;
         }
         @Override public Entity lookupEntity(Class<?> type, String id) {
             if (entities.containsKey(id)) {
@@ -199,7 +206,7 @@ public class XmlMementoSerializerTest {
                 }
                 return result;
             }
-            throw new NoSuchElementException("no entity with id "+id+"; contenders are "+locations.keySet()); 
+            throw new NoSuchElementException("no entity with id "+id+"; contenders are "+entities.keySet());
         }
         @Override public Location lookupLocation(Class<?> type, String id) {
             if (locations.containsKey(id)) {
@@ -209,7 +216,27 @@ public class XmlMementoSerializerTest {
                 }
                 return result;
             }
-            throw new NoSuchElementException("no location with id "+id+"; contenders are "+locations.keySet()); 
+            throw new NoSuchElementException("no location with id "+id+"; contenders are "+locations.keySet());
+        }
+        @Override public Policy lookupPolicy(Class<?> type, String id) {
+            if (policies.containsKey(id)) {
+                Policy result = policies.get(id);
+                if (type != null && !type.isInstance(result)) {
+                    throw new IllegalStateException("Policy with id "+id+" does not match type "+type+"; got "+result);
+                }
+                return result;
+            }
+            throw new NoSuchElementException("no policy with id "+id+"; contenders are "+policies.keySet());
+        }
+        @Override public Enricher lookupEnricher(Class<?> type, String id) {
+            if (enrichers.containsKey(id)) {
+                Enricher result = enrichers.get(id);
+                if (type != null && !type.isInstance(result)) {
+                    throw new IllegalStateException("Enricher with id "+id+" does not match type "+type+"; got "+result);
+                }
+                return result;
+            }
+            throw new NoSuchElementException("no enricher with id "+id+"; contenders are "+enrichers.keySet());
         }
     };
 }


[25/50] [abbrv] git commit: Merge pull request #1412 from grkvlt/enhancement/iptables-rules

Posted by ri...@apache.org.
Merge pull request #1412 from grkvlt/enhancement/iptables-rules

Fix use of service command with iptables and deprecate old methods

Project: http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/commit/48a34e41
Tree: http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/tree/48a34e41
Diff: http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/diff/48a34e41

Branch: refs/pull/1411/merge
Commit: 48a34e414bee3918ceff23c65481ab22d4a2859c
Parents: f54024f 803f9f1
Author: Aled Sage <al...@gmail.com>
Authored: Fri May 23 15:40:35 2014 +0100
Committer: Aled Sage <al...@gmail.com>
Committed: Fri May 23 15:40:35 2014 +0100

----------------------------------------------------------------------
 .../location/jclouds/JcloudsLocationConfig.java |  1 +
 .../brooklyn/util/ssh/IptablesCommands.java     | 97 +++++++++++---------
 2 files changed, 54 insertions(+), 44 deletions(-)
----------------------------------------------------------------------



[09/50] [abbrv] git commit: Deletes nested DynamicClusterTest.FailingEntity

Posted by ri...@apache.org.
Deletes nested DynamicClusterTest.FailingEntity

- use instead brooklyn.entity.trait.FailingEntity


Project: http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/commit/b0e541e4
Tree: http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/tree/b0e541e4
Diff: http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/diff/b0e541e4

Branch: refs/pull/1411/merge
Commit: b0e541e487af240c698e46f314c9a8271e7bc446
Parents: d52e7ed
Author: Aled Sage <al...@gmail.com>
Authored: Wed May 21 12:18:25 2014 +0100
Committer: Aled Sage <al...@gmail.com>
Committed: Wed May 21 15:52:42 2014 +0100

----------------------------------------------------------------------
 .../entity/group/DynamicClusterTest.java        | 101 +++++++------------
 1 file changed, 38 insertions(+), 63 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/b0e541e4/core/src/test/java/brooklyn/entity/group/DynamicClusterTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/brooklyn/entity/group/DynamicClusterTest.java b/core/src/test/java/brooklyn/entity/group/DynamicClusterTest.java
index 9fb9230..a59079d 100644
--- a/core/src/test/java/brooklyn/entity/group/DynamicClusterTest.java
+++ b/core/src/test/java/brooklyn/entity/group/DynamicClusterTest.java
@@ -34,6 +34,7 @@ import brooklyn.entity.basic.EntityFactory;
 import brooklyn.entity.basic.Lifecycle;
 import brooklyn.entity.proxying.EntitySpec;
 import brooklyn.entity.trait.Changeable;
+import brooklyn.entity.trait.FailingEntity;
 import brooklyn.location.Location;
 import brooklyn.location.basic.SimulatedLocation;
 import brooklyn.management.Task;
@@ -330,7 +331,10 @@ public class DynamicClusterTest {
                 .configure("factory", new EntityFactory() {
                     @Override public Entity newEntity(Map flags, Entity parent) {
                         int num = counter.incrementAndGet();
-                        return new FailingEntity(flags, (num==failNum));
+                        return app.getManagementContext().getEntityManager().createEntity(EntitySpec.create(FailingEntity.class)
+                                .configure(flags)
+                                .configure(FailingEntity.FAIL_ON_START, (num==failNum))
+                                .parent(parent));
                     }}));
 
         cluster.start(ImmutableList.of(loc));
@@ -338,7 +342,7 @@ public class DynamicClusterTest {
         assertEquals(cluster.getCurrentSize(), (Integer)2);
         assertEquals(cluster.getMembers().size(), 2);
         for (Entity member : cluster.getMembers()) {
-            assertFalse(((FailingEntity)member).failOnStart);
+            assertFalse(((FailingEntity)member).getConfig(FailingEntity.FAIL_ON_START));
         }
     }
 
@@ -352,7 +356,10 @@ public class DynamicClusterTest {
                 .configure("factory", new EntityFactory() {
                     @Override public Entity newEntity(Map flags, Entity parent) {
                         int num = counter.incrementAndGet();
-                        return new FailingEntity(flags, (num==failNum));
+                        return app.getManagementContext().getEntityManager().createEntity(EntitySpec.create(FailingEntity.class)
+                                .configure(flags)
+                                .configure(FailingEntity.FAIL_ON_START, (num==failNum))
+                                .parent(parent));
                     }}));
 
         cluster.start(ImmutableList.of(loc));
@@ -361,7 +368,7 @@ public class DynamicClusterTest {
         assertEquals(cluster.getCurrentSize(), (Integer)1);
         assertEquals(cluster.getMembers().size(), 1);
         for (Entity member : cluster.getMembers()) {
-            assertFalse(((FailingEntity)member).failOnStart);
+            assertFalse(((FailingEntity)member).getConfig(FailingEntity.FAIL_ON_START));
         }
     }
 
@@ -374,7 +381,10 @@ public class DynamicClusterTest {
                 .configure("factory", new EntityFactory() {
                     @Override public Entity newEntity(Map flags, Entity parent) {
                         int num = counter.incrementAndGet();
-                        return new FailingEntity(flags, (num==failNum));
+                        return app.getManagementContext().getEntityManager().createEntity(EntitySpec.create(FailingEntity.class)
+                                .configure(flags)
+                                .configure(FailingEntity.FAIL_ON_START, (num==failNum))
+                                .parent(parent));
                     }}));
 
         try {
@@ -392,7 +402,7 @@ public class DynamicClusterTest {
         assertEquals(cluster.getCurrentSize(), (Integer)1);
         assertEquals(cluster.getMembers().size(), 1);
         for (Entity member : cluster.getMembers()) {
-            assertFalse(((FailingEntity)member).failOnStart);
+            assertFalse(((FailingEntity)member).getConfig(FailingEntity.FAIL_ON_START));
         }
     }
 
@@ -406,7 +416,10 @@ public class DynamicClusterTest {
                 .configure("factory", new EntityFactory() {
                     @Override public Entity newEntity(Map flags, Entity parent) {
                         int num = counter.incrementAndGet();
-                        return new FailingEntity(flags, (num==failNum));
+                        return app.getManagementContext().getEntityManager().createEntity(EntitySpec.create(FailingEntity.class)
+                                .configure(flags)
+                                .configure(FailingEntity.FAIL_ON_START, (num==failNum))
+                                .parent(parent));
                     }}));
 
         cluster.start(ImmutableList.of(loc));
@@ -414,13 +427,13 @@ public class DynamicClusterTest {
         assertEquals(cluster.getCurrentSize(), (Integer)2);
         assertEquals(cluster.getMembers().size(), 2);
         assertEquals(Iterables.size(Iterables.filter(cluster.getChildren(), Predicates.instanceOf(FailingEntity.class))), 3);
-        for (Entity it : cluster.getMembers()) {
-            assertFalse(((FailingEntity)it).failOnStart);
+        for (Entity member : cluster.getMembers()) {
+            assertFalse(((FailingEntity)member).getConfig(FailingEntity.FAIL_ON_START));
         }
 
         assertEquals(cluster.getAttribute(DynamicCluster.QUARANTINE_GROUP).getMembers().size(), 1);
-        for (Entity it : cluster.getAttribute(DynamicCluster.QUARANTINE_GROUP).getMembers()) {
-            assertTrue(((FailingEntity)it).failOnStart);
+        for (Entity member : cluster.getAttribute(DynamicCluster.QUARANTINE_GROUP).getMembers()) {
+            assertTrue(((FailingEntity)member).getConfig(FailingEntity.FAIL_ON_START));
         }
     }
 
@@ -435,7 +448,10 @@ public class DynamicClusterTest {
                 .configure("factory", new EntityFactory() {
                     @Override public Entity newEntity(Map flags, Entity parent) {
                         int num = counter.incrementAndGet();
-                        return new FailingEntity(flags, (num==failNum));
+                        return app.getManagementContext().getEntityManager().createEntity(EntitySpec.create(FailingEntity.class)
+                                .configure(flags)
+                                .configure(FailingEntity.FAIL_ON_START, (num==failNum))
+                                .parent(parent));
                     }}));
 
         cluster.start(ImmutableList.of(loc));
@@ -452,14 +468,12 @@ public class DynamicClusterTest {
         // Failed node will not be managed either
         assertEquals(Iterables.size(Iterables.filter(cluster.getChildren(), Predicates.instanceOf(FailingEntity.class))), 2);
         for (Entity member : cluster.getMembers()) {
-            assertFalse(((FailingEntity)member).failOnStart);
+            assertFalse(((FailingEntity)member).getConfig(FailingEntity.FAIL_ON_START));
         }
     }
 
     @Test
     public void defaultRemovalStrategyShutsDownNewestFirstWhenResizing() throws Exception {
-        TestEntity entity;
-        final int failNum = 2;
         final List<Entity> creationOrder = Lists.newArrayList();
         DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
                 .configure("initialSize", 0)
@@ -709,7 +723,10 @@ public class DynamicClusterTest {
                 .configure("factory", new EntityFactory() {
                     @Override public Entity newEntity(Map flags, Entity parent) {
                         int num = counter.incrementAndGet();
-                        return new FailingEntity(flags, (num==failNum));
+                        return app.getManagementContext().getEntityManager().createEntity(EntitySpec.create(FailingEntity.class)
+                                .configure(flags)
+                                .configure(FailingEntity.FAIL_ON_START, (num==failNum))
+                                .parent(parent));
                     }}));
 
         cluster.start(ImmutableList.of(loc));
@@ -734,7 +751,10 @@ public class DynamicClusterTest {
                 .configure("factory", new EntityFactory() {
                     @Override public Entity newEntity(Map flags, Entity parent) {
                         int num = counter.incrementAndGet();
-                        return new FailingEntity(flags, false, (num==failNum), IllegalStateException.class);
+                        return app.getManagementContext().getEntityManager().createEntity(EntitySpec.create(FailingEntity.class)
+                                .configure(flags)
+                                .configure(FailingEntity.FAIL_ON_STOP, (num==failNum))
+                                .parent(parent));
                     }}));
 
         cluster.start(ImmutableList.of(loc));
@@ -767,49 +787,4 @@ public class DynamicClusterTest {
             return e;
         }
     }
-
-    public static class FailingEntity extends TestEntityImpl {
-        final boolean failOnStart;
-        final boolean failOnStop;
-        final Class<? extends Exception> exceptionClazz;
-    
-        public FailingEntity(Map flags, boolean failOnStart) {
-            this(flags, failOnStart, false);
-        }
-        
-        public FailingEntity(Map flags, boolean failOnStart, boolean failOnStop) {
-            this(flags, failOnStart, failOnStop, IllegalStateException.class);
-        }
-        
-        public FailingEntity(Map flags, boolean failOnStart, boolean failOnStop, Class<? extends Exception> exceptionClazz) {
-            super(flags);
-            this.failOnStart = failOnStart;
-            this.failOnStop = failOnStop;
-            this.exceptionClazz = exceptionClazz;
-        }
-        
-        @Override
-        public void start(Collection<? extends Location> locs) {
-            if (failOnStart) {
-                try {
-                    Exception e = exceptionClazz.getConstructor(String.class).newInstance("Simulating entity start failure for test");
-                    throw e;
-                } catch (Exception e) {
-                    throw Exceptions.propagate(e);
-                }
-            }
-        }
-        
-        @Override
-        public void stop() {
-            if (failOnStop) {
-                try {
-                    Exception e = exceptionClazz.getConstructor(String.class).newInstance("Simulating entity stop failure for test");
-                    throw e;
-                } catch (Exception e) {
-                    throw Exceptions.propagate(e);
-                }
-            }
-        }
-    }
-}
\ No newline at end of file
+}


[27/50] [abbrv] git commit: support OS_FAMILY and OS_VERSION_REGEX for jclouds

Posted by ri...@apache.org.
support OS_FAMILY and OS_VERSION_REGEX for jclouds


Project: http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/commit/37bf67ae
Tree: http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/tree/37bf67ae
Diff: http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/diff/37bf67ae

Branch: refs/pull/1414/head
Commit: 37bf67ae7f352320a043b28e0e0cf2499108ecee
Parents: f54024f
Author: Alex Heneveld <al...@cloudsoftcorp.com>
Authored: Fri May 23 10:08:07 2014 -0600
Committer: Alex Heneveld <al...@cloudsoftcorp.com>
Committed: Fri May 23 10:08:07 2014 -0600

----------------------------------------------------------------------
 .../brooklyn/location/jclouds/JcloudsLocation.java  | 16 +++++++++++++++-
 .../location/jclouds/JcloudsLocationConfig.java     |  7 ++++++-
 2 files changed, 21 insertions(+), 2 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/37bf67ae/locations/jclouds/src/main/java/brooklyn/location/jclouds/JcloudsLocation.java
----------------------------------------------------------------------
diff --git a/locations/jclouds/src/main/java/brooklyn/location/jclouds/JcloudsLocation.java b/locations/jclouds/src/main/java/brooklyn/location/jclouds/JcloudsLocation.java
index 328baf3..e4c3fce 100644
--- a/locations/jclouds/src/main/java/brooklyn/location/jclouds/JcloudsLocation.java
+++ b/locations/jclouds/src/main/java/brooklyn/location/jclouds/JcloudsLocation.java
@@ -43,6 +43,7 @@ import org.jclouds.compute.domain.Image;
 import org.jclouds.compute.domain.NodeMetadata;
 import org.jclouds.compute.domain.NodeMetadata.Status;
 import org.jclouds.compute.domain.NodeMetadataBuilder;
+import org.jclouds.compute.domain.OsFamily;
 import org.jclouds.compute.domain.Template;
 import org.jclouds.compute.domain.TemplateBuilder;
 import org.jclouds.compute.domain.TemplateBuilderSpec;
@@ -99,8 +100,10 @@ import brooklyn.util.exceptions.CompoundRuntimeException;
 import brooklyn.util.exceptions.Exceptions;
 import brooklyn.util.flags.SetFromFlag;
 import brooklyn.util.flags.TypeCoercions;
+import brooklyn.util.guava.Maybe;
 import brooklyn.util.internal.ssh.ShellTool;
 import brooklyn.util.internal.ssh.SshTool;
+import brooklyn.util.javalang.Enums;
 import brooklyn.util.javalang.Reflections;
 import brooklyn.util.net.Cidr;
 import brooklyn.util.net.Networking;
@@ -851,6 +854,17 @@ public class JcloudsLocation extends AbstractCloudMachineProvisioningLocation im
                     public void apply(TemplateBuilder tb, ConfigBag props, Object v) {
                         tb.imageNameMatches(((CharSequence)v).toString());
                     }})
+            .put(OS_FAMILY, new CustomizeTemplateBuilder() {
+                    public void apply(TemplateBuilder tb, ConfigBag props, Object v) {
+                        Maybe<OsFamily> osFamily = Enums.valueOfIgnoreCase(OsFamily.class, v.toString());
+                        if (osFamily.isAbsent())
+                            throw new IllegalArgumentException("Invalid "+OS_FAMILY+" value "+v);
+                        tb.osFamily(osFamily.get());
+                    }})
+            .put(OS_VERSION_REGEX, new CustomizeTemplateBuilder() {
+                    public void apply(TemplateBuilder tb, ConfigBag props, Object v) {
+                        tb.osVersionMatches( ((CharSequence)v).toString() );
+                    }})
             .put(TEMPLATE_SPEC, new CustomizeTemplateBuilder() {
                 public void apply(TemplateBuilder tb, ConfigBag props, Object v) {
                         tb.from(TemplateBuilderSpec.parse(((CharSequence)v).toString()));
@@ -864,7 +878,7 @@ public class JcloudsLocation extends AbstractCloudMachineProvisioningLocation im
                         /* done in the code, but included here so that it is in the map */
                     }})
             .build();
-   
+    
     /** properties which cause customization of the TemplateOptions */
     public static final Map<ConfigKey<?>,CustomizeTemplateOptions> SUPPORTED_TEMPLATE_OPTIONS_PROPERTIES = ImmutableMap.<ConfigKey<?>,CustomizeTemplateOptions>builder()
             .put(SECURITY_GROUPS, new CustomizeTemplateOptions() {

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/37bf67ae/locations/jclouds/src/main/java/brooklyn/location/jclouds/JcloudsLocationConfig.java
----------------------------------------------------------------------
diff --git a/locations/jclouds/src/main/java/brooklyn/location/jclouds/JcloudsLocationConfig.java b/locations/jclouds/src/main/java/brooklyn/location/jclouds/JcloudsLocationConfig.java
index 49729a1..73db853 100644
--- a/locations/jclouds/src/main/java/brooklyn/location/jclouds/JcloudsLocationConfig.java
+++ b/locations/jclouds/src/main/java/brooklyn/location/jclouds/JcloudsLocationConfig.java
@@ -1,11 +1,11 @@
 package brooklyn.location.jclouds;
 
-import java.io.File;
 import java.util.Collection;
 import java.util.concurrent.Semaphore;
 
 import org.jclouds.Constants;
 import org.jclouds.compute.domain.Image;
+import org.jclouds.compute.domain.OsFamily;
 import org.jclouds.compute.domain.TemplateBuilder;
 import org.jclouds.domain.LoginCredentials;
 
@@ -187,6 +187,11 @@ public interface JcloudsLocationConfig extends CloudLocationConfig {
         "imageChooser", "An image chooser function to control which images are preferred", 
         new BrooklynImageChooser().chooser());
 
+    public static final ConfigKey<OsFamily> OS_FAMILY = ConfigKeys.newConfigKey(OsFamily.class, "osFamily", 
+        "OS family, e.g. CentOS, Debian, RHEL, Ubuntu");
+    public static final ConfigKey<String> OS_VERSION_REGEX = ConfigKeys.newStringConfigKey("osVersionRegex", 
+        "Regular expression for the OS version to load");
+
     // TODO
     
 //  "noDefaultSshKeys" - hints that local ssh keys should not be read as defaults


[38/50] [abbrv] git commit: Merge pull request #1385 from Nakomis/abstract-membership-tracking-policy-ignore-duplicates

Posted by ri...@apache.org.
Merge pull request #1385 from Nakomis/abstract-membership-tracking-policy-ignore-duplicates

Added NOTIFY_ON_DUPLICATES to AbstractMembershipTrackingPolicy

Project: http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/commit/1c9ae924
Tree: http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/tree/1c9ae924
Diff: http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/diff/1c9ae924

Branch: refs/heads/master
Commit: 1c9ae9245088e6904c4ed66ec1f592e2588e6f8e
Parents: cb2d0d3 6f33889
Author: Andrew Kennedy <gr...@apache.org>
Authored: Fri May 23 17:20:05 2014 +0100
Committer: Andrew Kennedy <gr...@apache.org>
Committed: Fri May 23 17:20:05 2014 +0100

----------------------------------------------------------------------
 .../group/AbstractMembershipTrackingPolicy.java | 77 ++++++++++++++------
 .../group/MembershipTrackingPolicyTest.java     | 39 +++++++++-
 .../brooklyn/util/collections/MutableSet.java   |  2 +
 3 files changed, 95 insertions(+), 23 deletions(-)
----------------------------------------------------------------------



[12/50] [abbrv] git commit: Updated following PR review

Posted by ri...@apache.org.
Updated following PR review


Project: http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/commit/6f338897
Tree: http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/tree/6f338897
Diff: http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/diff/6f338897

Branch: refs/heads/master
Commit: 6f338897b704b1db1b88ec5cd9c1522e39ba2f08
Parents: 238780f
Author: Martin Harris <gi...@nakomis.com>
Authored: Thu May 22 10:47:42 2014 +0100
Committer: Martin Harris <gi...@nakomis.com>
Committed: Thu May 22 10:47:42 2014 +0100

----------------------------------------------------------------------
 .../brooklyn/entity/group/AbstractMembershipTrackingPolicy.java | 5 ++---
 .../src/main/java/brooklyn/util/collections/MutableSet.java     | 3 ---
 2 files changed, 2 insertions(+), 6 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/6f338897/core/src/main/java/brooklyn/entity/group/AbstractMembershipTrackingPolicy.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/brooklyn/entity/group/AbstractMembershipTrackingPolicy.java b/core/src/main/java/brooklyn/entity/group/AbstractMembershipTrackingPolicy.java
index 99fd2b5..049d49c 100644
--- a/core/src/main/java/brooklyn/entity/group/AbstractMembershipTrackingPolicy.java
+++ b/core/src/main/java/brooklyn/entity/group/AbstractMembershipTrackingPolicy.java
@@ -20,7 +20,6 @@ import brooklyn.event.SensorEvent;
 import brooklyn.event.SensorEventListener;
 import brooklyn.policy.basic.AbstractPolicy;
 import brooklyn.util.collections.MutableMap;
-import brooklyn.util.collections.MutableSet;
 
 import com.google.common.base.Objects;
 import com.google.common.base.Preconditions;
@@ -55,10 +54,10 @@ public abstract class AbstractMembershipTrackingPolicy extends AbstractPolicy {
     }
 
     protected Set<Sensor<?>> getSensorsToTrack() {
-        return MutableSet.<Sensor<?>>builder()
+        return ImmutableSet.<Sensor<?>>builder()
                 .addAll(getRequiredConfig(SENSORS_TO_TRACK))
                 .add(Attributes.SERVICE_UP)
-                .buildImmutable();
+                .build();
     }
     
     /**

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/6f338897/utils/common/src/main/java/brooklyn/util/collections/MutableSet.java
----------------------------------------------------------------------
diff --git a/utils/common/src/main/java/brooklyn/util/collections/MutableSet.java b/utils/common/src/main/java/brooklyn/util/collections/MutableSet.java
index 6ab967a..f791949 100644
--- a/utils/common/src/main/java/brooklyn/util/collections/MutableSet.java
+++ b/utils/common/src/main/java/brooklyn/util/collections/MutableSet.java
@@ -111,9 +111,6 @@ public class MutableSet<V> extends LinkedHashSet<V> {
           return new MutableSet<V>(result);
         }
         
-        public ImmutableSet<V> buildImmutable() {
-            return ImmutableSet.copyOf(result);
-        }
     }
     
     public boolean addIfNotNull(V e) {


[37/50] [abbrv] git commit: Merge pull request #1385 from Nakomis/abstract-membership-tracking-policy-ignore-duplicates

Posted by ri...@apache.org.
Merge pull request #1385 from Nakomis/abstract-membership-tracking-policy-ignore-duplicates

Added NOTIFY_ON_DUPLICATES to AbstractMembershipTrackingPolicy

Project: http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/commit/1c9ae924
Tree: http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/tree/1c9ae924
Diff: http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/diff/1c9ae924

Branch: refs/pull/1411/merge
Commit: 1c9ae9245088e6904c4ed66ec1f592e2588e6f8e
Parents: cb2d0d3 6f33889
Author: Andrew Kennedy <gr...@apache.org>
Authored: Fri May 23 17:20:05 2014 +0100
Committer: Andrew Kennedy <gr...@apache.org>
Committed: Fri May 23 17:20:05 2014 +0100

----------------------------------------------------------------------
 .../group/AbstractMembershipTrackingPolicy.java | 77 ++++++++++++++------
 .../group/MembershipTrackingPolicyTest.java     | 39 +++++++++-
 .../brooklyn/util/collections/MutableSet.java   |  2 +
 3 files changed, 95 insertions(+), 23 deletions(-)
----------------------------------------------------------------------



[31/50] [abbrv] git commit: Merge pull request #1398 from aledsage/refactor/DynamicClusterTest-from-groovy-to-java

Posted by ri...@apache.org.
Merge pull request #1398 from aledsage/refactor/DynamicClusterTest-from-groovy-to-java

Refactor DynamicClusterTest from groovy to java (and tidies)

Project: http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/commit/cb2d0d3a
Tree: http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/tree/cb2d0d3a
Diff: http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/diff/cb2d0d3a

Branch: refs/heads/master
Commit: cb2d0d3a184095b4bfdefe73a95435f4e4beb906
Parents: 48a34e4 b0e541e
Author: Andrew Kennedy <gr...@apache.org>
Authored: Fri May 23 17:18:40 2014 +0100
Committer: Andrew Kennedy <gr...@apache.org>
Committed: Fri May 23 17:18:40 2014 +0100

----------------------------------------------------------------------
 .../entity/group/DynamicClusterTest.groovy      | 726 -----------------
 .../entity/group/DynamicClusterTest.java        | 790 +++++++++++++++++++
 2 files changed, 790 insertions(+), 726 deletions(-)
----------------------------------------------------------------------



[02/50] [abbrv] git commit: Covert DynamicClusterTest from groovy to java

Posted by ri...@apache.org.
Covert DynamicClusterTest from groovy to java


Project: http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/commit/d52e7ed2
Tree: http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/tree/d52e7ed2
Diff: http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/diff/d52e7ed2

Branch: refs/pull/1408/merge
Commit: d52e7ed2fe0c2aa623bcacee6dd4f3638e2c5647
Parents: d3d5c11
Author: Aled Sage <al...@gmail.com>
Authored: Wed May 21 12:07:53 2014 +0100
Committer: Aled Sage <al...@gmail.com>
Committed: Wed May 21 15:52:41 2014 +0100

----------------------------------------------------------------------
 .../entity/group/DynamicClusterTest.groovy      | 726 -----------------
 .../entity/group/DynamicClusterTest.java        | 815 +++++++++++++++++++
 2 files changed, 815 insertions(+), 726 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/d52e7ed2/core/src/test/java/brooklyn/entity/group/DynamicClusterTest.groovy
----------------------------------------------------------------------
diff --git a/core/src/test/java/brooklyn/entity/group/DynamicClusterTest.groovy b/core/src/test/java/brooklyn/entity/group/DynamicClusterTest.groovy
deleted file mode 100644
index 636abbc..0000000
--- a/core/src/test/java/brooklyn/entity/group/DynamicClusterTest.groovy
+++ /dev/null
@@ -1,726 +0,0 @@
-package brooklyn.entity.group
-
-import brooklyn.entity.basic.Attributes
-import brooklyn.entity.basic.Lifecycle
-
-import static org.testng.Assert.*
-
-import java.util.concurrent.CopyOnWriteArrayList
-import java.util.concurrent.CountDownLatch
-import java.util.concurrent.ExecutionException
-import java.util.concurrent.ExecutorService
-import java.util.concurrent.Executors
-import java.util.concurrent.TimeUnit
-import java.util.concurrent.atomic.AtomicInteger
-
-import org.testng.annotations.AfterMethod
-import org.testng.annotations.BeforeMethod
-import org.testng.annotations.Test
-
-import brooklyn.entity.Application
-import brooklyn.entity.Entity
-import brooklyn.entity.basic.ApplicationBuilder
-import brooklyn.entity.basic.BrooklynTaskTags
-import brooklyn.entity.basic.Entities
-import brooklyn.entity.proxying.EntitySpec
-import brooklyn.entity.trait.Changeable
-import brooklyn.location.Location
-import brooklyn.location.basic.SimulatedLocation
-import brooklyn.management.Task
-import brooklyn.test.TestUtils
-import brooklyn.test.entity.TestApplication
-import brooklyn.test.entity.TestEntity
-import brooklyn.test.entity.TestEntityImpl
-import brooklyn.util.GroovyJavaMethods
-import brooklyn.util.exceptions.Exceptions
-
-import com.google.common.base.Predicates
-import com.google.common.base.Throwables;
-import com.google.common.collect.ImmutableList
-import com.google.common.collect.ImmutableSet
-import com.google.common.collect.Iterables
-
-
-class DynamicClusterTest {
-
-    private static final int TIMEOUT_MS = 2000
-
-    TestApplication app
-    SimulatedLocation loc
-    SimulatedLocation loc2
-    Random random = new Random()
-
-    @BeforeMethod
-    public void setUp() {
-        app = ApplicationBuilder.newManagedApp(TestApplication.class);
-        loc = new SimulatedLocation()
-        loc2 = new SimulatedLocation()
-    }
-
-    @AfterMethod(alwaysRun = true)
-    public void tearDown(){
-        if (app != null) Entities.destroyAll(app.getManagementContext());
-    }
-
-    @Test
-    public void creationOkayWithoutNewEntityFactoryArgument() {
-        app.createAndManageChild(EntitySpec.create(DynamicCluster.class));
-    }
-
-    @Test
-    public void constructionRequiresThatNewEntityArgumentIsAnEntityFactory() {
-        try {
-            app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
-                    .configure("factory", "error"));
-            fail();
-        } catch (Exception e) {
-            if (Exceptions.getFirstThrowableOfType(e, IllegalArgumentException.class) == null) throw e;
-        }
-    }
-
-    @Test
-    public void startRequiresThatNewEntityArgumentIsGiven() {
-        DynamicCluster c = app.createAndManageChild(EntitySpec.create(DynamicCluster.class));
-        try {
-            c.start([loc]);
-            fail();
-        } catch (Exception e) {
-            if (Exceptions.getFirstThrowableOfType(e, IllegalStateException.class) == null) throw e;
-        }
-    }
-
-    @Test
-    public void startMethodFailsIfLocationsParameterHasMoreThanOneElement() {
-        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
-                .configure("factory", { new TestEntityImpl() }));
-        try {
-            cluster.start([ loc, loc2 ])
-            fail();
-        } catch (Exception e) {
-            if (Exceptions.getFirstThrowableOfType(e, IllegalArgumentException.class) == null) throw e;
-        }
-    }
-
-    @Test
-    public void testClusterHasOneLocationAfterStarting() {
-        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
-                .configure("factory", { new TestEntityImpl() }));
-        cluster.start([loc])
-        assertEquals(cluster.getLocations().size(), 1)
-        assertEquals(cluster.getLocations() as List, [loc])
-    }
-
-    @Test
-    public void testServiceUpAfterStartingWithNoMembers() {
-        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
-                .configure(DynamicCluster.MEMBER_SPEC, EntitySpec.create(TestEntity.class))
-                .configure(DynamicCluster.INITIAL_SIZE, 0))
-        cluster.start([loc])
-        assertEquals(cluster.getAttribute(Attributes.SERVICE_STATE), Lifecycle.RUNNING)
-        assertTrue(cluster.getAttribute(Attributes.SERVICE_UP))
-    }
-
-    @Test
-    public void usingEntitySpecResizeFromZeroToOneStartsANewEntityAndSetsItsParent() {
-        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
-                .configure("memberSpec", EntitySpec.create(TestEntity.class)));
-        
-        cluster.start([loc])
-
-        cluster.resize(1)
-        Entity entity = Iterables.getOnlyElement(cluster.getMembers());
-        assertEquals entity.count, 1
-        assertEquals entity.parent, cluster
-        assertEquals entity.application, app
-    }
-
-    @Test
-    public void resizeFromZeroToOneStartsANewEntityAndSetsItsParent() {
-        TestEntity entity
-        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
-                .configure("factory", { properties -> entity = new TestEntityImpl(properties) }));
-
-        cluster.start([loc])
-
-        cluster.resize(1)
-        assertEquals entity.counter.get(), 1
-        assertEquals entity.parent, cluster
-        assertEquals entity.application, app
-    }
-
-    @Test
-    public void currentSizePropertyReflectsActualClusterSize() {
-        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
-                .configure("factory", { properties -> return new TestEntityImpl(properties) }));
-
-        assertEquals cluster.currentSize, 0
-
-        cluster.start([loc])
-        assertEquals cluster.currentSize, 1
-        assertEquals cluster.getAttribute(Changeable.GROUP_SIZE), 1
-
-        int newSize = cluster.resize(0)
-        assertEquals newSize, 0
-        assertEquals newSize, cluster.currentSize
-        assertEquals newSize, cluster.members.size()
-        assertEquals newSize, cluster.getAttribute(Changeable.GROUP_SIZE)
-
-        newSize = cluster.resize(4)
-        assertEquals newSize, 4
-        assertEquals newSize, cluster.currentSize
-        assertEquals newSize, cluster.members.size()
-        assertEquals newSize, cluster.getAttribute(Changeable.GROUP_SIZE)
-
-        newSize = cluster.resize(0)
-        assertEquals newSize, 0
-        assertEquals newSize, cluster.currentSize
-        assertEquals newSize, cluster.members.size()
-        assertEquals newSize, cluster.getAttribute(Changeable.GROUP_SIZE)
-    }
-
-    @Test
-    public void clusterSizeAfterStartIsInitialSize() {
-        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
-                .configure("factory", { properties -> return new TestEntityImpl(properties) })
-                .configure("initialSize", 2));
-
-        cluster.start([loc])
-        assertEquals cluster.currentSize, 2
-        assertEquals cluster.members.size(), 2
-        assertEquals cluster.getAttribute(Changeable.GROUP_SIZE), 2
-    }
-
-    @Test
-    public void clusterLocationIsPassedOnToEntityStart() {
-        Collection<Location> locations = [ loc ]
-        TestEntity entity
-        def newEntity = { properties, cluster ->
-            entity = new TestEntityImpl(parent:cluster) {
-	            List<Location> stashedLocations = null
-	            @Override
-	            void start(Collection<? extends Location> loc) {
-	                super.start(loc)
-	                stashedLocations = loc
-	            }
-	        }
-        }
-        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
-                .configure("factory", newEntity)
-                .configure("initialSize", 1));
-
-        cluster.start(locations)
-
-        assertNotNull entity.stashedLocations
-        assertEquals entity.stashedLocations.size(), 1
-        assertEquals entity.stashedLocations[0], locations[0]
-    }
-
-    @Test
-    public void resizeFromOneToZeroChangesClusterSize() {
-        TestEntity entity
-        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
-                .configure("factory", { properties -> entity = new TestEntityImpl(properties) })
-                .configure("initialSize", 1));
-
-        cluster.start([loc])
-        assertEquals cluster.currentSize, 1
-        assertEquals entity.counter.get(), 1
-        cluster.resize(0)
-        assertEquals cluster.currentSize, 0
-        assertEquals entity.counter.get(), 0
-    }
-
-    @Test
-    public void concurrentResizesToSameNumberCreatesCorrectNumberOfNodes() {
-        final int OVERHEAD_MS = 500
-        final int STARTUP_TIME_MS = 50
-        final AtomicInteger numStarted = new AtomicInteger(0)
-        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
-                .configure("factory", { 
-                    Map flags, Entity cluster -> 
-                    Thread.sleep(STARTUP_TIME_MS); numStarted.incrementAndGet(); new TestEntityImpl(flags, cluster)
-                }));
-
-        assertEquals cluster.currentSize, 0
-        cluster.start([loc])
-
-        ExecutorService executor = Executors.newCachedThreadPool()
-        List<Throwable> throwables = new CopyOnWriteArrayList<Throwable>()
-
-        try {
-            for (int i in 1..10) {
-                executor.submit( {
-                    try {
-                        cluster.resize(2)
-                    } catch (Throwable e) {
-                        throwables.add(e)
-                    }
-                })
-            }
-
-            executor.shutdown()
-            assertTrue(executor.awaitTermination(10*STARTUP_TIME_MS+OVERHEAD_MS, TimeUnit.MILLISECONDS))
-            if (throwables.size() > 0) throw throwables.get(0)
-            assertEquals(cluster.currentSize, 2)
-            assertEquals(cluster.getAttribute(Changeable.GROUP_SIZE), 2)
-            assertEquals(numStarted.get(), 2)
-        } finally {
-            executor.shutdownNow();
-        }
-    }
-
-    @Test(enabled = false)
-    public void stoppingTheClusterStopsTheEntity() {
-        TestEntity entity
-        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
-                .configure("factory", { properties -> entity = new TestEntityImpl(properties) })
-                .configure("initialSize", 1));
-
-        cluster.start([loc])
-        assertEquals entity.counter.get(), 1
-        cluster.stop()
-        assertEquals entity.counter.get(), 0
-    }
-
-    /**
-     * This tests the fix for ENGR-1826.
-     */
-    @Test
-    public void failingEntitiesDontBreakClusterActions() {
-        final int failNum = 2
-        final AtomicInteger counter = new AtomicInteger(0)
-        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
-                .configure("initialSize", 0)
-                .configure("factory", { properties ->
-                    int num = counter.incrementAndGet();
-                    return new FailingEntity(properties, (num==failNum))
-                }));
-
-        cluster.start([loc])
-        cluster.resize(3)
-        assertEquals(cluster.currentSize, 2)
-        assertEquals(cluster.getMembers().size(), 2)
-        for (Entity member : cluster.getMembers()) {
-            assertFalse(((FailingEntity)member).failOnStart)
-        }
-    }
-
-    @Test
-    public void testInitialQuorumSizeSufficientForStartup() {
-        final int failNum = 1;
-        final AtomicInteger counter = new AtomicInteger(0)
-        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
-                .configure("initialSize", 2)
-                .configure(DynamicCluster.INITIAL_QUORUM_SIZE, 1)
-                .configure("factory", { properties ->
-                    int num = counter.incrementAndGet();
-                    return new FailingEntity(properties, (num==failNum))
-                }));
-
-        cluster.start([loc])
-        
-        // note that children include quarantine group; and quarantined nodes
-        assertEquals(cluster.getCurrentSize(), 1)
-        assertEquals(cluster.getMembers().size(), 1)
-        for (Entity member : cluster.getMembers()) {
-            assertFalse(((FailingEntity)member).failOnStart)
-        }
-    }
-
-    @Test
-    public void testInitialQuorumSizeDefaultsToInitialSize() throws Exception {
-        final int failNum = 1;
-        final AtomicInteger counter = new AtomicInteger(0)
-        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
-                .configure("initialSize", 2)
-                .configure("factory", { properties ->
-                    int num = counter.incrementAndGet();
-                    return new FailingEntity(properties, (num==failNum))
-                }));
-
-        try {
-            cluster.start([loc])
-        } catch (Exception e) {
-            IllegalStateException unwrapped = Exceptions.getFirstThrowableOfType(e, IllegalStateException.class);
-            if (unwrapped != null && unwrapped.getMessage().contains("failed to get to initial size")) {
-                // success
-            } else {
-                throw e; // fail
-            }
-        }
-        
-        // note that children include quarantine group; and quarantined nodes
-        assertEquals(cluster.getCurrentSize(), 1)
-        assertEquals(cluster.getMembers().size(), 1)
-        for (Entity member : cluster.getMembers()) {
-            assertFalse(((FailingEntity)member).failOnStart)
-        }
-    }
-
-    @Test
-    public void testCanQuarantineFailedEntities() {
-        final int failNum = 2
-        final AtomicInteger counter = new AtomicInteger(0)
-        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
-                .configure("quarantineFailedEntities", true)
-                .configure("initialSize", 0)
-                .configure("factory", { properties ->
-                    int num = counter.incrementAndGet();
-                    return new FailingEntity(properties, (num==failNum))
-                }));
-
-        cluster.start([loc])
-        cluster.resize(3)
-        assertEquals(cluster.currentSize, 2)
-        assertEquals(cluster.getMembers().size(), 2)
-        assertEquals(Iterables.size(Iterables.filter(cluster.getChildren(), Predicates.instanceOf(FailingEntity.class))), 3)
-        cluster.members.each {
-            assertFalse(((FailingEntity)it).failOnStart)
-        }
-
-        assertEquals(cluster.getAttribute(DynamicCluster.QUARANTINE_GROUP).members.size(), 1)
-        cluster.getAttribute(DynamicCluster.QUARANTINE_GROUP).members.each {
-            assertTrue(((FailingEntity)it).failOnStart)
-        }
-    }
-
-    @Test
-    public void testDoNotQuarantineFailedEntities() {
-        final int failNum = 2
-        final AtomicInteger counter = new AtomicInteger(0)
-        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
-                // default is quarantineFailedEntities==true
-                .configure("quarantineFailedEntities", false)
-                .configure("initialSize", 0)
-                .configure("factory", { properties ->
-                    int num = counter.incrementAndGet();
-                    return new FailingEntity(properties, (num==failNum))
-                }));
-
-        cluster.start([loc])
-        
-        // no quarantine group, as a child
-        assertEquals(cluster.getChildren().size(), 0, "children="+cluster.getChildren())
-        
-        // Failed node will not be a member or child
-        cluster.resize(3)
-        assertEquals(cluster.currentSize, 2)
-        assertEquals(cluster.getMembers().size(), 2)
-        assertEquals(cluster.getChildren().size(), 2, "children="+cluster.getChildren())
-        
-        // Failed node will not be managed either
-        assertEquals(Iterables.size(Iterables.filter(cluster.getChildren(), Predicates.instanceOf(FailingEntity.class))), 2)
-        for (Entity member : cluster.getMembers()) {
-            assertFalse(((FailingEntity)member).failOnStart)
-        }
-    }
-
-    @Test
-    public void defaultRemovalStrategyShutsDownNewestFirstWhenResizing() {
-        TestEntity entity
-        final int failNum = 2
-        final List<Entity> creationOrder = []
-        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
-                .configure("initialSize", 0)
-                .configure("factory", { properties ->
-                    Entity result = new TestEntityImpl(properties)
-                    creationOrder << result
-                    return result
-                }));
-
-        cluster.start([loc])
-        cluster.resize(1)
-        cluster.resize(2)
-        assertEquals(cluster.currentSize, 2)
-        assertEquals(ImmutableSet.copyOf(cluster.getMembers()), ImmutableSet.copyOf(creationOrder), "actual="+cluster.getMembers())
-
-        // Now stop one
-        cluster.resize(1)
-        assertEquals(cluster.currentSize, 1)
-        assertEquals(ImmutableList.copyOf(cluster.getMembers()), creationOrder.subList(0, 1))
-    }
-
-    @Test
-    public void resizeLoggedAsEffectorCall() {
-        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
-                .configure("factory", { properties -> return new TestEntityImpl(properties) }));
-
-        app.start([loc])
-        cluster.resize(1)
-
-        Set<Task> tasks = app.getManagementContext().getExecutionManager().getTasksWithAllTags([
-            BrooklynTaskTags.tagForContextEntity(cluster),"EFFECTOR"])
-        assertEquals(tasks.size(), 2)
-        assertTrue(Iterables.get(tasks, 0).getDescription().contains("start"))
-        assertTrue(Iterables.get(tasks, 1).getDescription().contains("resize"))
-    }
-
-    @Test
-    public void testStoppedChildIsRemoveFromGroup() {
-        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
-                .configure("initialSize", 1)
-                .configure("factory", { properties -> return new TestEntityImpl(properties) }));
-
-        cluster.start([loc])
-
-        TestEntity child = Iterables.get(cluster.getMembers(), 0);
-        child.stop()
-        Entities.unmanage(child)
-
-        TestUtils.executeUntilSucceeds(timeout:TIMEOUT_MS) {
-            assertFalse(cluster.getChildren().contains(child), "children="+cluster.getChildren())
-            assertEquals(cluster.currentSize, 0)
-            assertEquals(cluster.members.size(), 0)
-        }
-    }
-
-    @Test
-    public void testPluggableRemovalStrategyIsUsed() {
-        List<Entity> removedEntities = []
-
-        Closure removalStrategy = { Collection<Entity> contenders ->
-            Entity choice = Iterables.get(contenders, random.nextInt(contenders.size()))
-            removedEntities.add(choice)
-            return choice
-        }
-        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
-                .configure("factory", { properties -> return new TestEntityImpl(properties) })
-                .configure("initialSize", 10)
-                .configure("removalStrategy", removalStrategy));
-
-        cluster.start([loc])
-        Set origMembers = cluster.members as Set
-
-        for (int i = 10; i >= 0; i--) {
-            cluster.resize(i)
-            assertEquals(cluster.getAttribute(Changeable.GROUP_SIZE), i)
-            assertEquals(removedEntities.size(), 10-i)
-            assertEquals(ImmutableSet.copyOf(Iterables.concat(cluster.members, removedEntities)), origMembers)
-        }
-    }
-
-    @Test
-    public void testPluggableRemovalStrategyCanBeSetAfterConstruction() {
-        List<Entity> removedEntities = []
-
-        Closure removalStrategy = { Collection<Entity> contenders ->
-            Entity choice = Iterables.get(contenders, random.nextInt(contenders.size()))
-            removedEntities.add(choice)
-            return choice
-        }
-        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
-                .configure("factory", { properties -> return new TestEntityImpl(properties) })
-                .configure("initialSize", 10));
-
-        cluster.start([loc])
-        Set origMembers = cluster.members as Set
-
-        cluster.setRemovalStrategy(GroovyJavaMethods.functionFromClosure(removalStrategy));
-
-        for (int i = 10; i >= 0; i--) {
-            cluster.resize(i)
-            assertEquals(cluster.getAttribute(Changeable.GROUP_SIZE), i)
-            assertEquals(removedEntities.size(), 10-i)
-            assertEquals(ImmutableSet.copyOf(Iterables.concat(cluster.members, removedEntities)), origMembers)
-        }
-    }
-
-    @Test
-    public void testResizeDoesNotBlockCallsToQueryGroupMembership() {
-        CountDownLatch executingLatch = new CountDownLatch(1)
-        CountDownLatch continuationLatch = new CountDownLatch(1)
-        
-        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
-                .configure("initialSize", 0)
-                .configure("factory", { properties ->
-                        executingLatch.countDown()
-                        continuationLatch.await()
-                        return new TestEntityImpl(properties)
-                    }));
-
-        cluster.start([loc])
-
-        Thread thread = new Thread( { cluster.resize(1) })
-        try {
-            // wait for resize to be executing
-            thread.start()
-            executingLatch.await(TIMEOUT_MS, TimeUnit.MILLISECONDS)
-
-            // ensure can still call methods on group, to query/update membership
-            assertEquals(cluster.getMembers(), [])
-            assertEquals(cluster.getCurrentSize(), 0)
-            assertFalse(cluster.hasMember(cluster))
-            cluster.addMember(cluster)
-            assertTrue(cluster.removeMember(cluster))
-
-            // allow the resize to complete
-            continuationLatch.countDown()
-            thread.join(TIMEOUT_MS)
-            assertFalse(thread.isAlive())
-        } finally {
-            thread.interrupt()
-        }
-    }
-
-    @Test
-    public void testReplacesMember() {
-        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
-                .configure("initialSize", 1)
-                .configure("factory", { properties -> return new TestEntityImpl(properties) }));
-
-        cluster.start([loc])
-        Entity member = Iterables.get(cluster.members, 0);
-
-        String replacementId = cluster.replaceMember(member.getId());
-        Entity replacement = cluster.getManagementContext().getEntityManager().getEntity(replacementId);
-
-        assertEquals(cluster.members.size(), 1)
-        assertFalse(cluster.members.contains(member))
-        assertFalse(cluster.children.contains(member))
-        assertNotNull(replacement, "replacementId="+replacementId);
-        assertTrue(cluster.members.contains(replacement), "replacement="+replacement+"; members="+cluster.members);
-        assertTrue(cluster.children.contains(replacement), "replacement="+replacement+"; children="+cluster.children);
-    }
-
-    @Test
-    public void testReplaceMemberThrowsIfMemberIdDoesNotResolve() {
-        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
-                .configure("initialSize", 1)
-                .configure("factory", { properties -> return new TestEntityImpl(properties) }));
-
-        cluster.start([loc])
-        Entity member = Iterables.get(cluster.members, 0);
-
-        try {
-            cluster.replaceMember("wrong.id");
-            fail();
-        } catch (Exception e) {
-            if (Exceptions.getFirstThrowableOfType(e, NoSuchElementException.class) == null) throw e;
-            if (!Exceptions.getFirstThrowableOfType(e, NoSuchElementException.class).getMessage().contains("entity wrong.id cannot be resolved")) throw e;
-        }
-
-        assertEquals(cluster.members as Set, ImmutableSet.of(member));
-    }
-
-    @Test
-    public void testReplaceMemberThrowsIfNotMember() {
-        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
-                .configure("initialSize", 1)
-                .configure("factory", { properties -> return new TestEntityImpl(properties) }));
-
-        cluster.start([loc])
-        Entity member = Iterables.get(cluster.members, 0);
-
-        try {
-            cluster.replaceMember(app.getId());
-            fail();
-        } catch (Exception e) {
-            if (Exceptions.getFirstThrowableOfType(e, NoSuchElementException.class) == null) throw e;
-            if (!Exceptions.getFirstThrowableOfType(e, NoSuchElementException.class).getMessage().contains("is not a member")) throw e;
-        }
-
-        assertEquals(cluster.members as Set, ImmutableSet.of(member));
-    }
-
-    @Test
-    public void testReplaceMemberFailsIfCantProvisionReplacement() {
-        final int failNum = 2
-        final AtomicInteger counter = new AtomicInteger(0)
-        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
-                .configure("factory", { properties -> 
-                    int num = counter.incrementAndGet();
-                    return new FailingEntity(properties, (num==failNum))
-                }));
-
-        cluster.start([loc])
-        Entity member = Iterables.get(cluster.members, 0);
-
-        try {
-            cluster.replaceMember(member.getId());
-            fail();
-        } catch (Exception e) {
-            if (!e.toString().contains("failed to grow")) throw e;
-            if (Exceptions.getFirstThrowableOfType(e, NoSuchElementException.class) != null) throw e;
-        }
-        assertEquals(cluster.members as Set, ImmutableSet.of(member));
-    }
-
-    @Test
-    public void testReplaceMemberRemovesAndThowsIfFailToStopOld() {
-        final int failNum = 1
-        final AtomicInteger counter = new AtomicInteger(0)
-        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
-                .configure("initialSize", 1)
-                .configure("factory", { properties ->
-                    int num = counter.incrementAndGet();
-                    return new FailingEntity(properties, false, (num==failNum), IllegalStateException.class)
-                }));
-
-        cluster.start([loc])
-        Entity member = Iterables.get(cluster.members, 0);
-
-        try {
-            cluster.replaceMember(member.getId());
-            fail();
-        } catch (Exception e) {
-            if (Exceptions.getFirstThrowableOfType(e, StopFailedRuntimeException.class) == null) throw e;
-            boolean found = false;
-            for (Throwable t : Throwables.getCausalChain(e)) {
-                if (t.toString().contains("Simulating entity stop failure")) {
-                    found = true;
-                    break;
-                }
-            }
-            if (!found) throw e;
-        }
-        assertFalse(Entities.isManaged(member));
-        assertEquals(cluster.members.size(), 1);
-    }
-
-    private Throwable unwrapException(Throwable e) {
-        if (e instanceof ExecutionException) {
-            return unwrapException(e.cause)
-        } else if (e instanceof org.codehaus.groovy.runtime.InvokerInvocationException) {
-            return unwrapException(e.cause)
-        } else {
-            return e
-        }
-    }
-}
-
-class FailingEntity extends TestEntityImpl {
-    final boolean failOnStart;
-    final boolean failOnStop;
-    final Class<? extends Exception> exceptionClazz;
-
-    public FailingEntity(Map flags, boolean failOnStart) {
-        this(flags, failOnStart, false);
-    }
-    
-    public FailingEntity(Map flags, boolean failOnStart, boolean failOnStop) {
-        this(flags, failOnStart, failOnStop, IllegalStateException.class);
-    }
-    
-    public FailingEntity(Map flags, boolean failOnStart, boolean failOnStop, Class<? extends Exception> exceptionClazz) {
-        super(flags)
-        this.failOnStart = failOnStart;
-        this.failOnStop = failOnStop;
-        this.exceptionClazz = exceptionClazz;
-    }
-    
-    @Override
-    public void start(Collection<? extends Location> locs) {
-        if (failOnStart) {
-            Exception e = exceptionClazz.getConstructor(String.class).newInstance("Simulating entity start failure for test");
-            throw e;
-        }
-    }
-    
-    @Override
-    public void stop() {
-        if (failOnStop) {
-            Exception e = exceptionClazz.getConstructor(String.class).newInstance("Simulating entity stop failure for test");
-            throw e;
-        }
-    }
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/d52e7ed2/core/src/test/java/brooklyn/entity/group/DynamicClusterTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/brooklyn/entity/group/DynamicClusterTest.java b/core/src/test/java/brooklyn/entity/group/DynamicClusterTest.java
new file mode 100644
index 0000000..9fb9230
--- /dev/null
+++ b/core/src/test/java/brooklyn/entity/group/DynamicClusterTest.java
@@ -0,0 +1,815 @@
+package brooklyn.entity.group;
+
+import static org.testng.Assert.assertEquals;
+import static org.testng.Assert.assertFalse;
+import static org.testng.Assert.assertNotNull;
+import static org.testng.Assert.assertTrue;
+import static org.testng.Assert.fail;
+
+import java.util.Collection;
+import java.util.List;
+import java.util.Map;
+import java.util.NoSuchElementException;
+import java.util.Random;
+import java.util.Set;
+import java.util.concurrent.CopyOnWriteArrayList;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.concurrent.atomic.AtomicReference;
+
+import org.testng.annotations.AfterMethod;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.Test;
+
+import brooklyn.entity.Entity;
+import brooklyn.entity.basic.ApplicationBuilder;
+import brooklyn.entity.basic.Attributes;
+import brooklyn.entity.basic.BrooklynTaskTags;
+import brooklyn.entity.basic.Entities;
+import brooklyn.entity.basic.EntityFactory;
+import brooklyn.entity.basic.Lifecycle;
+import brooklyn.entity.proxying.EntitySpec;
+import brooklyn.entity.trait.Changeable;
+import brooklyn.location.Location;
+import brooklyn.location.basic.SimulatedLocation;
+import brooklyn.management.Task;
+import brooklyn.test.Asserts;
+import brooklyn.test.entity.TestApplication;
+import brooklyn.test.entity.TestEntity;
+import brooklyn.test.entity.TestEntityImpl;
+import brooklyn.util.collections.MutableMap;
+import brooklyn.util.exceptions.Exceptions;
+import brooklyn.util.time.Time;
+
+import com.google.common.base.Function;
+import com.google.common.base.Predicates;
+import com.google.common.base.Throwables;
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.ImmutableSet;
+import com.google.common.collect.Iterables;
+import com.google.common.collect.Lists;
+import com.google.common.util.concurrent.Atomics;
+
+
+public class DynamicClusterTest {
+
+    private static final int TIMEOUT_MS = 2000;
+
+    TestApplication app;
+    SimulatedLocation loc;
+    SimulatedLocation loc2;
+    Random random = new Random();
+
+    @BeforeMethod
+    public void setUp() {
+        app = ApplicationBuilder.newManagedApp(TestApplication.class);
+        loc = new SimulatedLocation();
+        loc2 = new SimulatedLocation();
+    }
+
+    @AfterMethod(alwaysRun = true)
+    public void tearDown(){
+        if (app != null) Entities.destroyAll(app.getManagementContext());
+    }
+
+    @Test
+    public void creationOkayWithoutNewEntityFactoryArgument() throws Exception {
+        app.createAndManageChild(EntitySpec.create(DynamicCluster.class));
+    }
+
+    @Test
+    public void constructionRequiresThatNewEntityArgumentIsAnEntityFactory() throws Exception {
+        try {
+            app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
+                    .configure("factory", "error"));
+            fail();
+        } catch (Exception e) {
+            if (Exceptions.getFirstThrowableOfType(e, IllegalArgumentException.class) == null) throw e;
+        }
+    }
+
+    @Test
+    public void startRequiresThatNewEntityArgumentIsGiven() throws Exception {
+        DynamicCluster c = app.createAndManageChild(EntitySpec.create(DynamicCluster.class));
+        try {
+            c.start(ImmutableList.of(loc));
+            fail();
+        } catch (Exception e) {
+            if (Exceptions.getFirstThrowableOfType(e, IllegalStateException.class) == null) throw e;
+        }
+    }
+
+    @Test
+    public void startMethodFailsIfLocationsParameterHasMoreThanOneElement() throws Exception {
+        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
+                .configure(DynamicCluster.MEMBER_SPEC, EntitySpec.create(TestEntity.class)));
+        try {
+            cluster.start(ImmutableList.of(loc, loc2));
+            fail();
+        } catch (Exception e) {
+            if (Exceptions.getFirstThrowableOfType(e, IllegalArgumentException.class) == null) throw e;
+        }
+    }
+
+    @Test
+    public void testClusterHasOneLocationAfterStarting() throws Exception {
+        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
+                .configure(DynamicCluster.MEMBER_SPEC, EntitySpec.create(TestEntity.class)));
+        cluster.start(ImmutableList.of(loc));
+        assertEquals(cluster.getLocations().size(), 1);
+        assertEquals(ImmutableList.copyOf(cluster.getLocations()), ImmutableList.of(loc));
+    }
+
+    @Test
+    public void testServiceUpAfterStartingWithNoMembers() throws Exception {
+        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
+                .configure(DynamicCluster.MEMBER_SPEC, EntitySpec.create(TestEntity.class))
+                .configure(DynamicCluster.INITIAL_SIZE, 0));
+        cluster.start(ImmutableList.of(loc));
+        assertEquals(cluster.getAttribute(Attributes.SERVICE_STATE), Lifecycle.RUNNING);
+        assertTrue(cluster.getAttribute(Attributes.SERVICE_UP));
+    }
+
+    @Test
+    public void usingEntitySpecResizeFromZeroToOneStartsANewEntityAndSetsItsParent() throws Exception {
+        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
+                .configure("memberSpec", EntitySpec.create(TestEntity.class)));
+        
+        cluster.start(ImmutableList.of(loc));
+
+        cluster.resize(1);
+        TestEntity entity = (TestEntity) Iterables.getOnlyElement(cluster.getMembers());
+        assertEquals(entity.getCount(), 1);
+        assertEquals(entity.getParent(), cluster);
+        assertEquals(entity.getApplication(), app);
+    }
+
+    @Test
+    public void resizeFromZeroToOneStartsANewEntityAndSetsItsParent() throws Exception {
+        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
+                .configure("factory", new EntityFactory() {
+                    @Override public Entity newEntity(Map flags, Entity parent) {
+                        return new TestEntityImpl(flags);
+                    }}));
+
+        cluster.start(ImmutableList.of(loc));
+
+        cluster.resize(1);
+        TestEntity entity = (TestEntity) Iterables.get(cluster.getMembers(), 0);
+        assertEquals(entity.getCounter().get(), 1);
+        assertEquals(entity.getParent(), cluster);
+        assertEquals(entity.getApplication(), app);
+    }
+
+    @Test
+    public void currentSizePropertyReflectsActualClusterSize() throws Exception {
+        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
+                .configure("factory", new EntityFactory() {
+                    @Override public Entity newEntity(Map flags, Entity parent) {
+                        return new TestEntityImpl(flags);
+                    }}));
+
+
+        assertEquals(cluster.getCurrentSize(), (Integer)0);
+
+        cluster.start(ImmutableList.of(loc));
+        assertEquals(cluster.getCurrentSize(), (Integer)1);
+        assertEquals(cluster.getAttribute(Changeable.GROUP_SIZE), (Integer)1);
+
+        int newSize = cluster.resize(0);
+        assertEquals(newSize, 0);
+        assertEquals((Integer)newSize, cluster.getCurrentSize());
+        assertEquals(newSize, cluster.getMembers().size());
+        assertEquals((Integer)newSize, cluster.getAttribute(Changeable.GROUP_SIZE));
+
+        newSize = cluster.resize(4);
+        assertEquals(newSize, 4);
+        assertEquals((Integer)newSize, cluster.getCurrentSize());
+        assertEquals(newSize, cluster.getMembers().size());
+        assertEquals((Integer)newSize, cluster.getAttribute(Changeable.GROUP_SIZE));
+
+        newSize = cluster.resize(0);
+        assertEquals(newSize, 0);
+        assertEquals((Integer)newSize, cluster.getCurrentSize());
+        assertEquals(newSize, cluster.getMembers().size());
+        assertEquals((Integer)newSize, cluster.getAttribute(Changeable.GROUP_SIZE));
+    }
+
+    @Test
+    public void clusterSizeAfterStartIsInitialSize() throws Exception {
+        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
+                .configure("factory", new EntityFactory() {
+                    @Override public Entity newEntity(Map flags, Entity parent) {
+                        return new TestEntityImpl(flags);
+                    }})
+                .configure("initialSize", 2));
+
+        cluster.start(ImmutableList.of(loc));
+        assertEquals(cluster.getCurrentSize(), (Integer)2);
+        assertEquals(cluster.getMembers().size(), 2);
+        assertEquals(cluster.getAttribute(Changeable.GROUP_SIZE), (Integer)2);
+    }
+
+    @Test
+    public void clusterLocationIsPassedOnToEntityStart() throws Exception {
+        List<SimulatedLocation> locations = ImmutableList.of(loc);
+        final AtomicReference<Collection<? extends Location>> stashedLocations = Atomics.newReference();
+        
+        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
+                .configure("factory", new EntityFactory() {
+                    @Override public Entity newEntity(Map flags, Entity parent) {
+                        return new TestEntityImpl(parent) {
+                            @Override
+                            public void start(Collection<? extends Location> loc) {
+                                super.start(loc);
+                                stashedLocations.set(loc);
+                            }
+                        };
+                    }})
+                .configure("initialSize", 1));
+
+        cluster.start(locations);
+        TestEntity entity = (TestEntity) Iterables.get(cluster.getMembers(), 0);
+        
+        assertNotNull(stashedLocations.get());
+        assertEquals(stashedLocations.get().size(), 1);
+        assertEquals(ImmutableList.copyOf(stashedLocations.get()), locations);
+    }
+
+    @Test
+    public void resizeFromOneToZeroChangesClusterSize() throws Exception {
+        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
+                .configure("factory", new EntityFactory() {
+                    @Override public Entity newEntity(Map flags, Entity parent) {
+                        return new TestEntityImpl(flags);
+                    }})
+                .configure("initialSize", 1));
+
+        cluster.start(ImmutableList.of(loc));
+        TestEntity entity = (TestEntity) Iterables.get(cluster.getMembers(), 0);
+        assertEquals(cluster.getCurrentSize(), (Integer)1);
+        assertEquals(entity.getCounter().get(), 1);
+        
+        cluster.resize(0);
+        assertEquals(cluster.getCurrentSize(), (Integer)0);
+        assertEquals(entity.getCounter().get(), 0);
+    }
+
+    @Test
+    public void concurrentResizesToSameNumberCreatesCorrectNumberOfNodes() throws Exception {
+        final int OVERHEAD_MS = 500;
+        final int STARTUP_TIME_MS = 50;
+        final AtomicInteger numStarted = new AtomicInteger(0);
+        final DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
+                .configure("factory", new EntityFactory() {
+                    @Override public Entity newEntity(Map flags, Entity parent) {
+                        Time.sleep(STARTUP_TIME_MS);
+                        numStarted.incrementAndGet();
+                        return new TestEntityImpl(flags, parent);
+                    }}));
+
+        assertEquals(cluster.getCurrentSize(), (Integer)0);
+        cluster.start(ImmutableList.of(loc));
+
+        ExecutorService executor = Executors.newCachedThreadPool();
+        final List<Throwable> throwables = new CopyOnWriteArrayList<Throwable>();
+
+        try {
+            for (int i = 0; i < 10; i++) {
+                executor.submit(new Runnable() {
+                    public void run() {
+                        try {
+                            cluster.resize(2);
+                        } catch (Throwable e) {
+                            throwables.add(e);
+                        }
+                    }});
+            }
+
+            executor.shutdown();
+            assertTrue(executor.awaitTermination(10*STARTUP_TIME_MS+OVERHEAD_MS, TimeUnit.MILLISECONDS));
+            if (throwables.size() > 0) throw Exceptions.propagate(throwables.get(0));
+            assertEquals(cluster.getCurrentSize(), (Integer)2);
+            assertEquals(cluster.getAttribute(Changeable.GROUP_SIZE), (Integer)2);
+            assertEquals(numStarted.get(), 2);
+        } finally {
+            executor.shutdownNow();
+        }
+    }
+
+    @Test(enabled = false)
+    public void stoppingTheClusterStopsTheEntity() throws Exception {
+        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
+                .configure("factory", new EntityFactory() {
+                    @Override public Entity newEntity(Map flags, Entity parent) {
+                        return new TestEntityImpl(flags);
+                    }})
+                .configure("initialSize", 1));
+
+        cluster.start(ImmutableList.of(loc));
+        TestEntity entity = (TestEntity) Iterables.get(cluster.getMembers(), 0);
+        
+        assertEquals(entity.getCounter().get(), 1);
+        cluster.stop();
+        assertEquals(entity.getCounter().get(), 0);
+    }
+
+    /**
+     * This tests the fix for ENGR-1826.
+     */
+    @Test
+    public void failingEntitiesDontBreakClusterActions() throws Exception {
+        final int failNum = 2;
+        final AtomicInteger counter = new AtomicInteger(0);
+        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
+                .configure("initialSize", 0)
+                .configure("factory", new EntityFactory() {
+                    @Override public Entity newEntity(Map flags, Entity parent) {
+                        int num = counter.incrementAndGet();
+                        return new FailingEntity(flags, (num==failNum));
+                    }}));
+
+        cluster.start(ImmutableList.of(loc));
+        cluster.resize(3);
+        assertEquals(cluster.getCurrentSize(), (Integer)2);
+        assertEquals(cluster.getMembers().size(), 2);
+        for (Entity member : cluster.getMembers()) {
+            assertFalse(((FailingEntity)member).failOnStart);
+        }
+    }
+
+    @Test
+    public void testInitialQuorumSizeSufficientForStartup() throws Exception {
+        final int failNum = 1;
+        final AtomicInteger counter = new AtomicInteger(0);
+        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
+                .configure("initialSize", 2)
+                .configure(DynamicCluster.INITIAL_QUORUM_SIZE, 1)
+                .configure("factory", new EntityFactory() {
+                    @Override public Entity newEntity(Map flags, Entity parent) {
+                        int num = counter.incrementAndGet();
+                        return new FailingEntity(flags, (num==failNum));
+                    }}));
+
+        cluster.start(ImmutableList.of(loc));
+        
+        // note that children include quarantine group; and quarantined nodes
+        assertEquals(cluster.getCurrentSize(), (Integer)1);
+        assertEquals(cluster.getMembers().size(), 1);
+        for (Entity member : cluster.getMembers()) {
+            assertFalse(((FailingEntity)member).failOnStart);
+        }
+    }
+
+    @Test
+    public void testInitialQuorumSizeDefaultsToInitialSize() throws Exception {
+        final int failNum = 1;
+        final AtomicInteger counter = new AtomicInteger(0);
+        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
+                .configure("initialSize", 2)
+                .configure("factory", new EntityFactory() {
+                    @Override public Entity newEntity(Map flags, Entity parent) {
+                        int num = counter.incrementAndGet();
+                        return new FailingEntity(flags, (num==failNum));
+                    }}));
+
+        try {
+            cluster.start(ImmutableList.of(loc));
+        } catch (Exception e) {
+            IllegalStateException unwrapped = Exceptions.getFirstThrowableOfType(e, IllegalStateException.class);
+            if (unwrapped != null && unwrapped.getMessage().contains("failed to get to initial size")) {
+                // success
+            } else {
+                throw e; // fail
+            }
+        }
+        
+        // note that children include quarantine group; and quarantined nodes
+        assertEquals(cluster.getCurrentSize(), (Integer)1);
+        assertEquals(cluster.getMembers().size(), 1);
+        for (Entity member : cluster.getMembers()) {
+            assertFalse(((FailingEntity)member).failOnStart);
+        }
+    }
+
+    @Test
+    public void testCanQuarantineFailedEntities() throws Exception {
+        final int failNum = 2;
+        final AtomicInteger counter = new AtomicInteger(0);
+        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
+                .configure("quarantineFailedEntities", true)
+                .configure("initialSize", 0)
+                .configure("factory", new EntityFactory() {
+                    @Override public Entity newEntity(Map flags, Entity parent) {
+                        int num = counter.incrementAndGet();
+                        return new FailingEntity(flags, (num==failNum));
+                    }}));
+
+        cluster.start(ImmutableList.of(loc));
+        cluster.resize(3);
+        assertEquals(cluster.getCurrentSize(), (Integer)2);
+        assertEquals(cluster.getMembers().size(), 2);
+        assertEquals(Iterables.size(Iterables.filter(cluster.getChildren(), Predicates.instanceOf(FailingEntity.class))), 3);
+        for (Entity it : cluster.getMembers()) {
+            assertFalse(((FailingEntity)it).failOnStart);
+        }
+
+        assertEquals(cluster.getAttribute(DynamicCluster.QUARANTINE_GROUP).getMembers().size(), 1);
+        for (Entity it : cluster.getAttribute(DynamicCluster.QUARANTINE_GROUP).getMembers()) {
+            assertTrue(((FailingEntity)it).failOnStart);
+        }
+    }
+
+    @Test
+    public void testDoNotQuarantineFailedEntities() throws Exception {
+        final int failNum = 2;
+        final AtomicInteger counter = new AtomicInteger(0);
+        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
+                // default is quarantineFailedEntities==true
+                .configure("quarantineFailedEntities", false)
+                .configure("initialSize", 0)
+                .configure("factory", new EntityFactory() {
+                    @Override public Entity newEntity(Map flags, Entity parent) {
+                        int num = counter.incrementAndGet();
+                        return new FailingEntity(flags, (num==failNum));
+                    }}));
+
+        cluster.start(ImmutableList.of(loc));
+        
+        // no quarantine group, as a child
+        assertEquals(cluster.getChildren().size(), 0, "children="+cluster.getChildren());
+        
+        // Failed node will not be a member or child
+        cluster.resize(3);
+        assertEquals(cluster.getCurrentSize(), (Integer)2);
+        assertEquals(cluster.getMembers().size(), 2);
+        assertEquals(cluster.getChildren().size(), 2, "children="+cluster.getChildren());
+        
+        // Failed node will not be managed either
+        assertEquals(Iterables.size(Iterables.filter(cluster.getChildren(), Predicates.instanceOf(FailingEntity.class))), 2);
+        for (Entity member : cluster.getMembers()) {
+            assertFalse(((FailingEntity)member).failOnStart);
+        }
+    }
+
+    @Test
+    public void defaultRemovalStrategyShutsDownNewestFirstWhenResizing() throws Exception {
+        TestEntity entity;
+        final int failNum = 2;
+        final List<Entity> creationOrder = Lists.newArrayList();
+        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
+                .configure("initialSize", 0)
+                .configure("factory", new EntityFactory() {
+                    @Override public Entity newEntity(Map flags, Entity parent) {
+                        Entity result = new TestEntityImpl(flags);
+                        creationOrder.add(result);
+                        return result;
+                    }}));
+
+        cluster.start(ImmutableList.of(loc));
+        cluster.resize(1);
+        cluster.resize(2);
+        assertEquals(cluster.getCurrentSize(), (Integer)2);
+        assertEquals(ImmutableSet.copyOf(cluster.getMembers()), ImmutableSet.copyOf(creationOrder), "actual="+cluster.getMembers());
+
+        // Now stop one
+        cluster.resize(1);
+        assertEquals(cluster.getCurrentSize(), (Integer)1);
+        assertEquals(ImmutableList.copyOf(cluster.getMembers()), creationOrder.subList(0, 1));
+    }
+
+    @Test
+    public void resizeLoggedAsEffectorCall() throws Exception {
+        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
+                .configure("factory", new EntityFactory() {
+                    @Override public Entity newEntity(Map flags, Entity parent) {
+                        return new TestEntityImpl(flags);
+                    }}));
+
+        app.start(ImmutableList.of(loc));
+        cluster.resize(1);
+
+        Set<Task<?>> tasks = app.getManagementContext().getExecutionManager().getTasksWithAllTags(ImmutableList.of(
+            BrooklynTaskTags.tagForContextEntity(cluster),"EFFECTOR"));
+        assertEquals(tasks.size(), 2);
+        assertTrue(Iterables.get(tasks, 0).getDescription().contains("start"));
+        assertTrue(Iterables.get(tasks, 1).getDescription().contains("resize"));
+    }
+
+    @Test
+    public void testStoppedChildIsRemoveFromGroup() throws Exception {
+        final DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
+                .configure("initialSize", 1)
+                .configure("factory", new EntityFactory() {
+                    @Override public Entity newEntity(Map flags, Entity parent) {
+                        return new TestEntityImpl(flags);
+                    }}));
+
+        cluster.start(ImmutableList.of(loc));
+
+        final TestEntity child = (TestEntity) Iterables.get(cluster.getMembers(), 0);
+        child.stop();
+        Entities.unmanage(child);
+
+        Asserts.succeedsEventually(MutableMap.of("timeout", TIMEOUT_MS), new Runnable() {
+            @Override public void run() {
+                assertFalse(cluster.getChildren().contains(child), "children="+cluster.getChildren());
+                assertEquals(cluster.getCurrentSize(), (Integer)0);
+                assertEquals(cluster.getMembers().size(), 0);
+            }});
+    }
+
+    @Test
+    public void testPluggableRemovalStrategyIsUsed() throws Exception {
+        final List<Entity> removedEntities = Lists.newArrayList();
+
+        Function<Collection<Entity>, Entity> removalStrategy = new Function<Collection<Entity>, Entity>() {
+            @Override public Entity apply(Collection<Entity> contenders) {
+                Entity choice = Iterables.get(contenders, random.nextInt(contenders.size()));
+                removedEntities.add(choice);
+                return choice;
+            }
+        };
+
+        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
+                .configure("factory", new EntityFactory() {
+                    @Override public Entity newEntity(Map flags, Entity parent) {
+                        return new TestEntityImpl(flags);
+                    }})
+                .configure("initialSize", 10)
+                .configure("removalStrategy", removalStrategy));
+
+        cluster.start(ImmutableList.of(loc));
+        Set origMembers = ImmutableSet.copyOf(cluster.getMembers());
+
+        for (int i = 10; i >= 0; i--) {
+            cluster.resize(i);
+            assertEquals(cluster.getAttribute(Changeable.GROUP_SIZE), (Integer)i);
+            assertEquals(removedEntities.size(), 10-i);
+            assertEquals(ImmutableSet.copyOf(Iterables.concat(cluster.getMembers(), removedEntities)), origMembers);
+        }
+    }
+
+    @Test
+    public void testPluggableRemovalStrategyCanBeSetAfterConstruction() throws Exception {
+        final List<Entity> removedEntities = Lists.newArrayList();
+
+        Function<Collection<Entity>, Entity> removalStrategy = new Function<Collection<Entity>, Entity>() {
+            @Override public Entity apply(Collection<Entity> contenders) {
+                Entity choice = Iterables.get(contenders, random.nextInt(contenders.size()));
+                removedEntities.add(choice);
+                return choice;
+            }
+        };
+        
+        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
+                .configure("factory", new EntityFactory() {
+                    @Override public Entity newEntity(Map flags, Entity parent) {
+                        return new TestEntityImpl(flags);
+                    }})
+                .configure("initialSize", 10));
+
+        cluster.start(ImmutableList.of(loc));
+        Set origMembers = ImmutableSet.copyOf(cluster.getMembers());
+
+        cluster.setRemovalStrategy(removalStrategy);
+
+        for (int i = 10; i >= 0; i--) {
+            cluster.resize(i);
+            assertEquals(cluster.getAttribute(Changeable.GROUP_SIZE), (Integer)i);
+            assertEquals(removedEntities.size(), 10-i);
+            assertEquals(ImmutableSet.copyOf(Iterables.concat(cluster.getMembers(), removedEntities)), origMembers);
+        }
+    }
+
+    @Test
+    public void testResizeDoesNotBlockCallsToQueryGroupMembership() throws Exception {
+        final CountDownLatch executingLatch = new CountDownLatch(1);
+        final CountDownLatch continuationLatch = new CountDownLatch(1);
+        
+        final DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
+                .configure("initialSize", 0)
+                .configure("factory", new EntityFactory() {
+                    @Override public Entity newEntity(Map flags, Entity parent) {
+                        try {
+                            executingLatch.countDown();
+                            continuationLatch.await();
+                            return new TestEntityImpl(flags);
+                        } catch (InterruptedException e) {
+                            throw Exceptions.propagate(e);
+                        }
+                    }}));
+
+        cluster.start(ImmutableList.of(loc));
+
+        Thread thread = new Thread(new Runnable() {
+                @Override public void run() {
+                    cluster.resize(1);
+                }});
+        
+        try {
+            // wait for resize to be executing
+            thread.start();
+            executingLatch.await(TIMEOUT_MS, TimeUnit.MILLISECONDS);
+
+            // ensure can still call methods on group, to query/update membership
+            assertEquals(ImmutableList.copyOf(cluster.getMembers()), ImmutableList.of());
+            assertEquals(cluster.getCurrentSize(), (Integer)0);
+            assertFalse(cluster.hasMember(cluster));
+            cluster.addMember(cluster);
+            assertTrue(cluster.removeMember(cluster));
+
+            // allow the resize to complete
+            continuationLatch.countDown();
+            thread.join(TIMEOUT_MS);
+            assertFalse(thread.isAlive());
+        } finally {
+            thread.interrupt();
+        }
+    }
+
+    @Test
+    public void testReplacesMember() throws Exception {
+        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
+                .configure("initialSize", 1)
+                .configure("factory", new EntityFactory() {
+                    @Override public Entity newEntity(Map flags, Entity parent) {
+                        return new TestEntityImpl(flags);
+                    }}));
+
+        cluster.start(ImmutableList.of(loc));
+        Entity member = Iterables.get(cluster.getMembers(), 0);
+
+        String replacementId = cluster.replaceMember(member.getId());
+        Entity replacement = app.getManagementContext().getEntityManager().getEntity(replacementId);
+
+        assertEquals(cluster.getMembers().size(), 1);
+        assertFalse(cluster.getMembers().contains(member));
+        assertFalse(cluster.getChildren().contains(member));
+        assertNotNull(replacement, "replacementId="+replacementId);
+        assertTrue(cluster.getMembers().contains(replacement), "replacement="+replacement+"; members="+cluster.getMembers());
+        assertTrue(cluster.getChildren().contains(replacement), "replacement="+replacement+"; children="+cluster.getChildren());
+    }
+
+    @Test
+    public void testReplaceMemberThrowsIfMemberIdDoesNotResolve() throws Exception {
+        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
+                .configure("initialSize", 1)
+                .configure("factory", new EntityFactory() {
+                    @Override public Entity newEntity(Map flags, Entity parent) {
+                        return new TestEntityImpl(flags);
+                    }}));
+
+        cluster.start(ImmutableList.of(loc));
+        Entity member = Iterables.get(cluster.getMembers(), 0);
+
+        try {
+            cluster.replaceMember("wrong.id");
+            fail();
+        } catch (Exception e) {
+            if (Exceptions.getFirstThrowableOfType(e, NoSuchElementException.class) == null) throw e;
+            if (!Exceptions.getFirstThrowableOfType(e, NoSuchElementException.class).getMessage().contains("entity wrong.id cannot be resolved")) throw e;
+        }
+
+        assertEquals(ImmutableSet.copyOf(cluster.getMembers()), ImmutableSet.of(member));
+    }
+
+    @Test
+    public void testReplaceMemberThrowsIfNotMember() throws Exception {
+        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
+                .configure("initialSize", 1)
+                .configure("factory", new EntityFactory() {
+                    @Override public Entity newEntity(Map flags, Entity parent) {
+                        return new TestEntityImpl(flags);
+                    }}));
+
+        cluster.start(ImmutableList.of(loc));
+        Entity member = Iterables.get(cluster.getMembers(), 0);
+
+        try {
+            cluster.replaceMember(app.getId());
+            fail();
+        } catch (Exception e) {
+            if (Exceptions.getFirstThrowableOfType(e, NoSuchElementException.class) == null) throw e;
+            if (!Exceptions.getFirstThrowableOfType(e, NoSuchElementException.class).getMessage().contains("is not a member")) throw e;
+        }
+
+        assertEquals(ImmutableSet.copyOf(cluster.getMembers()), ImmutableSet.of(member));
+    }
+
+    @Test
+    public void testReplaceMemberFailsIfCantProvisionReplacement() throws Exception {
+        final int failNum = 2;
+        final AtomicInteger counter = new AtomicInteger(0);
+        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
+                .configure("factory", new EntityFactory() {
+                    @Override public Entity newEntity(Map flags, Entity parent) {
+                        int num = counter.incrementAndGet();
+                        return new FailingEntity(flags, (num==failNum));
+                    }}));
+
+        cluster.start(ImmutableList.of(loc));
+        Entity member = Iterables.get(cluster.getMembers(), 0);
+
+        try {
+            cluster.replaceMember(member.getId());
+            fail();
+        } catch (Exception e) {
+            if (!e.toString().contains("failed to grow")) throw e;
+            if (Exceptions.getFirstThrowableOfType(e, NoSuchElementException.class) != null) throw e;
+        }
+        assertEquals(ImmutableSet.copyOf(cluster.getMembers()), ImmutableSet.of(member));
+    }
+
+    @Test
+    public void testReplaceMemberRemovesAndThowsIfFailToStopOld() throws Exception {
+        final int failNum = 1;
+        final AtomicInteger counter = new AtomicInteger(0);
+        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
+                .configure("initialSize", 1)
+                .configure("factory", new EntityFactory() {
+                    @Override public Entity newEntity(Map flags, Entity parent) {
+                        int num = counter.incrementAndGet();
+                        return new FailingEntity(flags, false, (num==failNum), IllegalStateException.class);
+                    }}));
+
+        cluster.start(ImmutableList.of(loc));
+        Entity member = Iterables.get(cluster.getMembers(), 0);
+
+        try {
+            cluster.replaceMember(member.getId());
+            fail();
+        } catch (Exception e) {
+            if (Exceptions.getFirstThrowableOfType(e, StopFailedRuntimeException.class) == null) throw e;
+            boolean found = false;
+            for (Throwable t : Throwables.getCausalChain(e)) {
+                if (t.toString().contains("Simulating entity stop failure")) {
+                    found = true;
+                    break;
+                }
+            }
+            if (!found) throw e;
+        }
+        assertFalse(Entities.isManaged(member));
+        assertEquals(cluster.getMembers().size(), 1);
+    }
+
+    private Throwable unwrapException(Throwable e) {
+        if (e instanceof ExecutionException) {
+            return unwrapException(e.getCause());
+        } else if (e instanceof org.codehaus.groovy.runtime.InvokerInvocationException) {
+            return unwrapException(e.getCause());
+        } else {
+            return e;
+        }
+    }
+
+    public static class FailingEntity extends TestEntityImpl {
+        final boolean failOnStart;
+        final boolean failOnStop;
+        final Class<? extends Exception> exceptionClazz;
+    
+        public FailingEntity(Map flags, boolean failOnStart) {
+            this(flags, failOnStart, false);
+        }
+        
+        public FailingEntity(Map flags, boolean failOnStart, boolean failOnStop) {
+            this(flags, failOnStart, failOnStop, IllegalStateException.class);
+        }
+        
+        public FailingEntity(Map flags, boolean failOnStart, boolean failOnStop, Class<? extends Exception> exceptionClazz) {
+            super(flags);
+            this.failOnStart = failOnStart;
+            this.failOnStop = failOnStop;
+            this.exceptionClazz = exceptionClazz;
+        }
+        
+        @Override
+        public void start(Collection<? extends Location> locs) {
+            if (failOnStart) {
+                try {
+                    Exception e = exceptionClazz.getConstructor(String.class).newInstance("Simulating entity start failure for test");
+                    throw e;
+                } catch (Exception e) {
+                    throw Exceptions.propagate(e);
+                }
+            }
+        }
+        
+        @Override
+        public void stop() {
+            if (failOnStop) {
+                try {
+                    Exception e = exceptionClazz.getConstructor(String.class).newInstance("Simulating entity stop failure for test");
+                    throw e;
+                } catch (Exception e) {
+                    throw Exceptions.propagate(e);
+                }
+            }
+        }
+    }
+}
\ No newline at end of file


[26/50] [abbrv] git commit: support OS_FAMILY and OS_VERSION_REGEX for jclouds

Posted by ri...@apache.org.
support OS_FAMILY and OS_VERSION_REGEX for jclouds


Project: http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/commit/37bf67ae
Tree: http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/tree/37bf67ae
Diff: http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/diff/37bf67ae

Branch: refs/pull/1414/merge
Commit: 37bf67ae7f352320a043b28e0e0cf2499108ecee
Parents: f54024f
Author: Alex Heneveld <al...@cloudsoftcorp.com>
Authored: Fri May 23 10:08:07 2014 -0600
Committer: Alex Heneveld <al...@cloudsoftcorp.com>
Committed: Fri May 23 10:08:07 2014 -0600

----------------------------------------------------------------------
 .../brooklyn/location/jclouds/JcloudsLocation.java  | 16 +++++++++++++++-
 .../location/jclouds/JcloudsLocationConfig.java     |  7 ++++++-
 2 files changed, 21 insertions(+), 2 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/37bf67ae/locations/jclouds/src/main/java/brooklyn/location/jclouds/JcloudsLocation.java
----------------------------------------------------------------------
diff --git a/locations/jclouds/src/main/java/brooklyn/location/jclouds/JcloudsLocation.java b/locations/jclouds/src/main/java/brooklyn/location/jclouds/JcloudsLocation.java
index 328baf3..e4c3fce 100644
--- a/locations/jclouds/src/main/java/brooklyn/location/jclouds/JcloudsLocation.java
+++ b/locations/jclouds/src/main/java/brooklyn/location/jclouds/JcloudsLocation.java
@@ -43,6 +43,7 @@ import org.jclouds.compute.domain.Image;
 import org.jclouds.compute.domain.NodeMetadata;
 import org.jclouds.compute.domain.NodeMetadata.Status;
 import org.jclouds.compute.domain.NodeMetadataBuilder;
+import org.jclouds.compute.domain.OsFamily;
 import org.jclouds.compute.domain.Template;
 import org.jclouds.compute.domain.TemplateBuilder;
 import org.jclouds.compute.domain.TemplateBuilderSpec;
@@ -99,8 +100,10 @@ import brooklyn.util.exceptions.CompoundRuntimeException;
 import brooklyn.util.exceptions.Exceptions;
 import brooklyn.util.flags.SetFromFlag;
 import brooklyn.util.flags.TypeCoercions;
+import brooklyn.util.guava.Maybe;
 import brooklyn.util.internal.ssh.ShellTool;
 import brooklyn.util.internal.ssh.SshTool;
+import brooklyn.util.javalang.Enums;
 import brooklyn.util.javalang.Reflections;
 import brooklyn.util.net.Cidr;
 import brooklyn.util.net.Networking;
@@ -851,6 +854,17 @@ public class JcloudsLocation extends AbstractCloudMachineProvisioningLocation im
                     public void apply(TemplateBuilder tb, ConfigBag props, Object v) {
                         tb.imageNameMatches(((CharSequence)v).toString());
                     }})
+            .put(OS_FAMILY, new CustomizeTemplateBuilder() {
+                    public void apply(TemplateBuilder tb, ConfigBag props, Object v) {
+                        Maybe<OsFamily> osFamily = Enums.valueOfIgnoreCase(OsFamily.class, v.toString());
+                        if (osFamily.isAbsent())
+                            throw new IllegalArgumentException("Invalid "+OS_FAMILY+" value "+v);
+                        tb.osFamily(osFamily.get());
+                    }})
+            .put(OS_VERSION_REGEX, new CustomizeTemplateBuilder() {
+                    public void apply(TemplateBuilder tb, ConfigBag props, Object v) {
+                        tb.osVersionMatches( ((CharSequence)v).toString() );
+                    }})
             .put(TEMPLATE_SPEC, new CustomizeTemplateBuilder() {
                 public void apply(TemplateBuilder tb, ConfigBag props, Object v) {
                         tb.from(TemplateBuilderSpec.parse(((CharSequence)v).toString()));
@@ -864,7 +878,7 @@ public class JcloudsLocation extends AbstractCloudMachineProvisioningLocation im
                         /* done in the code, but included here so that it is in the map */
                     }})
             .build();
-   
+    
     /** properties which cause customization of the TemplateOptions */
     public static final Map<ConfigKey<?>,CustomizeTemplateOptions> SUPPORTED_TEMPLATE_OPTIONS_PROPERTIES = ImmutableMap.<ConfigKey<?>,CustomizeTemplateOptions>builder()
             .put(SECURITY_GROUPS, new CustomizeTemplateOptions() {

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/37bf67ae/locations/jclouds/src/main/java/brooklyn/location/jclouds/JcloudsLocationConfig.java
----------------------------------------------------------------------
diff --git a/locations/jclouds/src/main/java/brooklyn/location/jclouds/JcloudsLocationConfig.java b/locations/jclouds/src/main/java/brooklyn/location/jclouds/JcloudsLocationConfig.java
index 49729a1..73db853 100644
--- a/locations/jclouds/src/main/java/brooklyn/location/jclouds/JcloudsLocationConfig.java
+++ b/locations/jclouds/src/main/java/brooklyn/location/jclouds/JcloudsLocationConfig.java
@@ -1,11 +1,11 @@
 package brooklyn.location.jclouds;
 
-import java.io.File;
 import java.util.Collection;
 import java.util.concurrent.Semaphore;
 
 import org.jclouds.Constants;
 import org.jclouds.compute.domain.Image;
+import org.jclouds.compute.domain.OsFamily;
 import org.jclouds.compute.domain.TemplateBuilder;
 import org.jclouds.domain.LoginCredentials;
 
@@ -187,6 +187,11 @@ public interface JcloudsLocationConfig extends CloudLocationConfig {
         "imageChooser", "An image chooser function to control which images are preferred", 
         new BrooklynImageChooser().chooser());
 
+    public static final ConfigKey<OsFamily> OS_FAMILY = ConfigKeys.newConfigKey(OsFamily.class, "osFamily", 
+        "OS family, e.g. CentOS, Debian, RHEL, Ubuntu");
+    public static final ConfigKey<String> OS_VERSION_REGEX = ConfigKeys.newStringConfigKey("osVersionRegex", 
+        "Regular expression for the OS version to load");
+
     // TODO
     
 //  "noDefaultSshKeys" - hints that local ssh keys should not be read as defaults


[23/50] [abbrv] git commit: Fix use of service command with iptables and deprecate old methods

Posted by ri...@apache.org.
Fix use of service command with iptables and deprecate old methods


Project: http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/commit/803f9f13
Tree: http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/tree/803f9f13
Diff: http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/diff/803f9f13

Branch: refs/pull/1411/merge
Commit: 803f9f1397c1ade033e570fdb5ac1d47d811dfeb
Parents: f54024f
Author: Andrew Kennedy <an...@cloudsoftcorp.com>
Authored: Thu May 22 23:11:12 2014 +0100
Committer: Andrew Kennedy <an...@cloudsoftcorp.com>
Committed: Fri May 23 00:14:27 2014 +0100

----------------------------------------------------------------------
 .../location/jclouds/JcloudsLocationConfig.java |  1 +
 .../brooklyn/util/ssh/IptablesCommands.java     | 97 +++++++++++---------
 2 files changed, 54 insertions(+), 44 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/803f9f13/locations/jclouds/src/main/java/brooklyn/location/jclouds/JcloudsLocationConfig.java
----------------------------------------------------------------------
diff --git a/locations/jclouds/src/main/java/brooklyn/location/jclouds/JcloudsLocationConfig.java b/locations/jclouds/src/main/java/brooklyn/location/jclouds/JcloudsLocationConfig.java
index 49729a1..5f4a6ff 100644
--- a/locations/jclouds/src/main/java/brooklyn/location/jclouds/JcloudsLocationConfig.java
+++ b/locations/jclouds/src/main/java/brooklyn/location/jclouds/JcloudsLocationConfig.java
@@ -118,6 +118,7 @@ public interface JcloudsLocationConfig extends CloudLocationConfig {
             "Tags to be applied when creating a VM, on supported clouds " +
             "(either a single tag as a String, or an Iterable<String> or String[];" +
             "note this is not key-value pairs (e.g. what AWS calls 'tags'), for that see userMetadata)", null);
+
     @Deprecated /** @deprecated since 0.7.0 use #STRING_TAGS */
     public static final ConfigKey<Object> TAGS = STRING_TAGS;
 

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/803f9f13/utils/common/src/main/java/brooklyn/util/ssh/IptablesCommands.java
----------------------------------------------------------------------
diff --git a/utils/common/src/main/java/brooklyn/util/ssh/IptablesCommands.java b/utils/common/src/main/java/brooklyn/util/ssh/IptablesCommands.java
index 2fac2a6..6f971a0 100644
--- a/utils/common/src/main/java/brooklyn/util/ssh/IptablesCommands.java
+++ b/utils/common/src/main/java/brooklyn/util/ssh/IptablesCommands.java
@@ -15,9 +15,7 @@ public class IptablesCommands {
         ACCEPT, REJECT, DROP, LOG
     }
 
-    /**
-     * @deprecated since 0.7; use {@link brooklyn.util.net.Protocol}
-     */
+    /*** @deprecated since 0.7; use {@link brooklyn.util.net.Protocol} */
     @Deprecated
     public enum Protocol {
         TCP("tcp"), UDP("udp"), ALL("all");
@@ -32,18 +30,25 @@ public class IptablesCommands {
         public String toString() {
             return protocol;
         }
-        
+
         brooklyn.util.net.Protocol convert() {
             switch (this) {
-                case TCP : return brooklyn.util.net.Protocol.TCP;
-                case UDP : return brooklyn.util.net.Protocol.UDP;
-                case ALL : return brooklyn.util.net.Protocol.ALL;
-                default:   throw new IllegalStateException("Unexpected protocol "+this);
+                case TCP: return brooklyn.util.net.Protocol.TCP;
+                case UDP: return brooklyn.util.net.Protocol.UDP;
+                case ALL: return brooklyn.util.net.Protocol.ALL;
+                default: throw new IllegalStateException("Unexpected protocol "+this);
             }
         }
     }
 
     @Beta // implementation not portable across distros
+    public static String iptablesService(String cmd) {
+        return sudo(BashCommands.alternatives(
+                BashCommands.ifExecutableElse1("service", "service iptables "+cmd),
+                "/sbin/service iptables " + cmd));
+    }
+
+    @Beta // implementation not portable across distros
     public static String iptablesServiceStop() {
         return iptablesService("stop");
     }
@@ -63,32 +68,29 @@ public class IptablesCommands {
         return iptablesService("status");
     }
 
-    @Beta // implementation not portable across distros
-    public static String iptablesService(String cmd) {
-        return sudo("/sbin/service iptables "+cmd);
+    /**
+     * Returns the command that saves on disk iptables rules, to make them resilient to reboot.
+     *
+     * @return Returns the command that saves on disk iptables rules.
+     */
+    public static String saveIptablesRules() {
+        return BashCommands.alternatives(
+                BashCommands.ifExecutableElse1("iptables-save", sudo("iptables-save")),
+                iptablesService("save"));
     }
 
     /**
      * Returns the command that cleans up iptables rules.
-     * 
+     *
      * @return Returns the command that cleans up iptables rules.
      */
     public static String cleanUpIptablesRules() {
        return sudo("/sbin/iptables -F");
     }
-    
-    /**
-     * Returns the command that saves on disk iptables rules, to make them resilient to reboot.
-     * 
-     * @return Returns the command that saves on disk iptables rules.
-     */
-    public static String saveIptablesRules() {
-       return sudo("/sbin/service iptables save");
-    }
-    
+
     /**
      * Returns the iptables rules.
-     * 
+     *
      * @return Returns the command that list all the iptables rules.
      */
     public static String listIptablesRule() {
@@ -97,77 +99,84 @@ public class IptablesCommands {
 
     /**
      * Returns the command that inserts a rule on top of the iptables' rules to all interfaces.
-     * 
+     *
      * @return Returns the command that inserts a rule on top of the iptables'
      *         rules.
      */
     public static String insertIptablesRule(Chain chain, brooklyn.util.net.Protocol protocol, int port, Policy policy) {
         return addIptablesRule("-I", chain, Optional.<String> absent(), protocol, port, policy);
     }
-    
+
+    /** @deprecated since 0.7.0; use {@link #insertIptablesRule(Chain, brooklyn.util.net.Protocol, int, Policy)} */
+    @Deprecated
     public static String insertIptablesRule(Chain chain, Protocol protocol, int port, Policy policy) {
         return insertIptablesRule(chain, protocol.convert(), port, policy);
     }
-    
+
     /**
      * Returns the command that inserts a rule on top of the iptables' rules.
-     * 
+     *
      * @return Returns the command that inserts a rule on top of the iptables'
      *         rules.
      */
     public static String insertIptablesRule(Chain chain, String networkInterface, brooklyn.util.net.Protocol protocol, int port, Policy policy) {
         return addIptablesRule("-I", chain, Optional.of(networkInterface), protocol, port, policy);
     }
-    
+
+    /** @deprecated since 0.7.0; use {@link #insertIptablesRule(Chain, String, brooklyn.util.net.Protocol, int, Policy)} */
+    @Deprecated
     public static String insertIptablesRule(Chain chain, String networkInterface, Protocol protocol, int port, Policy policy) {
         return insertIptablesRule(chain, networkInterface, protocol.convert(), port, policy);
     }
 
     /**
      * Returns the command that appends a rule to iptables to all interfaces.
-     * 
+     *
      * @return Returns the command that appends a rule to iptables.
      */
     public static String appendIptablesRule(Chain chain, brooklyn.util.net.Protocol protocol, int port, Policy policy) {
         return addIptablesRule("-A", chain, Optional.<String> absent(), protocol, port, policy);
     }
-    
+
+    /** @deprecated since 0.7.0; use {@link #appendIptablesRule(Chain, brooklyn.util.net.Protocol, int, Policy)} */
+    @Deprecated
     public static String appendIptablesRule(Chain chain, Protocol protocol, int port, Policy policy) {
         return appendIptablesRule(chain, protocol.convert(), port, policy);
     }
-    
+
     /**
      * Returns the command that appends a rule to iptables.
-     * 
+     *
      * @return Returns the command that appends a rule to iptables.
      */
     public static String appendIptablesRule(Chain chain, String networkInterface, brooklyn.util.net.Protocol protocol, int port, Policy policy) {
         return addIptablesRule("-A", chain, Optional.of(networkInterface), protocol, port, policy);
     }
-    
+
+    /** @deprecated since 0.7.0; use {@link #appendIptablesRule(Chain, String, brooklyn.util.net.Protocol, int, Policy)} */
+    @Deprecated
     public static String appendIptablesRule(Chain chain, String networkInterface, Protocol protocol, int port, Policy policy) {
         return appendIptablesRule(chain, networkInterface, protocol.convert(), port, policy);
     }
 
     /**
      * Returns the command that creates a rule to iptables.
-     * 
-     * @return Returns the command that creates a rule to iptables.
+     *
+     * @return Returns the command that creates a rule for iptables.
      */
-    private static String addIptablesRule(String direction, Chain chain, Optional<String> networkInterface, brooklyn.util.net.Protocol protocol, int port,
-            Policy policy) {
-        String addIptablesRule; 
-        if(networkInterface.isPresent()) {  
+    public static String addIptablesRule(String direction, Chain chain, Optional<String> networkInterface, brooklyn.util.net.Protocol protocol, int port, Policy policy) {
+        String addIptablesRule;
+        if(networkInterface.isPresent()) {
            addIptablesRule = String.format("/sbin/iptables %s %s -i %s -p %s --dport %d -j %s", direction, chain, networkInterface.get(), protocol, port, policy);
         } else {
-           addIptablesRule = String.format("/sbin/iptables %s %s -p %s --dport %d -j %s", direction, chain,
-                 protocol, port, policy);
+           addIptablesRule = String.format("/sbin/iptables %s %s -p %s --dport %d -j %s", direction, chain, protocol, port, policy);
         }
         return sudo(addIptablesRule);
     }
-    
-    private static String addIptablesRule(String direction, Chain chain, Optional<String> networkInterface, Protocol protocol, int port,
-            Policy policy) {
+
+    /** @deprecated since 0.7.0; use {@link #addIptablesRule(String, Chain, Optional, brooklyn.util.net.Protocol, int, Policy)} */
+    @Deprecated
+    public static String addIptablesRule(String direction, Chain chain, Optional<String> networkInterface, Protocol protocol, int port, Policy policy) {
         return addIptablesRule(direction, chain, networkInterface, protocol.convert(), port, policy);
     }
 


[43/50] [abbrv] git commit: add function for converting to string, and use that for the "cpu fraction" sensor

Posted by ri...@apache.org.
add function for converting to string, and use that for the "cpu fraction" sensor


Project: http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/commit/17ac8986
Tree: http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/tree/17ac8986
Diff: http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/diff/17ac8986

Branch: refs/pull/1414/merge
Commit: 17ac89862c4fd89fb35c35a816b9967ab50b455e
Parents: 37bf67a
Author: Alex Heneveld <al...@cloudsoftcorp.com>
Authored: Fri May 23 10:28:04 2014 -0600
Committer: Alex Heneveld <al...@cloudsoftcorp.com>
Committed: Fri May 23 10:28:04 2014 -0600

----------------------------------------------------------------------
 .../java/brooklyn/entity/java/JavaAppUtils.java |  5 ++--
 .../java/brooklyn/util/math/MathFunctions.java  | 24 +++++++++++++++++++-
 .../brooklyn/util/math/MathFunctionsTest.java   | 18 +++++++++++++++
 3 files changed, 43 insertions(+), 4 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/17ac8986/software/base/src/main/java/brooklyn/entity/java/JavaAppUtils.java
----------------------------------------------------------------------
diff --git a/software/base/src/main/java/brooklyn/entity/java/JavaAppUtils.java b/software/base/src/main/java/brooklyn/entity/java/JavaAppUtils.java
index b5bfb31..eb6d2e5 100644
--- a/software/base/src/main/java/brooklyn/entity/java/JavaAppUtils.java
+++ b/software/base/src/main/java/brooklyn/entity/java/JavaAppUtils.java
@@ -216,7 +216,6 @@ public class JavaAppUtils {
     private static final AtomicBoolean initialized = new AtomicBoolean(false);
 
     /** Setup renderer hints for the MXBean attributes. */
-    @SuppressWarnings("rawtypes")
     public static void init() {
         if (initialized.get()) return;
         synchronized (initialized) {
@@ -233,8 +232,8 @@ public class JavaAppUtils {
             RendererHints.register(UsesJavaMXBeans.START_TIME, RendererHints.displayValue(Time.toDateString()));
             RendererHints.register(UsesJavaMXBeans.UP_TIME, RendererHints.displayValue(Duration.millisToStringRounded()));
             RendererHints.register(UsesJavaMXBeans.PROCESS_CPU_TIME, RendererHints.displayValue(Duration.millisToStringRounded()));
-            RendererHints.register(UsesJavaMXBeans.PROCESS_CPU_TIME_FRACTION_LAST, RendererHints.displayValue(Duration.millisToStringRounded()));
-            RendererHints.register(UsesJavaMXBeans.PROCESS_CPU_TIME_FRACTION_IN_WINDOW, RendererHints.displayValue(Duration.millisToStringRounded()));
+            RendererHints.register(UsesJavaMXBeans.PROCESS_CPU_TIME_FRACTION_LAST, RendererHints.displayValue(MathFunctions.percent(4)));
+            RendererHints.register(UsesJavaMXBeans.PROCESS_CPU_TIME_FRACTION_IN_WINDOW, RendererHints.displayValue(MathFunctions.percent(4)));
 
             initialized.set(true);
         }

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/17ac8986/utils/common/src/main/java/brooklyn/util/math/MathFunctions.java
----------------------------------------------------------------------
diff --git a/utils/common/src/main/java/brooklyn/util/math/MathFunctions.java b/utils/common/src/main/java/brooklyn/util/math/MathFunctions.java
index c70cdfc..dbf5604 100644
--- a/utils/common/src/main/java/brooklyn/util/math/MathFunctions.java
+++ b/utils/common/src/main/java/brooklyn/util/math/MathFunctions.java
@@ -2,6 +2,8 @@ package brooklyn.util.math;
 
 import javax.annotation.Nullable;
 
+import brooklyn.util.text.Strings;
+
 import com.google.common.base.Function;
 
 public class MathFunctions {
@@ -61,5 +63,25 @@ public class MathFunctions {
             }
         };
     }
-    
+
+    /** returns a string of up to maxLen length (longer in extreme cases) also capped at significantDigits significantDigits */
+    public static Function<Number, String> readableString(final int significantDigits, final int maxLen) {
+        return new Function<Number, String>() {
+            public String apply(@Nullable Number input) {
+                if (input==null) return null;
+                return Strings.makeRealString(input.doubleValue(), maxLen, significantDigits, 0);
+            }
+        };
+    }
+
+    /** returns a string where the input number is expressed as percent, with given number of significant digits */
+    public static Function<Number, String> percent(final int significantDigits) {
+        return new Function<Number, String>() {
+            public String apply(@Nullable Number input) {
+                if (input==null) return null;
+                return readableString(significantDigits, significantDigits+3).apply(input.doubleValue() * 100d)+"%";
+            }
+        };
+    }
+
 }

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/17ac8986/utils/common/src/test/java/brooklyn/util/math/MathFunctionsTest.java
----------------------------------------------------------------------
diff --git a/utils/common/src/test/java/brooklyn/util/math/MathFunctionsTest.java b/utils/common/src/test/java/brooklyn/util/math/MathFunctionsTest.java
new file mode 100644
index 0000000..6f0955d
--- /dev/null
+++ b/utils/common/src/test/java/brooklyn/util/math/MathFunctionsTest.java
@@ -0,0 +1,18 @@
+package brooklyn.util.math;
+
+import org.testng.Assert;
+import org.testng.annotations.Test;
+
+public class MathFunctionsTest {
+
+    @Test
+    public void testAdd() {
+        Assert.assertEquals(MathFunctions.plus(3).apply(4), (Integer)7);
+        Assert.assertEquals(MathFunctions.plus(0.3).apply(0.4).doubleValue(), 0.7, 0.00000001);
+    }
+    
+    @Test
+    public void testPercent() {
+        Assert.assertEquals(MathFunctions.percent(3).apply(0.0123456), "1.23%");
+    }
+}


[15/50] [abbrv] git commit: Updated following PR review

Posted by ri...@apache.org.
Updated following PR review


Project: http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/commit/6f338897
Tree: http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/tree/6f338897
Diff: http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/diff/6f338897

Branch: refs/pull/1408/merge
Commit: 6f338897b704b1db1b88ec5cd9c1522e39ba2f08
Parents: 238780f
Author: Martin Harris <gi...@nakomis.com>
Authored: Thu May 22 10:47:42 2014 +0100
Committer: Martin Harris <gi...@nakomis.com>
Committed: Thu May 22 10:47:42 2014 +0100

----------------------------------------------------------------------
 .../brooklyn/entity/group/AbstractMembershipTrackingPolicy.java | 5 ++---
 .../src/main/java/brooklyn/util/collections/MutableSet.java     | 3 ---
 2 files changed, 2 insertions(+), 6 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/6f338897/core/src/main/java/brooklyn/entity/group/AbstractMembershipTrackingPolicy.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/brooklyn/entity/group/AbstractMembershipTrackingPolicy.java b/core/src/main/java/brooklyn/entity/group/AbstractMembershipTrackingPolicy.java
index 99fd2b5..049d49c 100644
--- a/core/src/main/java/brooklyn/entity/group/AbstractMembershipTrackingPolicy.java
+++ b/core/src/main/java/brooklyn/entity/group/AbstractMembershipTrackingPolicy.java
@@ -20,7 +20,6 @@ import brooklyn.event.SensorEvent;
 import brooklyn.event.SensorEventListener;
 import brooklyn.policy.basic.AbstractPolicy;
 import brooklyn.util.collections.MutableMap;
-import brooklyn.util.collections.MutableSet;
 
 import com.google.common.base.Objects;
 import com.google.common.base.Preconditions;
@@ -55,10 +54,10 @@ public abstract class AbstractMembershipTrackingPolicy extends AbstractPolicy {
     }
 
     protected Set<Sensor<?>> getSensorsToTrack() {
-        return MutableSet.<Sensor<?>>builder()
+        return ImmutableSet.<Sensor<?>>builder()
                 .addAll(getRequiredConfig(SENSORS_TO_TRACK))
                 .add(Attributes.SERVICE_UP)
-                .buildImmutable();
+                .build();
     }
     
     /**

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/6f338897/utils/common/src/main/java/brooklyn/util/collections/MutableSet.java
----------------------------------------------------------------------
diff --git a/utils/common/src/main/java/brooklyn/util/collections/MutableSet.java b/utils/common/src/main/java/brooklyn/util/collections/MutableSet.java
index 6ab967a..f791949 100644
--- a/utils/common/src/main/java/brooklyn/util/collections/MutableSet.java
+++ b/utils/common/src/main/java/brooklyn/util/collections/MutableSet.java
@@ -111,9 +111,6 @@ public class MutableSet<V> extends LinkedHashSet<V> {
           return new MutableSet<V>(result);
         }
         
-        public ImmutableSet<V> buildImmutable() {
-            return ImmutableSet.copyOf(result);
-        }
     }
     
     public boolean addIfNotNull(V e) {


[10/50] [abbrv] git commit: Deletes nested DynamicClusterTest.FailingEntity

Posted by ri...@apache.org.
Deletes nested DynamicClusterTest.FailingEntity

- use instead brooklyn.entity.trait.FailingEntity


Project: http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/commit/b0e541e4
Tree: http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/tree/b0e541e4
Diff: http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/diff/b0e541e4

Branch: refs/pull/1405/merge
Commit: b0e541e487af240c698e46f314c9a8271e7bc446
Parents: d52e7ed
Author: Aled Sage <al...@gmail.com>
Authored: Wed May 21 12:18:25 2014 +0100
Committer: Aled Sage <al...@gmail.com>
Committed: Wed May 21 15:52:42 2014 +0100

----------------------------------------------------------------------
 .../entity/group/DynamicClusterTest.java        | 101 +++++++------------
 1 file changed, 38 insertions(+), 63 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/b0e541e4/core/src/test/java/brooklyn/entity/group/DynamicClusterTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/brooklyn/entity/group/DynamicClusterTest.java b/core/src/test/java/brooklyn/entity/group/DynamicClusterTest.java
index 9fb9230..a59079d 100644
--- a/core/src/test/java/brooklyn/entity/group/DynamicClusterTest.java
+++ b/core/src/test/java/brooklyn/entity/group/DynamicClusterTest.java
@@ -34,6 +34,7 @@ import brooklyn.entity.basic.EntityFactory;
 import brooklyn.entity.basic.Lifecycle;
 import brooklyn.entity.proxying.EntitySpec;
 import brooklyn.entity.trait.Changeable;
+import brooklyn.entity.trait.FailingEntity;
 import brooklyn.location.Location;
 import brooklyn.location.basic.SimulatedLocation;
 import brooklyn.management.Task;
@@ -330,7 +331,10 @@ public class DynamicClusterTest {
                 .configure("factory", new EntityFactory() {
                     @Override public Entity newEntity(Map flags, Entity parent) {
                         int num = counter.incrementAndGet();
-                        return new FailingEntity(flags, (num==failNum));
+                        return app.getManagementContext().getEntityManager().createEntity(EntitySpec.create(FailingEntity.class)
+                                .configure(flags)
+                                .configure(FailingEntity.FAIL_ON_START, (num==failNum))
+                                .parent(parent));
                     }}));
 
         cluster.start(ImmutableList.of(loc));
@@ -338,7 +342,7 @@ public class DynamicClusterTest {
         assertEquals(cluster.getCurrentSize(), (Integer)2);
         assertEquals(cluster.getMembers().size(), 2);
         for (Entity member : cluster.getMembers()) {
-            assertFalse(((FailingEntity)member).failOnStart);
+            assertFalse(((FailingEntity)member).getConfig(FailingEntity.FAIL_ON_START));
         }
     }
 
@@ -352,7 +356,10 @@ public class DynamicClusterTest {
                 .configure("factory", new EntityFactory() {
                     @Override public Entity newEntity(Map flags, Entity parent) {
                         int num = counter.incrementAndGet();
-                        return new FailingEntity(flags, (num==failNum));
+                        return app.getManagementContext().getEntityManager().createEntity(EntitySpec.create(FailingEntity.class)
+                                .configure(flags)
+                                .configure(FailingEntity.FAIL_ON_START, (num==failNum))
+                                .parent(parent));
                     }}));
 
         cluster.start(ImmutableList.of(loc));
@@ -361,7 +368,7 @@ public class DynamicClusterTest {
         assertEquals(cluster.getCurrentSize(), (Integer)1);
         assertEquals(cluster.getMembers().size(), 1);
         for (Entity member : cluster.getMembers()) {
-            assertFalse(((FailingEntity)member).failOnStart);
+            assertFalse(((FailingEntity)member).getConfig(FailingEntity.FAIL_ON_START));
         }
     }
 
@@ -374,7 +381,10 @@ public class DynamicClusterTest {
                 .configure("factory", new EntityFactory() {
                     @Override public Entity newEntity(Map flags, Entity parent) {
                         int num = counter.incrementAndGet();
-                        return new FailingEntity(flags, (num==failNum));
+                        return app.getManagementContext().getEntityManager().createEntity(EntitySpec.create(FailingEntity.class)
+                                .configure(flags)
+                                .configure(FailingEntity.FAIL_ON_START, (num==failNum))
+                                .parent(parent));
                     }}));
 
         try {
@@ -392,7 +402,7 @@ public class DynamicClusterTest {
         assertEquals(cluster.getCurrentSize(), (Integer)1);
         assertEquals(cluster.getMembers().size(), 1);
         for (Entity member : cluster.getMembers()) {
-            assertFalse(((FailingEntity)member).failOnStart);
+            assertFalse(((FailingEntity)member).getConfig(FailingEntity.FAIL_ON_START));
         }
     }
 
@@ -406,7 +416,10 @@ public class DynamicClusterTest {
                 .configure("factory", new EntityFactory() {
                     @Override public Entity newEntity(Map flags, Entity parent) {
                         int num = counter.incrementAndGet();
-                        return new FailingEntity(flags, (num==failNum));
+                        return app.getManagementContext().getEntityManager().createEntity(EntitySpec.create(FailingEntity.class)
+                                .configure(flags)
+                                .configure(FailingEntity.FAIL_ON_START, (num==failNum))
+                                .parent(parent));
                     }}));
 
         cluster.start(ImmutableList.of(loc));
@@ -414,13 +427,13 @@ public class DynamicClusterTest {
         assertEquals(cluster.getCurrentSize(), (Integer)2);
         assertEquals(cluster.getMembers().size(), 2);
         assertEquals(Iterables.size(Iterables.filter(cluster.getChildren(), Predicates.instanceOf(FailingEntity.class))), 3);
-        for (Entity it : cluster.getMembers()) {
-            assertFalse(((FailingEntity)it).failOnStart);
+        for (Entity member : cluster.getMembers()) {
+            assertFalse(((FailingEntity)member).getConfig(FailingEntity.FAIL_ON_START));
         }
 
         assertEquals(cluster.getAttribute(DynamicCluster.QUARANTINE_GROUP).getMembers().size(), 1);
-        for (Entity it : cluster.getAttribute(DynamicCluster.QUARANTINE_GROUP).getMembers()) {
-            assertTrue(((FailingEntity)it).failOnStart);
+        for (Entity member : cluster.getAttribute(DynamicCluster.QUARANTINE_GROUP).getMembers()) {
+            assertTrue(((FailingEntity)member).getConfig(FailingEntity.FAIL_ON_START));
         }
     }
 
@@ -435,7 +448,10 @@ public class DynamicClusterTest {
                 .configure("factory", new EntityFactory() {
                     @Override public Entity newEntity(Map flags, Entity parent) {
                         int num = counter.incrementAndGet();
-                        return new FailingEntity(flags, (num==failNum));
+                        return app.getManagementContext().getEntityManager().createEntity(EntitySpec.create(FailingEntity.class)
+                                .configure(flags)
+                                .configure(FailingEntity.FAIL_ON_START, (num==failNum))
+                                .parent(parent));
                     }}));
 
         cluster.start(ImmutableList.of(loc));
@@ -452,14 +468,12 @@ public class DynamicClusterTest {
         // Failed node will not be managed either
         assertEquals(Iterables.size(Iterables.filter(cluster.getChildren(), Predicates.instanceOf(FailingEntity.class))), 2);
         for (Entity member : cluster.getMembers()) {
-            assertFalse(((FailingEntity)member).failOnStart);
+            assertFalse(((FailingEntity)member).getConfig(FailingEntity.FAIL_ON_START));
         }
     }
 
     @Test
     public void defaultRemovalStrategyShutsDownNewestFirstWhenResizing() throws Exception {
-        TestEntity entity;
-        final int failNum = 2;
         final List<Entity> creationOrder = Lists.newArrayList();
         DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
                 .configure("initialSize", 0)
@@ -709,7 +723,10 @@ public class DynamicClusterTest {
                 .configure("factory", new EntityFactory() {
                     @Override public Entity newEntity(Map flags, Entity parent) {
                         int num = counter.incrementAndGet();
-                        return new FailingEntity(flags, (num==failNum));
+                        return app.getManagementContext().getEntityManager().createEntity(EntitySpec.create(FailingEntity.class)
+                                .configure(flags)
+                                .configure(FailingEntity.FAIL_ON_START, (num==failNum))
+                                .parent(parent));
                     }}));
 
         cluster.start(ImmutableList.of(loc));
@@ -734,7 +751,10 @@ public class DynamicClusterTest {
                 .configure("factory", new EntityFactory() {
                     @Override public Entity newEntity(Map flags, Entity parent) {
                         int num = counter.incrementAndGet();
-                        return new FailingEntity(flags, false, (num==failNum), IllegalStateException.class);
+                        return app.getManagementContext().getEntityManager().createEntity(EntitySpec.create(FailingEntity.class)
+                                .configure(flags)
+                                .configure(FailingEntity.FAIL_ON_STOP, (num==failNum))
+                                .parent(parent));
                     }}));
 
         cluster.start(ImmutableList.of(loc));
@@ -767,49 +787,4 @@ public class DynamicClusterTest {
             return e;
         }
     }
-
-    public static class FailingEntity extends TestEntityImpl {
-        final boolean failOnStart;
-        final boolean failOnStop;
-        final Class<? extends Exception> exceptionClazz;
-    
-        public FailingEntity(Map flags, boolean failOnStart) {
-            this(flags, failOnStart, false);
-        }
-        
-        public FailingEntity(Map flags, boolean failOnStart, boolean failOnStop) {
-            this(flags, failOnStart, failOnStop, IllegalStateException.class);
-        }
-        
-        public FailingEntity(Map flags, boolean failOnStart, boolean failOnStop, Class<? extends Exception> exceptionClazz) {
-            super(flags);
-            this.failOnStart = failOnStart;
-            this.failOnStop = failOnStop;
-            this.exceptionClazz = exceptionClazz;
-        }
-        
-        @Override
-        public void start(Collection<? extends Location> locs) {
-            if (failOnStart) {
-                try {
-                    Exception e = exceptionClazz.getConstructor(String.class).newInstance("Simulating entity start failure for test");
-                    throw e;
-                } catch (Exception e) {
-                    throw Exceptions.propagate(e);
-                }
-            }
-        }
-        
-        @Override
-        public void stop() {
-            if (failOnStop) {
-                try {
-                    Exception e = exceptionClazz.getConstructor(String.class).newInstance("Simulating entity stop failure for test");
-                    throw e;
-                } catch (Exception e) {
-                    throw Exceptions.propagate(e);
-                }
-            }
-        }
-    }
-}
\ No newline at end of file
+}


[14/50] [abbrv] git commit: Updated following PR review

Posted by ri...@apache.org.
Updated following PR review


Project: http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/commit/6f338897
Tree: http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/tree/6f338897
Diff: http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/diff/6f338897

Branch: refs/pull/1410/merge
Commit: 6f338897b704b1db1b88ec5cd9c1522e39ba2f08
Parents: 238780f
Author: Martin Harris <gi...@nakomis.com>
Authored: Thu May 22 10:47:42 2014 +0100
Committer: Martin Harris <gi...@nakomis.com>
Committed: Thu May 22 10:47:42 2014 +0100

----------------------------------------------------------------------
 .../brooklyn/entity/group/AbstractMembershipTrackingPolicy.java | 5 ++---
 .../src/main/java/brooklyn/util/collections/MutableSet.java     | 3 ---
 2 files changed, 2 insertions(+), 6 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/6f338897/core/src/main/java/brooklyn/entity/group/AbstractMembershipTrackingPolicy.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/brooklyn/entity/group/AbstractMembershipTrackingPolicy.java b/core/src/main/java/brooklyn/entity/group/AbstractMembershipTrackingPolicy.java
index 99fd2b5..049d49c 100644
--- a/core/src/main/java/brooklyn/entity/group/AbstractMembershipTrackingPolicy.java
+++ b/core/src/main/java/brooklyn/entity/group/AbstractMembershipTrackingPolicy.java
@@ -20,7 +20,6 @@ import brooklyn.event.SensorEvent;
 import brooklyn.event.SensorEventListener;
 import brooklyn.policy.basic.AbstractPolicy;
 import brooklyn.util.collections.MutableMap;
-import brooklyn.util.collections.MutableSet;
 
 import com.google.common.base.Objects;
 import com.google.common.base.Preconditions;
@@ -55,10 +54,10 @@ public abstract class AbstractMembershipTrackingPolicy extends AbstractPolicy {
     }
 
     protected Set<Sensor<?>> getSensorsToTrack() {
-        return MutableSet.<Sensor<?>>builder()
+        return ImmutableSet.<Sensor<?>>builder()
                 .addAll(getRequiredConfig(SENSORS_TO_TRACK))
                 .add(Attributes.SERVICE_UP)
-                .buildImmutable();
+                .build();
     }
     
     /**

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/6f338897/utils/common/src/main/java/brooklyn/util/collections/MutableSet.java
----------------------------------------------------------------------
diff --git a/utils/common/src/main/java/brooklyn/util/collections/MutableSet.java b/utils/common/src/main/java/brooklyn/util/collections/MutableSet.java
index 6ab967a..f791949 100644
--- a/utils/common/src/main/java/brooklyn/util/collections/MutableSet.java
+++ b/utils/common/src/main/java/brooklyn/util/collections/MutableSet.java
@@ -111,9 +111,6 @@ public class MutableSet<V> extends LinkedHashSet<V> {
           return new MutableSet<V>(result);
         }
         
-        public ImmutableSet<V> buildImmutable() {
-            return ImmutableSet.copyOf(result);
-        }
     }
     
     public boolean addIfNotNull(V e) {


[36/50] [abbrv] git commit: Merge pull request #1385 from Nakomis/abstract-membership-tracking-policy-ignore-duplicates

Posted by ri...@apache.org.
Merge pull request #1385 from Nakomis/abstract-membership-tracking-policy-ignore-duplicates

Added NOTIFY_ON_DUPLICATES to AbstractMembershipTrackingPolicy

Project: http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/commit/1c9ae924
Tree: http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/tree/1c9ae924
Diff: http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/diff/1c9ae924

Branch: refs/pull/1408/merge
Commit: 1c9ae9245088e6904c4ed66ec1f592e2588e6f8e
Parents: cb2d0d3 6f33889
Author: Andrew Kennedy <gr...@apache.org>
Authored: Fri May 23 17:20:05 2014 +0100
Committer: Andrew Kennedy <gr...@apache.org>
Committed: Fri May 23 17:20:05 2014 +0100

----------------------------------------------------------------------
 .../group/AbstractMembershipTrackingPolicy.java | 77 ++++++++++++++------
 .../group/MembershipTrackingPolicyTest.java     | 39 +++++++++-
 .../brooklyn/util/collections/MutableSet.java   |  2 +
 3 files changed, 95 insertions(+), 23 deletions(-)
----------------------------------------------------------------------



[19/50] [abbrv] git commit: Add enricher memento for rebind

Posted by ri...@apache.org.
Add enricher memento for rebind


Project: http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/commit/34d4f8a4
Tree: http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/tree/34d4f8a4
Diff: http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/diff/34d4f8a4

Branch: refs/pull/1413/head
Commit: 34d4f8a40c11ef5367c3058cdfd3b89a0ecbdedc
Parents: f54024f
Author: Andrew Kennedy <an...@cloudsoftcorp.com>
Authored: Thu May 22 15:20:31 2014 +0100
Committer: Andrew Kennedy <an...@cloudsoftcorp.com>
Committed: Thu May 22 15:20:31 2014 +0100

----------------------------------------------------------------------
 .../java/brooklyn/mementos/BrooklynMemento.java |  6 ++
 .../mementos/BrooklynMementoManifest.java       |  3 +
 .../mementos/BrooklynMementoPersister.java      |  2 +
 .../java/brooklyn/mementos/EnricherMemento.java | 16 +++++
 .../java/brooklyn/mementos/EntityMemento.java   |  5 ++
 .../rebind/BasicEnricherRebindSupport.java      | 50 ++++++++++++++
 .../entity/rebind/BasicPolicyRebindSupport.java |  8 +--
 .../entity/rebind/dto/BasicEnricherMemento.java | 68 ++++++++++++++++++++
 .../entity/rebind/dto/BasicEntityMemento.java   | 10 +++
 .../entity/rebind/dto/MementosGenerators.java   | 32 ++++++++-
 .../rebind/dto/MutableBrooklynMemento.java      | 39 ++++++++++-
 11 files changed, 230 insertions(+), 9 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/34d4f8a4/api/src/main/java/brooklyn/mementos/BrooklynMemento.java
----------------------------------------------------------------------
diff --git a/api/src/main/java/brooklyn/mementos/BrooklynMemento.java b/api/src/main/java/brooklyn/mementos/BrooklynMemento.java
index a528440..1717b3c 100644
--- a/api/src/main/java/brooklyn/mementos/BrooklynMemento.java
+++ b/api/src/main/java/brooklyn/mementos/BrooklynMemento.java
@@ -25,6 +25,8 @@ public interface BrooklynMemento extends Serializable {
     
     public PolicyMemento getPolicyMemento(String id);
     
+    public EnricherMemento getEnricherMemento(String id);
+    
     public Collection<String> getApplicationIds();
     
     public Collection<String> getTopLevelLocationIds();
@@ -35,9 +37,13 @@ public interface BrooklynMemento extends Serializable {
 
     public Collection<String> getPolicyIds();
 
+    public Collection<String> getEnricherIds();
+
     public Map<String, EntityMemento> getEntityMementos();
 
     public Map<String, LocationMemento> getLocationMementos();
 
     public Map<String, PolicyMemento> getPolicyMementos();
+
+    public Map<String, EnricherMemento> getEnricherMementos();
 }

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/34d4f8a4/api/src/main/java/brooklyn/mementos/BrooklynMementoManifest.java
----------------------------------------------------------------------
diff --git a/api/src/main/java/brooklyn/mementos/BrooklynMementoManifest.java b/api/src/main/java/brooklyn/mementos/BrooklynMementoManifest.java
index 2f3e83f..0bc10c0 100644
--- a/api/src/main/java/brooklyn/mementos/BrooklynMementoManifest.java
+++ b/api/src/main/java/brooklyn/mementos/BrooklynMementoManifest.java
@@ -15,4 +15,7 @@ public interface BrooklynMementoManifest extends Serializable {
     public Map<String, String> getLocationIdToType();
 
     public Map<String, String> getPolicyIdToType();
+
+    public Map<String, String> getEnricherIdToType();
+
 }

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/34d4f8a4/api/src/main/java/brooklyn/mementos/BrooklynMementoPersister.java
----------------------------------------------------------------------
diff --git a/api/src/main/java/brooklyn/mementos/BrooklynMementoPersister.java b/api/src/main/java/brooklyn/mementos/BrooklynMementoPersister.java
index ada8135..e29e70e 100644
--- a/api/src/main/java/brooklyn/mementos/BrooklynMementoPersister.java
+++ b/api/src/main/java/brooklyn/mementos/BrooklynMementoPersister.java
@@ -49,8 +49,10 @@ public interface BrooklynMementoPersister {
         Collection<LocationMemento> locations();
         Collection<EntityMemento> entities();
         Collection<PolicyMemento> policies();
+        Collection<EnricherMemento> enrichers();
         Collection<String> removedLocationIds();
         Collection<String> removedEntityIds();
         Collection<String> removedPolicyIds();
+        Collection<String> removedEnricherIds();
     }
 }

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/34d4f8a4/api/src/main/java/brooklyn/mementos/EnricherMemento.java
----------------------------------------------------------------------
diff --git a/api/src/main/java/brooklyn/mementos/EnricherMemento.java b/api/src/main/java/brooklyn/mementos/EnricherMemento.java
new file mode 100644
index 0000000..4213d40
--- /dev/null
+++ b/api/src/main/java/brooklyn/mementos/EnricherMemento.java
@@ -0,0 +1,16 @@
+package brooklyn.mementos;
+
+import java.util.Map;
+
+import brooklyn.entity.rebind.RebindSupport;
+
+/**
+ * Represents the state of an enricher, so that it can be reconstructed (e.g. after restarting brooklyn).
+ * 
+ * @see RebindSupport
+ */
+public interface EnricherMemento extends Memento {
+
+    Map<String, Object> getFlags();
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/34d4f8a4/api/src/main/java/brooklyn/mementos/EntityMemento.java
----------------------------------------------------------------------
diff --git a/api/src/main/java/brooklyn/mementos/EntityMemento.java b/api/src/main/java/brooklyn/mementos/EntityMemento.java
index 59501e2..966bedd 100644
--- a/api/src/main/java/brooklyn/mementos/EntityMemento.java
+++ b/api/src/main/java/brooklyn/mementos/EntityMemento.java
@@ -49,5 +49,10 @@ public interface EntityMemento extends Memento, TreeNode {
      * The ids of the policies of this entity.
      */
     public Collection<String> getPolicies();
+
+    /**
+     * The ids of the enrichers of this entity.
+     */
+    public Collection<String> getEnrichers();
     
 }

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/34d4f8a4/core/src/main/java/brooklyn/entity/rebind/BasicEnricherRebindSupport.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/brooklyn/entity/rebind/BasicEnricherRebindSupport.java b/core/src/main/java/brooklyn/entity/rebind/BasicEnricherRebindSupport.java
new file mode 100644
index 0000000..9d3a50e
--- /dev/null
+++ b/core/src/main/java/brooklyn/entity/rebind/BasicEnricherRebindSupport.java
@@ -0,0 +1,50 @@
+package brooklyn.entity.rebind;
+
+import java.util.Collections;
+import java.util.Map;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import brooklyn.entity.rebind.dto.MementosGenerators;
+import brooklyn.mementos.PolicyMemento;
+import brooklyn.policy.basic.AbstractPolicy;
+
+public class BasicEnricherRebindSupport implements RebindSupport<PolicyMemento> {
+
+    private static final Logger LOG = LoggerFactory.getLogger(BasicEnricherRebindSupport.class);
+    
+    private final AbstractPolicy policy;
+    
+    public BasicEnricherRebindSupport(AbstractPolicy policy) {
+        this.policy = policy;
+    }
+    
+    @Override
+    public PolicyMemento getMemento() {
+        return getMementoWithProperties(Collections.<String,Object>emptyMap());
+    }
+
+    protected PolicyMemento getMementoWithProperties(Map<String,?> props) {
+        PolicyMemento memento = MementosGenerators.newPolicyMementoBuilder(policy).customFields(props).build();
+        if (LOG.isTraceEnabled()) LOG.trace("Creating memento for policy: {}", memento.toVerboseString());
+        return memento;
+    }
+
+    @Override
+    public void reconstruct(RebindContext rebindContext, PolicyMemento memento) {
+        if (LOG.isTraceEnabled()) LOG.trace("Reconstructing policy: {}", memento.toVerboseString());
+
+        // Note that the flags have been set in the constructor
+        policy.setName(memento.getDisplayName());
+        
+        doReconsruct(rebindContext, memento);
+    }
+
+    /**
+     * For overriding, to give custom reconsruct behaviour.
+     */
+    protected void doReconsruct(RebindContext rebindContext, PolicyMemento memento) {
+        // default is no-op
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/34d4f8a4/core/src/main/java/brooklyn/entity/rebind/BasicPolicyRebindSupport.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/brooklyn/entity/rebind/BasicPolicyRebindSupport.java b/core/src/main/java/brooklyn/entity/rebind/BasicPolicyRebindSupport.java
index acf0ebb..2c33702 100644
--- a/core/src/main/java/brooklyn/entity/rebind/BasicPolicyRebindSupport.java
+++ b/core/src/main/java/brooklyn/entity/rebind/BasicPolicyRebindSupport.java
@@ -27,15 +27,15 @@ public class BasicPolicyRebindSupport implements RebindSupport<PolicyMemento> {
 
     protected PolicyMemento getMementoWithProperties(Map<String,?> props) {
         PolicyMemento memento = MementosGenerators.newPolicyMementoBuilder(policy).customFields(props).build();
-    	if (LOG.isTraceEnabled()) LOG.trace("Creating memento for policy: {}", memento.toVerboseString());
-    	return memento;
+        if (LOG.isTraceEnabled()) LOG.trace("Creating memento for policy: {}", memento.toVerboseString());
+        return memento;
     }
 
     @Override
     public void reconstruct(RebindContext rebindContext, PolicyMemento memento) {
-    	if (LOG.isTraceEnabled()) LOG.trace("Reconstructing policy: {}", memento.toVerboseString());
+        if (LOG.isTraceEnabled()) LOG.trace("Reconstructing policy: {}", memento.toVerboseString());
 
-    	// Note that the flags have been set in the constructor
+        // Note that the flags have been set in the constructor
         policy.setName(memento.getDisplayName());
         
         doReconsruct(rebindContext, memento);

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/34d4f8a4/core/src/main/java/brooklyn/entity/rebind/dto/BasicEnricherMemento.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/brooklyn/entity/rebind/dto/BasicEnricherMemento.java b/core/src/main/java/brooklyn/entity/rebind/dto/BasicEnricherMemento.java
new file mode 100644
index 0000000..b1d7052
--- /dev/null
+++ b/core/src/main/java/brooklyn/entity/rebind/dto/BasicEnricherMemento.java
@@ -0,0 +1,68 @@
+package brooklyn.entity.rebind.dto;
+
+import java.io.Serializable;
+import java.util.Map;
+
+import brooklyn.entity.basic.Entities;
+import brooklyn.mementos.EnricherMemento;
+
+import com.google.common.base.Objects.ToStringHelper;
+import com.google.common.collect.Maps;
+
+/**
+ * The persisted state of a location.
+ *
+ * @author aled
+ */
+public class BasicEnricherMemento extends AbstractMemento implements EnricherMemento, Serializable {
+
+    private static final long serialVersionUID = -1; // FIXME
+
+    public static Builder builder() {
+        return new Builder();
+    }
+
+    public static class Builder extends AbstractMemento.Builder<Builder> {
+        protected Map<String,Object> flags = Maps.newLinkedHashMap();
+
+        public Builder from(EnricherMemento other) {
+            super.from(other);
+            flags.putAll(other.getFlags());
+            return this;
+        }
+        public Builder flags(Map<String,?> vals) {
+            flags.putAll(vals); return this;
+        }
+        public EnricherMemento build() {
+            return new BasicEnricherMemento(this);
+        }
+    }
+
+    private Map<String,Object> flags;
+    private Map<String, Object> fields;
+
+    // Trusts the builder to not mess around with mutability after calling build()
+    protected BasicEnricherMemento(Builder builder) {
+        flags = toPersistedMap(builder.flags);
+    }
+
+    @Override
+    protected void setCustomFields(Map<String, Object> fields) {
+        this.fields = toPersistedMap(fields);
+    }
+
+    @Override
+    public Map<String, Object> getCustomFields() {
+        return fromPersistedMap(fields);
+    }
+
+    @Override
+    public Map<String, Object> getFlags() {
+        return fromPersistedMap(flags);
+    }
+
+    @Override
+    protected ToStringHelper newVerboseStringHelper() {
+        return super.newVerboseStringHelper().add("flags", Entities.sanitize(getFlags()));
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/34d4f8a4/core/src/main/java/brooklyn/entity/rebind/dto/BasicEntityMemento.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/brooklyn/entity/rebind/dto/BasicEntityMemento.java b/core/src/main/java/brooklyn/entity/rebind/dto/BasicEntityMemento.java
index 7377629..9ded4f7 100644
--- a/core/src/main/java/brooklyn/entity/rebind/dto/BasicEntityMemento.java
+++ b/core/src/main/java/brooklyn/entity/rebind/dto/BasicEntityMemento.java
@@ -49,6 +49,7 @@ public class BasicEntityMemento extends AbstractTreeNodeMemento implements Entit
         protected Map<AttributeSensor<?>, Object> attributes = Maps.newLinkedHashMap();
         protected List<String> locations = Lists.newArrayList();
         protected List<String> policies = Lists.newArrayList();
+        protected List<String> enrichers = Lists.newArrayList();
         protected List<String> members = Lists.newArrayList();
         protected List<Effector<?>> effectors = Lists.newArrayList();
         
@@ -61,6 +62,7 @@ public class BasicEntityMemento extends AbstractTreeNodeMemento implements Entit
             attributes.putAll(other.getAttributes());
             locations.addAll(other.getLocations());
             policies.addAll(other.getPolicies());
+            enrichers.addAll(other.getEnrichers());
             members.addAll(other.getMembers());
             effectors.addAll(other.getEffectors());
             return this;
@@ -81,6 +83,7 @@ public class BasicEntityMemento extends AbstractTreeNodeMemento implements Entit
     private List<String> members;
     private Map<String, Object> attributes;
     private List<String> policies;
+    private List<String> enrichers;
     
     // TODO can we move some of these to entity type, or remove/re-insert those which are final statics?
     private Map<String, ConfigKey<?>> configKeys;
@@ -107,6 +110,7 @@ public class BasicEntityMemento extends AbstractTreeNodeMemento implements Entit
         
         locations = toPersistedList(builder.locations);
         policies = toPersistedList(builder.policies);
+        enrichers = toPersistedList(builder.enrichers);
         members = toPersistedList(builder.members);
         
         effectors = toPersistedList(builder.effectors);
@@ -243,6 +247,11 @@ public class BasicEntityMemento extends AbstractTreeNodeMemento implements Entit
     }
     
     @Override
+    public List<String> getEnrichers() {
+        return fromPersistedList(enrichers);
+    }
+    
+    @Override
     public List<String> getMembers() {
         return fromPersistedList(members);
     }
@@ -260,6 +269,7 @@ public class BasicEntityMemento extends AbstractTreeNodeMemento implements Entit
                 .add("configUnmatched", Entities.sanitize(getConfigUnmatched()))
                 .add("attributes", Entities.sanitize(getAttributes()))
                 .add("policies", getPolicies())
+                .add("enrichers", getEnrichers())
                 .add("locations", getLocations());
     }
 

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/34d4f8a4/core/src/main/java/brooklyn/entity/rebind/dto/MementosGenerators.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/brooklyn/entity/rebind/dto/MementosGenerators.java b/core/src/main/java/brooklyn/entity/rebind/dto/MementosGenerators.java
index 3eaada3..c77fb34 100644
--- a/core/src/main/java/brooklyn/entity/rebind/dto/MementosGenerators.java
+++ b/core/src/main/java/brooklyn/entity/rebind/dto/MementosGenerators.java
@@ -21,9 +21,11 @@ import brooklyn.location.basic.LocationInternal;
 import brooklyn.management.ManagementContext;
 import brooklyn.management.Task;
 import brooklyn.mementos.BrooklynMemento;
+import brooklyn.mementos.EnricherMemento;
 import brooklyn.mementos.EntityMemento;
 import brooklyn.mementos.LocationMemento;
 import brooklyn.mementos.PolicyMemento;
+import brooklyn.policy.Enricher;
 import brooklyn.policy.Policy;
 import brooklyn.util.collections.MutableMap;
 import brooklyn.util.config.ConfigBag;
@@ -143,9 +145,13 @@ public class MementosGenerators {
         // (e.g. AbstractController registering a AbstractMembershipTrackingPolicy)
         // Also, the entity constructor often re-creates the policy
         // Also see RebindManagerImpl.CheckpointingChangeListener.onChanged(Entity)
-//        for (Policy policy : entity.getPolicies()) {
-//            builder.policies.add(policy.getId()); 
-//        }
+        for (Policy policy : entity.getPolicies()) {
+            builder.policies.add(policy.getId()); 
+        }
+        
+        for (Enricher enricher : entity.getEnrichers()) {
+            builder.enrichers.add(enricher.getId()); 
+        }
         
         Entity parentEntity = entity.getParent();
         builder.parent = (parentEntity != null) ? parentEntity.getId() : null;
@@ -219,4 +225,24 @@ public class MementosGenerators {
         
         return builder;
     }
+    
+    /**
+     * Given an enricher, extracts its state for serialization.
+     */
+    public static EnricherMemento newEnricherMemento(Enricher enricher) {
+        return newEnricherMementoBuilder(enricher).build();
+    }
+    
+    public static BasicEnricherMemento.Builder newEnricherMementoBuilder(Enricher enricher) {
+        BasicEnricherMemento.Builder builder = BasicEnricherMemento.builder();
+        
+        builder.type = enricher.getClass().getName();
+        builder.typeClass = enricher.getClass();
+        builder.id = enricher.getId();
+        builder.displayName = enricher.getName();
+
+        builder.flags.putAll(FlagUtils.getFieldsWithFlagsExcludingModifiers(enricher, Modifier.STATIC ^ Modifier.TRANSIENT));
+        
+        return builder;
+    }
 }

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/34d4f8a4/core/src/main/java/brooklyn/entity/rebind/dto/MutableBrooklynMemento.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/brooklyn/entity/rebind/dto/MutableBrooklynMemento.java b/core/src/main/java/brooklyn/entity/rebind/dto/MutableBrooklynMemento.java
index 1b9e4e7..61bbb8c 100644
--- a/core/src/main/java/brooklyn/entity/rebind/dto/MutableBrooklynMemento.java
+++ b/core/src/main/java/brooklyn/entity/rebind/dto/MutableBrooklynMemento.java
@@ -10,6 +10,7 @@ import org.codehaus.jackson.annotate.JsonAutoDetect;
 import org.codehaus.jackson.annotate.JsonAutoDetect.Visibility;
 
 import brooklyn.mementos.BrooklynMemento;
+import brooklyn.mementos.EnricherMemento;
 import brooklyn.mementos.EntityMemento;
 import brooklyn.mementos.LocationMemento;
 import brooklyn.mementos.PolicyMemento;
@@ -36,6 +37,7 @@ public class MutableBrooklynMemento implements BrooklynMemento {
     private final Map<String, EntityMemento> entities = Maps.newLinkedHashMap();
     private final Map<String, LocationMemento> locations = Maps.newLinkedHashMap();
     private final Map<String, PolicyMemento> policies = Maps.newLinkedHashMap();
+    private final Map<String, EnricherMemento> enrichers = Maps.newLinkedHashMap();
 
     public MutableBrooklynMemento() {
     }
@@ -67,6 +69,10 @@ public class MutableBrooklynMemento implements BrooklynMemento {
         updatePolicyMementos(ImmutableSet.of(memento));
     }
     
+    public void updateEnricherMemento(EnricherMemento memento) {
+        updateEnricherMementos(ImmutableSet.of(memento));
+    }
+    
     public void updateEntityMementos(Collection<EntityMemento> mementos) {
         for (EntityMemento memento : mementos) {
             entities.put(memento.getId(), memento);
@@ -93,6 +99,12 @@ public class MutableBrooklynMemento implements BrooklynMemento {
         }
     }
     
+    public void updateEnricherMementos(Collection<EnricherMemento> mementos) {
+        for (EnricherMemento memento : mementos) {
+            enrichers.put(memento.getId(), memento);
+        }
+    }
+    
     /**
      * Removes the entities with the given ids.
      */
@@ -102,7 +114,7 @@ public class MutableBrooklynMemento implements BrooklynMemento {
     }
     
     /**
-     * Removes the entities with the given ids.
+     * Removes the locations with the given ids.
      */
     public void removeLocations(Collection<String> ids) {
         locations.keySet().removeAll(ids);
@@ -110,12 +122,19 @@ public class MutableBrooklynMemento implements BrooklynMemento {
     }
 
     /**
-     * Removes the entities with the given ids.
+     * Removes the policies with the given ids.
      */
     public void removePolicies(Collection<String> ids) {
         policies.keySet().removeAll(ids);
     }
 
+    /**
+     * Removes the enrichers with the given ids.
+     */
+    public void removeEnrichers(Collection<String> ids) {
+        enrichers.keySet().removeAll(ids);
+    }
+
     @Override
     public EntityMemento getEntityMemento(String id) {
         return entities.get(id);
@@ -130,6 +149,12 @@ public class MutableBrooklynMemento implements BrooklynMemento {
     public PolicyMemento getPolicyMemento(String id) {
         return policies.get(id);
     }
+
+    
+    @Override
+    public EnricherMemento getEnricherMemento(String id) {
+        return enrichers.get(id);
+    }
     
     @Override
     public Collection<String> getApplicationIds() {
@@ -153,6 +178,11 @@ public class MutableBrooklynMemento implements BrooklynMemento {
     }
     
     @Override
+    public Collection<String> getEnricherIds() {
+        return Collections.unmodifiableSet(enrichers.keySet());
+    }
+    
+    @Override
     public Collection<String> getTopLevelLocationIds() {
         return Collections.unmodifiableCollection(topLevelLocationIds);
     }
@@ -171,4 +201,9 @@ public class MutableBrooklynMemento implements BrooklynMemento {
     public Map<String, PolicyMemento> getPolicyMementos() {
         return ImmutableMap.copyOf(policies);
     }
+
+    @Override
+    public Map<String, EnricherMemento> getEnricherMementos() {
+        return ImmutableMap.copyOf(enrichers);
+    }
 }


[42/50] [abbrv] git commit: Merge f93972fbb7a397c275ee0dd73feeecb03bd24cb3 into 1c9ae9245088e6904c4ed66ec1f592e2588e6f8e

Posted by ri...@apache.org.
Merge f93972fbb7a397c275ee0dd73feeecb03bd24cb3 into 1c9ae9245088e6904c4ed66ec1f592e2588e6f8e


Project: http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/commit/9f2ef416
Tree: http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/tree/9f2ef416
Diff: http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/diff/9f2ef416

Branch: refs/pull/1405/merge
Commit: 9f2ef416874d9ff4e6db5631fd37799cf7be9a34
Parents: 1c9ae92 f93972f
Author: Aled Sage <al...@gmail.com>
Authored: Fri May 23 16:27:03 2014 +0000
Committer: Aled Sage <al...@gmail.com>
Committed: Fri May 23 16:27:03 2014 +0000

----------------------------------------------------------------------
 .../java/brooklyn/entity/basic/Entities.java    | 12 ++++
 .../location/basic/AbstractLocation.java        |  3 +-
 .../location/basic/BasicLocationRegistry.java   | 42 ++++++++----
 .../location/basic/LocationInternal.java        |  7 +-
 .../location/basic/LocationPredicates.java      | 69 +++++++++++++++++++
 .../location/basic/MultiLocationResolver.java   | 71 ++++++++++++++------
 .../location/basic/LocationPredicatesTest.java  | 68 +++++++++++++++++++
 .../basic/MultiLocationResolverTest.java        | 11 +++
 .../entity/proxy/AbstractControllerImpl.java    |  8 ++-
 .../rest/resources/LocationResource.java        | 13 +++-
 10 files changed, 262 insertions(+), 42 deletions(-)
----------------------------------------------------------------------



[34/50] [abbrv] git commit: Merge pull request #1385 from Nakomis/abstract-membership-tracking-policy-ignore-duplicates

Posted by ri...@apache.org.
Merge pull request #1385 from Nakomis/abstract-membership-tracking-policy-ignore-duplicates

Added NOTIFY_ON_DUPLICATES to AbstractMembershipTrackingPolicy

Project: http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/commit/1c9ae924
Tree: http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/tree/1c9ae924
Diff: http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/diff/1c9ae924

Branch: refs/pull/1405/merge
Commit: 1c9ae9245088e6904c4ed66ec1f592e2588e6f8e
Parents: cb2d0d3 6f33889
Author: Andrew Kennedy <gr...@apache.org>
Authored: Fri May 23 17:20:05 2014 +0100
Committer: Andrew Kennedy <gr...@apache.org>
Committed: Fri May 23 17:20:05 2014 +0100

----------------------------------------------------------------------
 .../group/AbstractMembershipTrackingPolicy.java | 77 ++++++++++++++------
 .../group/MembershipTrackingPolicyTest.java     | 39 +++++++++-
 .../brooklyn/util/collections/MutableSet.java   |  2 +
 3 files changed, 95 insertions(+), 23 deletions(-)
----------------------------------------------------------------------



[39/50] [abbrv] git commit: Merge 972115a2479fbafd8c3f793094a3fd0b831b6665 into 1c9ae9245088e6904c4ed66ec1f592e2588e6f8e

Posted by ri...@apache.org.
Merge 972115a2479fbafd8c3f793094a3fd0b831b6665 into 1c9ae9245088e6904c4ed66ec1f592e2588e6f8e


Project: http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/commit/df8e1a0b
Tree: http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/tree/df8e1a0b
Diff: http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/diff/df8e1a0b

Branch: refs/pull/1408/merge
Commit: df8e1a0b2d8b4726bdedfd5cf1b076d205477730
Parents: 1c9ae92 972115a
Author: Zaid <za...@cloudsoftcorp.com>
Authored: Fri May 23 16:20:22 2014 +0000
Committer: Zaid <za...@cloudsoftcorp.com>
Committed: Fri May 23 16:20:22 2014 +0000

----------------------------------------------------------------------
 .../java/brooklyn/demo/RiakClusterExample.java  | 33 ++++++---
 .../brooklyn/entity/nosql/riak/RiakCluster.java |  9 +++
 .../entity/nosql/riak/RiakClusterImpl.java      | 77 +++++++++++++++-----
 .../brooklyn/entity/nosql/riak/RiakNode.java    | 48 ++++++------
 .../entity/nosql/riak/RiakNodeDriver.java       |  2 +
 .../entity/nosql/riak/RiakNodeImpl.java         |  3 +
 .../entity/nosql/riak/RiakNodeSshDriver.java    | 59 +++++++++------
 .../nosql/riak/RiakClusterEc2LiveTest.java      |  7 +-
 .../riak/RiakNodeGoogleComputeLiveTest.java     |  7 +-
 9 files changed, 169 insertions(+), 76 deletions(-)
----------------------------------------------------------------------



[22/50] [abbrv] git commit: Fix use of service command with iptables and deprecate old methods

Posted by ri...@apache.org.
Fix use of service command with iptables and deprecate old methods


Project: http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/commit/803f9f13
Tree: http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/tree/803f9f13
Diff: http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/diff/803f9f13

Branch: refs/pull/1405/merge
Commit: 803f9f1397c1ade033e570fdb5ac1d47d811dfeb
Parents: f54024f
Author: Andrew Kennedy <an...@cloudsoftcorp.com>
Authored: Thu May 22 23:11:12 2014 +0100
Committer: Andrew Kennedy <an...@cloudsoftcorp.com>
Committed: Fri May 23 00:14:27 2014 +0100

----------------------------------------------------------------------
 .../location/jclouds/JcloudsLocationConfig.java |  1 +
 .../brooklyn/util/ssh/IptablesCommands.java     | 97 +++++++++++---------
 2 files changed, 54 insertions(+), 44 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/803f9f13/locations/jclouds/src/main/java/brooklyn/location/jclouds/JcloudsLocationConfig.java
----------------------------------------------------------------------
diff --git a/locations/jclouds/src/main/java/brooklyn/location/jclouds/JcloudsLocationConfig.java b/locations/jclouds/src/main/java/brooklyn/location/jclouds/JcloudsLocationConfig.java
index 49729a1..5f4a6ff 100644
--- a/locations/jclouds/src/main/java/brooklyn/location/jclouds/JcloudsLocationConfig.java
+++ b/locations/jclouds/src/main/java/brooklyn/location/jclouds/JcloudsLocationConfig.java
@@ -118,6 +118,7 @@ public interface JcloudsLocationConfig extends CloudLocationConfig {
             "Tags to be applied when creating a VM, on supported clouds " +
             "(either a single tag as a String, or an Iterable<String> or String[];" +
             "note this is not key-value pairs (e.g. what AWS calls 'tags'), for that see userMetadata)", null);
+
     @Deprecated /** @deprecated since 0.7.0 use #STRING_TAGS */
     public static final ConfigKey<Object> TAGS = STRING_TAGS;
 

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/803f9f13/utils/common/src/main/java/brooklyn/util/ssh/IptablesCommands.java
----------------------------------------------------------------------
diff --git a/utils/common/src/main/java/brooklyn/util/ssh/IptablesCommands.java b/utils/common/src/main/java/brooklyn/util/ssh/IptablesCommands.java
index 2fac2a6..6f971a0 100644
--- a/utils/common/src/main/java/brooklyn/util/ssh/IptablesCommands.java
+++ b/utils/common/src/main/java/brooklyn/util/ssh/IptablesCommands.java
@@ -15,9 +15,7 @@ public class IptablesCommands {
         ACCEPT, REJECT, DROP, LOG
     }
 
-    /**
-     * @deprecated since 0.7; use {@link brooklyn.util.net.Protocol}
-     */
+    /*** @deprecated since 0.7; use {@link brooklyn.util.net.Protocol} */
     @Deprecated
     public enum Protocol {
         TCP("tcp"), UDP("udp"), ALL("all");
@@ -32,18 +30,25 @@ public class IptablesCommands {
         public String toString() {
             return protocol;
         }
-        
+
         brooklyn.util.net.Protocol convert() {
             switch (this) {
-                case TCP : return brooklyn.util.net.Protocol.TCP;
-                case UDP : return brooklyn.util.net.Protocol.UDP;
-                case ALL : return brooklyn.util.net.Protocol.ALL;
-                default:   throw new IllegalStateException("Unexpected protocol "+this);
+                case TCP: return brooklyn.util.net.Protocol.TCP;
+                case UDP: return brooklyn.util.net.Protocol.UDP;
+                case ALL: return brooklyn.util.net.Protocol.ALL;
+                default: throw new IllegalStateException("Unexpected protocol "+this);
             }
         }
     }
 
     @Beta // implementation not portable across distros
+    public static String iptablesService(String cmd) {
+        return sudo(BashCommands.alternatives(
+                BashCommands.ifExecutableElse1("service", "service iptables "+cmd),
+                "/sbin/service iptables " + cmd));
+    }
+
+    @Beta // implementation not portable across distros
     public static String iptablesServiceStop() {
         return iptablesService("stop");
     }
@@ -63,32 +68,29 @@ public class IptablesCommands {
         return iptablesService("status");
     }
 
-    @Beta // implementation not portable across distros
-    public static String iptablesService(String cmd) {
-        return sudo("/sbin/service iptables "+cmd);
+    /**
+     * Returns the command that saves on disk iptables rules, to make them resilient to reboot.
+     *
+     * @return Returns the command that saves on disk iptables rules.
+     */
+    public static String saveIptablesRules() {
+        return BashCommands.alternatives(
+                BashCommands.ifExecutableElse1("iptables-save", sudo("iptables-save")),
+                iptablesService("save"));
     }
 
     /**
      * Returns the command that cleans up iptables rules.
-     * 
+     *
      * @return Returns the command that cleans up iptables rules.
      */
     public static String cleanUpIptablesRules() {
        return sudo("/sbin/iptables -F");
     }
-    
-    /**
-     * Returns the command that saves on disk iptables rules, to make them resilient to reboot.
-     * 
-     * @return Returns the command that saves on disk iptables rules.
-     */
-    public static String saveIptablesRules() {
-       return sudo("/sbin/service iptables save");
-    }
-    
+
     /**
      * Returns the iptables rules.
-     * 
+     *
      * @return Returns the command that list all the iptables rules.
      */
     public static String listIptablesRule() {
@@ -97,77 +99,84 @@ public class IptablesCommands {
 
     /**
      * Returns the command that inserts a rule on top of the iptables' rules to all interfaces.
-     * 
+     *
      * @return Returns the command that inserts a rule on top of the iptables'
      *         rules.
      */
     public static String insertIptablesRule(Chain chain, brooklyn.util.net.Protocol protocol, int port, Policy policy) {
         return addIptablesRule("-I", chain, Optional.<String> absent(), protocol, port, policy);
     }
-    
+
+    /** @deprecated since 0.7.0; use {@link #insertIptablesRule(Chain, brooklyn.util.net.Protocol, int, Policy)} */
+    @Deprecated
     public static String insertIptablesRule(Chain chain, Protocol protocol, int port, Policy policy) {
         return insertIptablesRule(chain, protocol.convert(), port, policy);
     }
-    
+
     /**
      * Returns the command that inserts a rule on top of the iptables' rules.
-     * 
+     *
      * @return Returns the command that inserts a rule on top of the iptables'
      *         rules.
      */
     public static String insertIptablesRule(Chain chain, String networkInterface, brooklyn.util.net.Protocol protocol, int port, Policy policy) {
         return addIptablesRule("-I", chain, Optional.of(networkInterface), protocol, port, policy);
     }
-    
+
+    /** @deprecated since 0.7.0; use {@link #insertIptablesRule(Chain, String, brooklyn.util.net.Protocol, int, Policy)} */
+    @Deprecated
     public static String insertIptablesRule(Chain chain, String networkInterface, Protocol protocol, int port, Policy policy) {
         return insertIptablesRule(chain, networkInterface, protocol.convert(), port, policy);
     }
 
     /**
      * Returns the command that appends a rule to iptables to all interfaces.
-     * 
+     *
      * @return Returns the command that appends a rule to iptables.
      */
     public static String appendIptablesRule(Chain chain, brooklyn.util.net.Protocol protocol, int port, Policy policy) {
         return addIptablesRule("-A", chain, Optional.<String> absent(), protocol, port, policy);
     }
-    
+
+    /** @deprecated since 0.7.0; use {@link #appendIptablesRule(Chain, brooklyn.util.net.Protocol, int, Policy)} */
+    @Deprecated
     public static String appendIptablesRule(Chain chain, Protocol protocol, int port, Policy policy) {
         return appendIptablesRule(chain, protocol.convert(), port, policy);
     }
-    
+
     /**
      * Returns the command that appends a rule to iptables.
-     * 
+     *
      * @return Returns the command that appends a rule to iptables.
      */
     public static String appendIptablesRule(Chain chain, String networkInterface, brooklyn.util.net.Protocol protocol, int port, Policy policy) {
         return addIptablesRule("-A", chain, Optional.of(networkInterface), protocol, port, policy);
     }
-    
+
+    /** @deprecated since 0.7.0; use {@link #appendIptablesRule(Chain, String, brooklyn.util.net.Protocol, int, Policy)} */
+    @Deprecated
     public static String appendIptablesRule(Chain chain, String networkInterface, Protocol protocol, int port, Policy policy) {
         return appendIptablesRule(chain, networkInterface, protocol.convert(), port, policy);
     }
 
     /**
      * Returns the command that creates a rule to iptables.
-     * 
-     * @return Returns the command that creates a rule to iptables.
+     *
+     * @return Returns the command that creates a rule for iptables.
      */
-    private static String addIptablesRule(String direction, Chain chain, Optional<String> networkInterface, brooklyn.util.net.Protocol protocol, int port,
-            Policy policy) {
-        String addIptablesRule; 
-        if(networkInterface.isPresent()) {  
+    public static String addIptablesRule(String direction, Chain chain, Optional<String> networkInterface, brooklyn.util.net.Protocol protocol, int port, Policy policy) {
+        String addIptablesRule;
+        if(networkInterface.isPresent()) {
            addIptablesRule = String.format("/sbin/iptables %s %s -i %s -p %s --dport %d -j %s", direction, chain, networkInterface.get(), protocol, port, policy);
         } else {
-           addIptablesRule = String.format("/sbin/iptables %s %s -p %s --dport %d -j %s", direction, chain,
-                 protocol, port, policy);
+           addIptablesRule = String.format("/sbin/iptables %s %s -p %s --dport %d -j %s", direction, chain, protocol, port, policy);
         }
         return sudo(addIptablesRule);
     }
-    
-    private static String addIptablesRule(String direction, Chain chain, Optional<String> networkInterface, Protocol protocol, int port,
-            Policy policy) {
+
+    /** @deprecated since 0.7.0; use {@link #addIptablesRule(String, Chain, Optional, brooklyn.util.net.Protocol, int, Policy)} */
+    @Deprecated
+    public static String addIptablesRule(String direction, Chain chain, Optional<String> networkInterface, Protocol protocol, int port, Policy policy) {
         return addIptablesRule(direction, chain, networkInterface, protocol.convert(), port, policy);
     }
 


[28/50] [abbrv] git commit: Merge 80532a5bcea8334f1c012657448e302230d7247d into 48a34e414bee3918ceff23c65481ab22d4a2859c

Posted by ri...@apache.org.
Merge 80532a5bcea8334f1c012657448e302230d7247d into 48a34e414bee3918ceff23c65481ab22d4a2859c


Project: http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/commit/46aeda22
Tree: http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/tree/46aeda22
Diff: http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/diff/46aeda22

Branch: refs/pull/1413/merge
Commit: 46aeda224dac230fb28ef5fe6751174038780c78
Parents: 48a34e4 80532a5
Author: Andrew Kennedy <gr...@apache.org>
Authored: Fri May 23 16:15:41 2014 +0000
Committer: Andrew Kennedy <gr...@apache.org>
Committed: Fri May 23 16:15:41 2014 +0000

----------------------------------------------------------------------
 .../brooklyn/entity/rebind/ChangeListener.java  |  4 ++
 .../brooklyn/entity/rebind/RebindContext.java   | 12 ++--
 .../java/brooklyn/mementos/BrooklynMemento.java |  6 ++
 .../mementos/BrooklynMementoManifest.java       |  3 +
 .../mementos/BrooklynMementoPersister.java      |  6 ++
 .../java/brooklyn/mementos/EnricherMemento.java | 16 +++++
 .../java/brooklyn/mementos/EntityMemento.java   |  5 ++
 api/src/main/java/brooklyn/policy/Enricher.java | 17 +++--
 .../enricher/basic/AbstractEnricher.java        |  8 +++
 .../rebind/BasicEnricherRebindSupport.java      | 50 +++++++++++++
 .../entity/rebind/BasicEntityRebindSupport.java | 20 +++++-
 .../entity/rebind/BasicPolicyRebindSupport.java |  8 +--
 .../rebind/ImmediateDeltaChangeListener.java    | 10 +++
 .../rebind/PeriodicDeltaChangeListener.java     | 35 +++++++--
 .../entity/rebind/PersisterDeltaImpl.java       | 13 ++++
 .../entity/rebind/RebindContextImpl.java        | 11 +++
 .../entity/rebind/RebindManagerImpl.java        | 76 +++++++++++++++++++-
 .../entity/rebind/dto/BasicEnricherMemento.java | 68 ++++++++++++++++++
 .../entity/rebind/dto/BasicEntityMemento.java   | 10 +++
 .../entity/rebind/dto/BrooklynMementoImpl.java  | 25 +++++++
 .../rebind/dto/BrooklynMementoManifestImpl.java | 14 ++++
 .../entity/rebind/dto/MementosGenerators.java   | 32 ++++++++-
 .../rebind/dto/MutableBrooklynMemento.java      | 39 +++++++++-
 .../AbstractBrooklynMementoPersister.java       |  6 ++
 .../BrooklynMementoPersisterInMemory.java       | 12 ++++
 .../BrooklynMementoPersisterToMultiFile.java    | 71 +++++++++++++++---
 .../rebind/persister/XmlMementoSerializer.java  | 31 +++++++-
 .../internal/EntityChangeListener.java          |  2 +-
 .../internal/EntityManagementSupport.java       |  2 +
 .../persister/XmlMementoSerializerTest.java     | 75 ++++++++++++-------
 30 files changed, 624 insertions(+), 63 deletions(-)
----------------------------------------------------------------------



[41/50] [abbrv] git commit: Merge b23340ba2fecc7b7276c3fbf570ba23f91a9a387 into 1c9ae9245088e6904c4ed66ec1f592e2588e6f8e

Posted by ri...@apache.org.
Merge b23340ba2fecc7b7276c3fbf570ba23f91a9a387 into 1c9ae9245088e6904c4ed66ec1f592e2588e6f8e


Project: http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/commit/8179824f
Tree: http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/tree/8179824f
Diff: http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/diff/8179824f

Branch: refs/pull/1410/merge
Commit: 8179824f7de86b863154957c1ba5e992e41d4fca
Parents: 1c9ae92 b23340b
Author: Sam Corbett <sa...@cloudsoftcorp.com>
Authored: Fri May 23 16:21:20 2014 +0000
Committer: Sam Corbett <sa...@cloudsoftcorp.com>
Committed: Fri May 23 16:21:20 2014 +0000

----------------------------------------------------------------------
 .../entity/basic/BrooklynConfigKeys.java        | 10 +++---
 usage/jsgui/build/gzip-with-redirect.sh         | 23 --------------
 usage/jsgui/pom.xml                             | 32 +++++++++-----------
 .../main/webapp/assets/js/view/googlemaps.js    |  6 ++--
 4 files changed, 22 insertions(+), 49 deletions(-)
----------------------------------------------------------------------



[48/50] [abbrv] git commit: comments on BrooklynNode

Posted by ri...@apache.org.
comments on BrooklynNode


Project: http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/commit/99b9e19b
Tree: http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/tree/99b9e19b
Diff: http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/diff/99b9e19b

Branch: refs/pull/1414/merge
Commit: 99b9e19bfbb406f30d1e6c05bcc52ccdc4acdc87
Parents: 37cf817
Author: Alex Heneveld <al...@cloudsoftcorp.com>
Authored: Wed May 21 09:28:07 2014 -0600
Committer: Alex Heneveld <al...@cloudsoftcorp.com>
Committed: Fri May 23 10:35:45 2014 -0600

----------------------------------------------------------------------
 .../src/main/java/brooklyn/entity/brooklynnode/BrooklynNode.java  | 3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/99b9e19b/software/base/src/main/java/brooklyn/entity/brooklynnode/BrooklynNode.java
----------------------------------------------------------------------
diff --git a/software/base/src/main/java/brooklyn/entity/brooklynnode/BrooklynNode.java b/software/base/src/main/java/brooklyn/entity/brooklynnode/BrooklynNode.java
index f582820..cb21307 100644
--- a/software/base/src/main/java/brooklyn/entity/brooklynnode/BrooklynNode.java
+++ b/software/base/src/main/java/brooklyn/entity/brooklynnode/BrooklynNode.java
@@ -94,7 +94,8 @@ public interface BrooklynNode extends SoftwareProcess, UsesJava {
 
     @SetFromFlag("launchCommandCreatesPidFile")
     ConfigKey<Boolean> LAUNCH_COMMAND_CREATES_PID_FILE = ConfigKeys.newBooleanConfigKey("brooklynnode.launch.command.pid.updated",
-        "Whether the launch script creates/updates the PID file, if not the entity will do so", 
+        "Whether the launch script creates/updates the PID file, if not the entity will do so, "
+        + "but note it will not necessarily kill sub-processes", 
         true);
 
     @SetFromFlag("app")


[16/50] [abbrv] git commit: Updated following PR review

Posted by ri...@apache.org.
Updated following PR review


Project: http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/commit/6f338897
Tree: http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/tree/6f338897
Diff: http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/diff/6f338897

Branch: refs/pull/1411/merge
Commit: 6f338897b704b1db1b88ec5cd9c1522e39ba2f08
Parents: 238780f
Author: Martin Harris <gi...@nakomis.com>
Authored: Thu May 22 10:47:42 2014 +0100
Committer: Martin Harris <gi...@nakomis.com>
Committed: Thu May 22 10:47:42 2014 +0100

----------------------------------------------------------------------
 .../brooklyn/entity/group/AbstractMembershipTrackingPolicy.java | 5 ++---
 .../src/main/java/brooklyn/util/collections/MutableSet.java     | 3 ---
 2 files changed, 2 insertions(+), 6 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/6f338897/core/src/main/java/brooklyn/entity/group/AbstractMembershipTrackingPolicy.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/brooklyn/entity/group/AbstractMembershipTrackingPolicy.java b/core/src/main/java/brooklyn/entity/group/AbstractMembershipTrackingPolicy.java
index 99fd2b5..049d49c 100644
--- a/core/src/main/java/brooklyn/entity/group/AbstractMembershipTrackingPolicy.java
+++ b/core/src/main/java/brooklyn/entity/group/AbstractMembershipTrackingPolicy.java
@@ -20,7 +20,6 @@ import brooklyn.event.SensorEvent;
 import brooklyn.event.SensorEventListener;
 import brooklyn.policy.basic.AbstractPolicy;
 import brooklyn.util.collections.MutableMap;
-import brooklyn.util.collections.MutableSet;
 
 import com.google.common.base.Objects;
 import com.google.common.base.Preconditions;
@@ -55,10 +54,10 @@ public abstract class AbstractMembershipTrackingPolicy extends AbstractPolicy {
     }
 
     protected Set<Sensor<?>> getSensorsToTrack() {
-        return MutableSet.<Sensor<?>>builder()
+        return ImmutableSet.<Sensor<?>>builder()
                 .addAll(getRequiredConfig(SENSORS_TO_TRACK))
                 .add(Attributes.SERVICE_UP)
-                .buildImmutable();
+                .build();
     }
     
     /**

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/6f338897/utils/common/src/main/java/brooklyn/util/collections/MutableSet.java
----------------------------------------------------------------------
diff --git a/utils/common/src/main/java/brooklyn/util/collections/MutableSet.java b/utils/common/src/main/java/brooklyn/util/collections/MutableSet.java
index 6ab967a..f791949 100644
--- a/utils/common/src/main/java/brooklyn/util/collections/MutableSet.java
+++ b/utils/common/src/main/java/brooklyn/util/collections/MutableSet.java
@@ -111,9 +111,6 @@ public class MutableSet<V> extends LinkedHashSet<V> {
           return new MutableSet<V>(result);
         }
         
-        public ImmutableSet<V> buildImmutable() {
-            return ImmutableSet.copyOf(result);
-        }
     }
     
     public boolean addIfNotNull(V e) {


[50/50] [abbrv] git commit: Merge pull request #1407 from jdtoy/gs-update-master-squash

Posted by ri...@apache.org.
Merge pull request #1407 from jdtoy/gs-update-master-squash

Move to docs for 0.7.0. Includes YAML GS and new Location section.

Project: http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/commit/48df48a9
Tree: http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/tree/48df48a9
Diff: http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/diff/48df48a9

Branch: refs/heads/master
Commit: 48df48a966c7e92ecea98b773c9a74f724c155ed
Parents: 1c9ae92 bd0e1e0
Author: Alex Heneveld <al...@cloudsoftcorp.com>
Authored: Fri May 23 17:50:54 2014 +0100
Committer: Alex Heneveld <al...@cloudsoftcorp.com>
Committed: Fri May 23 17:50:54 2014 +0100

----------------------------------------------------------------------
 docs/_scripts/help.txt                          |  81 +-----------
 docs/use/guide/locations/index.md               |  35 +++--
 docs/use/guide/quickstart/brooklyn.properties   |  72 +++++-----
 ...cation-catalog-web-cluster-with-db-large.png | Bin 0 -> 131618 bytes
 ...talog-web-cluster-with-db-location-large.png | Bin 0 -> 152721 bytes
 ...ion-catalog-web-cluster-with-db-location.png | Bin 0 -> 86425 bytes
 ...-application-catalog-web-cluster-with-db.png | Bin 0 -> 76065 bytes
 .../images/add-application-modal-yaml.png       | Bin 0 -> 68401 bytes
 .../images/jboss7-cluster-policies-large.png    | Bin 0 -> 157883 bytes
 .../images/jboss7-cluster-policies.png          | Bin 0 -> 94056 bytes
 .../images/my-db-activities-large.png           | Bin 0 -> 208313 bytes
 .../quickstart/images/my-db-activities.png      | Bin 0 -> 130262 bytes
 .../images/my-web-cluster-starting.png          | Bin 0 -> 32948 bytes
 .../my-web-cluster-stop-confirm-large.png       | Bin 0 -> 148155 bytes
 .../images/my-web-cluster-stop-confirm.png      | Bin 0 -> 79280 bytes
 .../quickstart/images/my-web-summary-large.png  | Bin 0 -> 178785 bytes
 .../guide/quickstart/images/my-web-summary.png  | Bin 0 -> 80583 bytes
 docs/use/guide/quickstart/images/my-web.png     | Bin 0 -> 83081 bytes
 docs/use/guide/quickstart/index.md              | 130 ++++++++++---------
 docs/use/guide/quickstart/my-web-cluster.yaml   |  19 +++
 .../guide/quickstart/policies-and-catalogs.md   |  66 ++++++++++
 docs/use/guide/quickstart/toc.json              |   4 +
 docs/use/guide/toc.json                         |   5 +-
 23 files changed, 224 insertions(+), 188 deletions(-)
----------------------------------------------------------------------



[06/50] [abbrv] git commit: Covert DynamicClusterTest from groovy to java

Posted by ri...@apache.org.
Covert DynamicClusterTest from groovy to java


Project: http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/commit/d52e7ed2
Tree: http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/tree/d52e7ed2
Diff: http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/diff/d52e7ed2

Branch: refs/pull/1410/merge
Commit: d52e7ed2fe0c2aa623bcacee6dd4f3638e2c5647
Parents: d3d5c11
Author: Aled Sage <al...@gmail.com>
Authored: Wed May 21 12:07:53 2014 +0100
Committer: Aled Sage <al...@gmail.com>
Committed: Wed May 21 15:52:41 2014 +0100

----------------------------------------------------------------------
 .../entity/group/DynamicClusterTest.groovy      | 726 -----------------
 .../entity/group/DynamicClusterTest.java        | 815 +++++++++++++++++++
 2 files changed, 815 insertions(+), 726 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/d52e7ed2/core/src/test/java/brooklyn/entity/group/DynamicClusterTest.groovy
----------------------------------------------------------------------
diff --git a/core/src/test/java/brooklyn/entity/group/DynamicClusterTest.groovy b/core/src/test/java/brooklyn/entity/group/DynamicClusterTest.groovy
deleted file mode 100644
index 636abbc..0000000
--- a/core/src/test/java/brooklyn/entity/group/DynamicClusterTest.groovy
+++ /dev/null
@@ -1,726 +0,0 @@
-package brooklyn.entity.group
-
-import brooklyn.entity.basic.Attributes
-import brooklyn.entity.basic.Lifecycle
-
-import static org.testng.Assert.*
-
-import java.util.concurrent.CopyOnWriteArrayList
-import java.util.concurrent.CountDownLatch
-import java.util.concurrent.ExecutionException
-import java.util.concurrent.ExecutorService
-import java.util.concurrent.Executors
-import java.util.concurrent.TimeUnit
-import java.util.concurrent.atomic.AtomicInteger
-
-import org.testng.annotations.AfterMethod
-import org.testng.annotations.BeforeMethod
-import org.testng.annotations.Test
-
-import brooklyn.entity.Application
-import brooklyn.entity.Entity
-import brooklyn.entity.basic.ApplicationBuilder
-import brooklyn.entity.basic.BrooklynTaskTags
-import brooklyn.entity.basic.Entities
-import brooklyn.entity.proxying.EntitySpec
-import brooklyn.entity.trait.Changeable
-import brooklyn.location.Location
-import brooklyn.location.basic.SimulatedLocation
-import brooklyn.management.Task
-import brooklyn.test.TestUtils
-import brooklyn.test.entity.TestApplication
-import brooklyn.test.entity.TestEntity
-import brooklyn.test.entity.TestEntityImpl
-import brooklyn.util.GroovyJavaMethods
-import brooklyn.util.exceptions.Exceptions
-
-import com.google.common.base.Predicates
-import com.google.common.base.Throwables;
-import com.google.common.collect.ImmutableList
-import com.google.common.collect.ImmutableSet
-import com.google.common.collect.Iterables
-
-
-class DynamicClusterTest {
-
-    private static final int TIMEOUT_MS = 2000
-
-    TestApplication app
-    SimulatedLocation loc
-    SimulatedLocation loc2
-    Random random = new Random()
-
-    @BeforeMethod
-    public void setUp() {
-        app = ApplicationBuilder.newManagedApp(TestApplication.class);
-        loc = new SimulatedLocation()
-        loc2 = new SimulatedLocation()
-    }
-
-    @AfterMethod(alwaysRun = true)
-    public void tearDown(){
-        if (app != null) Entities.destroyAll(app.getManagementContext());
-    }
-
-    @Test
-    public void creationOkayWithoutNewEntityFactoryArgument() {
-        app.createAndManageChild(EntitySpec.create(DynamicCluster.class));
-    }
-
-    @Test
-    public void constructionRequiresThatNewEntityArgumentIsAnEntityFactory() {
-        try {
-            app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
-                    .configure("factory", "error"));
-            fail();
-        } catch (Exception e) {
-            if (Exceptions.getFirstThrowableOfType(e, IllegalArgumentException.class) == null) throw e;
-        }
-    }
-
-    @Test
-    public void startRequiresThatNewEntityArgumentIsGiven() {
-        DynamicCluster c = app.createAndManageChild(EntitySpec.create(DynamicCluster.class));
-        try {
-            c.start([loc]);
-            fail();
-        } catch (Exception e) {
-            if (Exceptions.getFirstThrowableOfType(e, IllegalStateException.class) == null) throw e;
-        }
-    }
-
-    @Test
-    public void startMethodFailsIfLocationsParameterHasMoreThanOneElement() {
-        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
-                .configure("factory", { new TestEntityImpl() }));
-        try {
-            cluster.start([ loc, loc2 ])
-            fail();
-        } catch (Exception e) {
-            if (Exceptions.getFirstThrowableOfType(e, IllegalArgumentException.class) == null) throw e;
-        }
-    }
-
-    @Test
-    public void testClusterHasOneLocationAfterStarting() {
-        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
-                .configure("factory", { new TestEntityImpl() }));
-        cluster.start([loc])
-        assertEquals(cluster.getLocations().size(), 1)
-        assertEquals(cluster.getLocations() as List, [loc])
-    }
-
-    @Test
-    public void testServiceUpAfterStartingWithNoMembers() {
-        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
-                .configure(DynamicCluster.MEMBER_SPEC, EntitySpec.create(TestEntity.class))
-                .configure(DynamicCluster.INITIAL_SIZE, 0))
-        cluster.start([loc])
-        assertEquals(cluster.getAttribute(Attributes.SERVICE_STATE), Lifecycle.RUNNING)
-        assertTrue(cluster.getAttribute(Attributes.SERVICE_UP))
-    }
-
-    @Test
-    public void usingEntitySpecResizeFromZeroToOneStartsANewEntityAndSetsItsParent() {
-        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
-                .configure("memberSpec", EntitySpec.create(TestEntity.class)));
-        
-        cluster.start([loc])
-
-        cluster.resize(1)
-        Entity entity = Iterables.getOnlyElement(cluster.getMembers());
-        assertEquals entity.count, 1
-        assertEquals entity.parent, cluster
-        assertEquals entity.application, app
-    }
-
-    @Test
-    public void resizeFromZeroToOneStartsANewEntityAndSetsItsParent() {
-        TestEntity entity
-        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
-                .configure("factory", { properties -> entity = new TestEntityImpl(properties) }));
-
-        cluster.start([loc])
-
-        cluster.resize(1)
-        assertEquals entity.counter.get(), 1
-        assertEquals entity.parent, cluster
-        assertEquals entity.application, app
-    }
-
-    @Test
-    public void currentSizePropertyReflectsActualClusterSize() {
-        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
-                .configure("factory", { properties -> return new TestEntityImpl(properties) }));
-
-        assertEquals cluster.currentSize, 0
-
-        cluster.start([loc])
-        assertEquals cluster.currentSize, 1
-        assertEquals cluster.getAttribute(Changeable.GROUP_SIZE), 1
-
-        int newSize = cluster.resize(0)
-        assertEquals newSize, 0
-        assertEquals newSize, cluster.currentSize
-        assertEquals newSize, cluster.members.size()
-        assertEquals newSize, cluster.getAttribute(Changeable.GROUP_SIZE)
-
-        newSize = cluster.resize(4)
-        assertEquals newSize, 4
-        assertEquals newSize, cluster.currentSize
-        assertEquals newSize, cluster.members.size()
-        assertEquals newSize, cluster.getAttribute(Changeable.GROUP_SIZE)
-
-        newSize = cluster.resize(0)
-        assertEquals newSize, 0
-        assertEquals newSize, cluster.currentSize
-        assertEquals newSize, cluster.members.size()
-        assertEquals newSize, cluster.getAttribute(Changeable.GROUP_SIZE)
-    }
-
-    @Test
-    public void clusterSizeAfterStartIsInitialSize() {
-        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
-                .configure("factory", { properties -> return new TestEntityImpl(properties) })
-                .configure("initialSize", 2));
-
-        cluster.start([loc])
-        assertEquals cluster.currentSize, 2
-        assertEquals cluster.members.size(), 2
-        assertEquals cluster.getAttribute(Changeable.GROUP_SIZE), 2
-    }
-
-    @Test
-    public void clusterLocationIsPassedOnToEntityStart() {
-        Collection<Location> locations = [ loc ]
-        TestEntity entity
-        def newEntity = { properties, cluster ->
-            entity = new TestEntityImpl(parent:cluster) {
-	            List<Location> stashedLocations = null
-	            @Override
-	            void start(Collection<? extends Location> loc) {
-	                super.start(loc)
-	                stashedLocations = loc
-	            }
-	        }
-        }
-        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
-                .configure("factory", newEntity)
-                .configure("initialSize", 1));
-
-        cluster.start(locations)
-
-        assertNotNull entity.stashedLocations
-        assertEquals entity.stashedLocations.size(), 1
-        assertEquals entity.stashedLocations[0], locations[0]
-    }
-
-    @Test
-    public void resizeFromOneToZeroChangesClusterSize() {
-        TestEntity entity
-        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
-                .configure("factory", { properties -> entity = new TestEntityImpl(properties) })
-                .configure("initialSize", 1));
-
-        cluster.start([loc])
-        assertEquals cluster.currentSize, 1
-        assertEquals entity.counter.get(), 1
-        cluster.resize(0)
-        assertEquals cluster.currentSize, 0
-        assertEquals entity.counter.get(), 0
-    }
-
-    @Test
-    public void concurrentResizesToSameNumberCreatesCorrectNumberOfNodes() {
-        final int OVERHEAD_MS = 500
-        final int STARTUP_TIME_MS = 50
-        final AtomicInteger numStarted = new AtomicInteger(0)
-        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
-                .configure("factory", { 
-                    Map flags, Entity cluster -> 
-                    Thread.sleep(STARTUP_TIME_MS); numStarted.incrementAndGet(); new TestEntityImpl(flags, cluster)
-                }));
-
-        assertEquals cluster.currentSize, 0
-        cluster.start([loc])
-
-        ExecutorService executor = Executors.newCachedThreadPool()
-        List<Throwable> throwables = new CopyOnWriteArrayList<Throwable>()
-
-        try {
-            for (int i in 1..10) {
-                executor.submit( {
-                    try {
-                        cluster.resize(2)
-                    } catch (Throwable e) {
-                        throwables.add(e)
-                    }
-                })
-            }
-
-            executor.shutdown()
-            assertTrue(executor.awaitTermination(10*STARTUP_TIME_MS+OVERHEAD_MS, TimeUnit.MILLISECONDS))
-            if (throwables.size() > 0) throw throwables.get(0)
-            assertEquals(cluster.currentSize, 2)
-            assertEquals(cluster.getAttribute(Changeable.GROUP_SIZE), 2)
-            assertEquals(numStarted.get(), 2)
-        } finally {
-            executor.shutdownNow();
-        }
-    }
-
-    @Test(enabled = false)
-    public void stoppingTheClusterStopsTheEntity() {
-        TestEntity entity
-        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
-                .configure("factory", { properties -> entity = new TestEntityImpl(properties) })
-                .configure("initialSize", 1));
-
-        cluster.start([loc])
-        assertEquals entity.counter.get(), 1
-        cluster.stop()
-        assertEquals entity.counter.get(), 0
-    }
-
-    /**
-     * This tests the fix for ENGR-1826.
-     */
-    @Test
-    public void failingEntitiesDontBreakClusterActions() {
-        final int failNum = 2
-        final AtomicInteger counter = new AtomicInteger(0)
-        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
-                .configure("initialSize", 0)
-                .configure("factory", { properties ->
-                    int num = counter.incrementAndGet();
-                    return new FailingEntity(properties, (num==failNum))
-                }));
-
-        cluster.start([loc])
-        cluster.resize(3)
-        assertEquals(cluster.currentSize, 2)
-        assertEquals(cluster.getMembers().size(), 2)
-        for (Entity member : cluster.getMembers()) {
-            assertFalse(((FailingEntity)member).failOnStart)
-        }
-    }
-
-    @Test
-    public void testInitialQuorumSizeSufficientForStartup() {
-        final int failNum = 1;
-        final AtomicInteger counter = new AtomicInteger(0)
-        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
-                .configure("initialSize", 2)
-                .configure(DynamicCluster.INITIAL_QUORUM_SIZE, 1)
-                .configure("factory", { properties ->
-                    int num = counter.incrementAndGet();
-                    return new FailingEntity(properties, (num==failNum))
-                }));
-
-        cluster.start([loc])
-        
-        // note that children include quarantine group; and quarantined nodes
-        assertEquals(cluster.getCurrentSize(), 1)
-        assertEquals(cluster.getMembers().size(), 1)
-        for (Entity member : cluster.getMembers()) {
-            assertFalse(((FailingEntity)member).failOnStart)
-        }
-    }
-
-    @Test
-    public void testInitialQuorumSizeDefaultsToInitialSize() throws Exception {
-        final int failNum = 1;
-        final AtomicInteger counter = new AtomicInteger(0)
-        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
-                .configure("initialSize", 2)
-                .configure("factory", { properties ->
-                    int num = counter.incrementAndGet();
-                    return new FailingEntity(properties, (num==failNum))
-                }));
-
-        try {
-            cluster.start([loc])
-        } catch (Exception e) {
-            IllegalStateException unwrapped = Exceptions.getFirstThrowableOfType(e, IllegalStateException.class);
-            if (unwrapped != null && unwrapped.getMessage().contains("failed to get to initial size")) {
-                // success
-            } else {
-                throw e; // fail
-            }
-        }
-        
-        // note that children include quarantine group; and quarantined nodes
-        assertEquals(cluster.getCurrentSize(), 1)
-        assertEquals(cluster.getMembers().size(), 1)
-        for (Entity member : cluster.getMembers()) {
-            assertFalse(((FailingEntity)member).failOnStart)
-        }
-    }
-
-    @Test
-    public void testCanQuarantineFailedEntities() {
-        final int failNum = 2
-        final AtomicInteger counter = new AtomicInteger(0)
-        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
-                .configure("quarantineFailedEntities", true)
-                .configure("initialSize", 0)
-                .configure("factory", { properties ->
-                    int num = counter.incrementAndGet();
-                    return new FailingEntity(properties, (num==failNum))
-                }));
-
-        cluster.start([loc])
-        cluster.resize(3)
-        assertEquals(cluster.currentSize, 2)
-        assertEquals(cluster.getMembers().size(), 2)
-        assertEquals(Iterables.size(Iterables.filter(cluster.getChildren(), Predicates.instanceOf(FailingEntity.class))), 3)
-        cluster.members.each {
-            assertFalse(((FailingEntity)it).failOnStart)
-        }
-
-        assertEquals(cluster.getAttribute(DynamicCluster.QUARANTINE_GROUP).members.size(), 1)
-        cluster.getAttribute(DynamicCluster.QUARANTINE_GROUP).members.each {
-            assertTrue(((FailingEntity)it).failOnStart)
-        }
-    }
-
-    @Test
-    public void testDoNotQuarantineFailedEntities() {
-        final int failNum = 2
-        final AtomicInteger counter = new AtomicInteger(0)
-        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
-                // default is quarantineFailedEntities==true
-                .configure("quarantineFailedEntities", false)
-                .configure("initialSize", 0)
-                .configure("factory", { properties ->
-                    int num = counter.incrementAndGet();
-                    return new FailingEntity(properties, (num==failNum))
-                }));
-
-        cluster.start([loc])
-        
-        // no quarantine group, as a child
-        assertEquals(cluster.getChildren().size(), 0, "children="+cluster.getChildren())
-        
-        // Failed node will not be a member or child
-        cluster.resize(3)
-        assertEquals(cluster.currentSize, 2)
-        assertEquals(cluster.getMembers().size(), 2)
-        assertEquals(cluster.getChildren().size(), 2, "children="+cluster.getChildren())
-        
-        // Failed node will not be managed either
-        assertEquals(Iterables.size(Iterables.filter(cluster.getChildren(), Predicates.instanceOf(FailingEntity.class))), 2)
-        for (Entity member : cluster.getMembers()) {
-            assertFalse(((FailingEntity)member).failOnStart)
-        }
-    }
-
-    @Test
-    public void defaultRemovalStrategyShutsDownNewestFirstWhenResizing() {
-        TestEntity entity
-        final int failNum = 2
-        final List<Entity> creationOrder = []
-        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
-                .configure("initialSize", 0)
-                .configure("factory", { properties ->
-                    Entity result = new TestEntityImpl(properties)
-                    creationOrder << result
-                    return result
-                }));
-
-        cluster.start([loc])
-        cluster.resize(1)
-        cluster.resize(2)
-        assertEquals(cluster.currentSize, 2)
-        assertEquals(ImmutableSet.copyOf(cluster.getMembers()), ImmutableSet.copyOf(creationOrder), "actual="+cluster.getMembers())
-
-        // Now stop one
-        cluster.resize(1)
-        assertEquals(cluster.currentSize, 1)
-        assertEquals(ImmutableList.copyOf(cluster.getMembers()), creationOrder.subList(0, 1))
-    }
-
-    @Test
-    public void resizeLoggedAsEffectorCall() {
-        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
-                .configure("factory", { properties -> return new TestEntityImpl(properties) }));
-
-        app.start([loc])
-        cluster.resize(1)
-
-        Set<Task> tasks = app.getManagementContext().getExecutionManager().getTasksWithAllTags([
-            BrooklynTaskTags.tagForContextEntity(cluster),"EFFECTOR"])
-        assertEquals(tasks.size(), 2)
-        assertTrue(Iterables.get(tasks, 0).getDescription().contains("start"))
-        assertTrue(Iterables.get(tasks, 1).getDescription().contains("resize"))
-    }
-
-    @Test
-    public void testStoppedChildIsRemoveFromGroup() {
-        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
-                .configure("initialSize", 1)
-                .configure("factory", { properties -> return new TestEntityImpl(properties) }));
-
-        cluster.start([loc])
-
-        TestEntity child = Iterables.get(cluster.getMembers(), 0);
-        child.stop()
-        Entities.unmanage(child)
-
-        TestUtils.executeUntilSucceeds(timeout:TIMEOUT_MS) {
-            assertFalse(cluster.getChildren().contains(child), "children="+cluster.getChildren())
-            assertEquals(cluster.currentSize, 0)
-            assertEquals(cluster.members.size(), 0)
-        }
-    }
-
-    @Test
-    public void testPluggableRemovalStrategyIsUsed() {
-        List<Entity> removedEntities = []
-
-        Closure removalStrategy = { Collection<Entity> contenders ->
-            Entity choice = Iterables.get(contenders, random.nextInt(contenders.size()))
-            removedEntities.add(choice)
-            return choice
-        }
-        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
-                .configure("factory", { properties -> return new TestEntityImpl(properties) })
-                .configure("initialSize", 10)
-                .configure("removalStrategy", removalStrategy));
-
-        cluster.start([loc])
-        Set origMembers = cluster.members as Set
-
-        for (int i = 10; i >= 0; i--) {
-            cluster.resize(i)
-            assertEquals(cluster.getAttribute(Changeable.GROUP_SIZE), i)
-            assertEquals(removedEntities.size(), 10-i)
-            assertEquals(ImmutableSet.copyOf(Iterables.concat(cluster.members, removedEntities)), origMembers)
-        }
-    }
-
-    @Test
-    public void testPluggableRemovalStrategyCanBeSetAfterConstruction() {
-        List<Entity> removedEntities = []
-
-        Closure removalStrategy = { Collection<Entity> contenders ->
-            Entity choice = Iterables.get(contenders, random.nextInt(contenders.size()))
-            removedEntities.add(choice)
-            return choice
-        }
-        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
-                .configure("factory", { properties -> return new TestEntityImpl(properties) })
-                .configure("initialSize", 10));
-
-        cluster.start([loc])
-        Set origMembers = cluster.members as Set
-
-        cluster.setRemovalStrategy(GroovyJavaMethods.functionFromClosure(removalStrategy));
-
-        for (int i = 10; i >= 0; i--) {
-            cluster.resize(i)
-            assertEquals(cluster.getAttribute(Changeable.GROUP_SIZE), i)
-            assertEquals(removedEntities.size(), 10-i)
-            assertEquals(ImmutableSet.copyOf(Iterables.concat(cluster.members, removedEntities)), origMembers)
-        }
-    }
-
-    @Test
-    public void testResizeDoesNotBlockCallsToQueryGroupMembership() {
-        CountDownLatch executingLatch = new CountDownLatch(1)
-        CountDownLatch continuationLatch = new CountDownLatch(1)
-        
-        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
-                .configure("initialSize", 0)
-                .configure("factory", { properties ->
-                        executingLatch.countDown()
-                        continuationLatch.await()
-                        return new TestEntityImpl(properties)
-                    }));
-
-        cluster.start([loc])
-
-        Thread thread = new Thread( { cluster.resize(1) })
-        try {
-            // wait for resize to be executing
-            thread.start()
-            executingLatch.await(TIMEOUT_MS, TimeUnit.MILLISECONDS)
-
-            // ensure can still call methods on group, to query/update membership
-            assertEquals(cluster.getMembers(), [])
-            assertEquals(cluster.getCurrentSize(), 0)
-            assertFalse(cluster.hasMember(cluster))
-            cluster.addMember(cluster)
-            assertTrue(cluster.removeMember(cluster))
-
-            // allow the resize to complete
-            continuationLatch.countDown()
-            thread.join(TIMEOUT_MS)
-            assertFalse(thread.isAlive())
-        } finally {
-            thread.interrupt()
-        }
-    }
-
-    @Test
-    public void testReplacesMember() {
-        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
-                .configure("initialSize", 1)
-                .configure("factory", { properties -> return new TestEntityImpl(properties) }));
-
-        cluster.start([loc])
-        Entity member = Iterables.get(cluster.members, 0);
-
-        String replacementId = cluster.replaceMember(member.getId());
-        Entity replacement = cluster.getManagementContext().getEntityManager().getEntity(replacementId);
-
-        assertEquals(cluster.members.size(), 1)
-        assertFalse(cluster.members.contains(member))
-        assertFalse(cluster.children.contains(member))
-        assertNotNull(replacement, "replacementId="+replacementId);
-        assertTrue(cluster.members.contains(replacement), "replacement="+replacement+"; members="+cluster.members);
-        assertTrue(cluster.children.contains(replacement), "replacement="+replacement+"; children="+cluster.children);
-    }
-
-    @Test
-    public void testReplaceMemberThrowsIfMemberIdDoesNotResolve() {
-        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
-                .configure("initialSize", 1)
-                .configure("factory", { properties -> return new TestEntityImpl(properties) }));
-
-        cluster.start([loc])
-        Entity member = Iterables.get(cluster.members, 0);
-
-        try {
-            cluster.replaceMember("wrong.id");
-            fail();
-        } catch (Exception e) {
-            if (Exceptions.getFirstThrowableOfType(e, NoSuchElementException.class) == null) throw e;
-            if (!Exceptions.getFirstThrowableOfType(e, NoSuchElementException.class).getMessage().contains("entity wrong.id cannot be resolved")) throw e;
-        }
-
-        assertEquals(cluster.members as Set, ImmutableSet.of(member));
-    }
-
-    @Test
-    public void testReplaceMemberThrowsIfNotMember() {
-        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
-                .configure("initialSize", 1)
-                .configure("factory", { properties -> return new TestEntityImpl(properties) }));
-
-        cluster.start([loc])
-        Entity member = Iterables.get(cluster.members, 0);
-
-        try {
-            cluster.replaceMember(app.getId());
-            fail();
-        } catch (Exception e) {
-            if (Exceptions.getFirstThrowableOfType(e, NoSuchElementException.class) == null) throw e;
-            if (!Exceptions.getFirstThrowableOfType(e, NoSuchElementException.class).getMessage().contains("is not a member")) throw e;
-        }
-
-        assertEquals(cluster.members as Set, ImmutableSet.of(member));
-    }
-
-    @Test
-    public void testReplaceMemberFailsIfCantProvisionReplacement() {
-        final int failNum = 2
-        final AtomicInteger counter = new AtomicInteger(0)
-        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
-                .configure("factory", { properties -> 
-                    int num = counter.incrementAndGet();
-                    return new FailingEntity(properties, (num==failNum))
-                }));
-
-        cluster.start([loc])
-        Entity member = Iterables.get(cluster.members, 0);
-
-        try {
-            cluster.replaceMember(member.getId());
-            fail();
-        } catch (Exception e) {
-            if (!e.toString().contains("failed to grow")) throw e;
-            if (Exceptions.getFirstThrowableOfType(e, NoSuchElementException.class) != null) throw e;
-        }
-        assertEquals(cluster.members as Set, ImmutableSet.of(member));
-    }
-
-    @Test
-    public void testReplaceMemberRemovesAndThowsIfFailToStopOld() {
-        final int failNum = 1
-        final AtomicInteger counter = new AtomicInteger(0)
-        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
-                .configure("initialSize", 1)
-                .configure("factory", { properties ->
-                    int num = counter.incrementAndGet();
-                    return new FailingEntity(properties, false, (num==failNum), IllegalStateException.class)
-                }));
-
-        cluster.start([loc])
-        Entity member = Iterables.get(cluster.members, 0);
-
-        try {
-            cluster.replaceMember(member.getId());
-            fail();
-        } catch (Exception e) {
-            if (Exceptions.getFirstThrowableOfType(e, StopFailedRuntimeException.class) == null) throw e;
-            boolean found = false;
-            for (Throwable t : Throwables.getCausalChain(e)) {
-                if (t.toString().contains("Simulating entity stop failure")) {
-                    found = true;
-                    break;
-                }
-            }
-            if (!found) throw e;
-        }
-        assertFalse(Entities.isManaged(member));
-        assertEquals(cluster.members.size(), 1);
-    }
-
-    private Throwable unwrapException(Throwable e) {
-        if (e instanceof ExecutionException) {
-            return unwrapException(e.cause)
-        } else if (e instanceof org.codehaus.groovy.runtime.InvokerInvocationException) {
-            return unwrapException(e.cause)
-        } else {
-            return e
-        }
-    }
-}
-
-class FailingEntity extends TestEntityImpl {
-    final boolean failOnStart;
-    final boolean failOnStop;
-    final Class<? extends Exception> exceptionClazz;
-
-    public FailingEntity(Map flags, boolean failOnStart) {
-        this(flags, failOnStart, false);
-    }
-    
-    public FailingEntity(Map flags, boolean failOnStart, boolean failOnStop) {
-        this(flags, failOnStart, failOnStop, IllegalStateException.class);
-    }
-    
-    public FailingEntity(Map flags, boolean failOnStart, boolean failOnStop, Class<? extends Exception> exceptionClazz) {
-        super(flags)
-        this.failOnStart = failOnStart;
-        this.failOnStop = failOnStop;
-        this.exceptionClazz = exceptionClazz;
-    }
-    
-    @Override
-    public void start(Collection<? extends Location> locs) {
-        if (failOnStart) {
-            Exception e = exceptionClazz.getConstructor(String.class).newInstance("Simulating entity start failure for test");
-            throw e;
-        }
-    }
-    
-    @Override
-    public void stop() {
-        if (failOnStop) {
-            Exception e = exceptionClazz.getConstructor(String.class).newInstance("Simulating entity stop failure for test");
-            throw e;
-        }
-    }
-}

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/d52e7ed2/core/src/test/java/brooklyn/entity/group/DynamicClusterTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/brooklyn/entity/group/DynamicClusterTest.java b/core/src/test/java/brooklyn/entity/group/DynamicClusterTest.java
new file mode 100644
index 0000000..9fb9230
--- /dev/null
+++ b/core/src/test/java/brooklyn/entity/group/DynamicClusterTest.java
@@ -0,0 +1,815 @@
+package brooklyn.entity.group;
+
+import static org.testng.Assert.assertEquals;
+import static org.testng.Assert.assertFalse;
+import static org.testng.Assert.assertNotNull;
+import static org.testng.Assert.assertTrue;
+import static org.testng.Assert.fail;
+
+import java.util.Collection;
+import java.util.List;
+import java.util.Map;
+import java.util.NoSuchElementException;
+import java.util.Random;
+import java.util.Set;
+import java.util.concurrent.CopyOnWriteArrayList;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.concurrent.atomic.AtomicReference;
+
+import org.testng.annotations.AfterMethod;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.Test;
+
+import brooklyn.entity.Entity;
+import brooklyn.entity.basic.ApplicationBuilder;
+import brooklyn.entity.basic.Attributes;
+import brooklyn.entity.basic.BrooklynTaskTags;
+import brooklyn.entity.basic.Entities;
+import brooklyn.entity.basic.EntityFactory;
+import brooklyn.entity.basic.Lifecycle;
+import brooklyn.entity.proxying.EntitySpec;
+import brooklyn.entity.trait.Changeable;
+import brooklyn.location.Location;
+import brooklyn.location.basic.SimulatedLocation;
+import brooklyn.management.Task;
+import brooklyn.test.Asserts;
+import brooklyn.test.entity.TestApplication;
+import brooklyn.test.entity.TestEntity;
+import brooklyn.test.entity.TestEntityImpl;
+import brooklyn.util.collections.MutableMap;
+import brooklyn.util.exceptions.Exceptions;
+import brooklyn.util.time.Time;
+
+import com.google.common.base.Function;
+import com.google.common.base.Predicates;
+import com.google.common.base.Throwables;
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.ImmutableSet;
+import com.google.common.collect.Iterables;
+import com.google.common.collect.Lists;
+import com.google.common.util.concurrent.Atomics;
+
+
+public class DynamicClusterTest {
+
+    private static final int TIMEOUT_MS = 2000;
+
+    TestApplication app;
+    SimulatedLocation loc;
+    SimulatedLocation loc2;
+    Random random = new Random();
+
+    @BeforeMethod
+    public void setUp() {
+        app = ApplicationBuilder.newManagedApp(TestApplication.class);
+        loc = new SimulatedLocation();
+        loc2 = new SimulatedLocation();
+    }
+
+    @AfterMethod(alwaysRun = true)
+    public void tearDown(){
+        if (app != null) Entities.destroyAll(app.getManagementContext());
+    }
+
+    @Test
+    public void creationOkayWithoutNewEntityFactoryArgument() throws Exception {
+        app.createAndManageChild(EntitySpec.create(DynamicCluster.class));
+    }
+
+    @Test
+    public void constructionRequiresThatNewEntityArgumentIsAnEntityFactory() throws Exception {
+        try {
+            app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
+                    .configure("factory", "error"));
+            fail();
+        } catch (Exception e) {
+            if (Exceptions.getFirstThrowableOfType(e, IllegalArgumentException.class) == null) throw e;
+        }
+    }
+
+    @Test
+    public void startRequiresThatNewEntityArgumentIsGiven() throws Exception {
+        DynamicCluster c = app.createAndManageChild(EntitySpec.create(DynamicCluster.class));
+        try {
+            c.start(ImmutableList.of(loc));
+            fail();
+        } catch (Exception e) {
+            if (Exceptions.getFirstThrowableOfType(e, IllegalStateException.class) == null) throw e;
+        }
+    }
+
+    @Test
+    public void startMethodFailsIfLocationsParameterHasMoreThanOneElement() throws Exception {
+        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
+                .configure(DynamicCluster.MEMBER_SPEC, EntitySpec.create(TestEntity.class)));
+        try {
+            cluster.start(ImmutableList.of(loc, loc2));
+            fail();
+        } catch (Exception e) {
+            if (Exceptions.getFirstThrowableOfType(e, IllegalArgumentException.class) == null) throw e;
+        }
+    }
+
+    @Test
+    public void testClusterHasOneLocationAfterStarting() throws Exception {
+        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
+                .configure(DynamicCluster.MEMBER_SPEC, EntitySpec.create(TestEntity.class)));
+        cluster.start(ImmutableList.of(loc));
+        assertEquals(cluster.getLocations().size(), 1);
+        assertEquals(ImmutableList.copyOf(cluster.getLocations()), ImmutableList.of(loc));
+    }
+
+    @Test
+    public void testServiceUpAfterStartingWithNoMembers() throws Exception {
+        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
+                .configure(DynamicCluster.MEMBER_SPEC, EntitySpec.create(TestEntity.class))
+                .configure(DynamicCluster.INITIAL_SIZE, 0));
+        cluster.start(ImmutableList.of(loc));
+        assertEquals(cluster.getAttribute(Attributes.SERVICE_STATE), Lifecycle.RUNNING);
+        assertTrue(cluster.getAttribute(Attributes.SERVICE_UP));
+    }
+
+    @Test
+    public void usingEntitySpecResizeFromZeroToOneStartsANewEntityAndSetsItsParent() throws Exception {
+        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
+                .configure("memberSpec", EntitySpec.create(TestEntity.class)));
+        
+        cluster.start(ImmutableList.of(loc));
+
+        cluster.resize(1);
+        TestEntity entity = (TestEntity) Iterables.getOnlyElement(cluster.getMembers());
+        assertEquals(entity.getCount(), 1);
+        assertEquals(entity.getParent(), cluster);
+        assertEquals(entity.getApplication(), app);
+    }
+
+    @Test
+    public void resizeFromZeroToOneStartsANewEntityAndSetsItsParent() throws Exception {
+        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
+                .configure("factory", new EntityFactory() {
+                    @Override public Entity newEntity(Map flags, Entity parent) {
+                        return new TestEntityImpl(flags);
+                    }}));
+
+        cluster.start(ImmutableList.of(loc));
+
+        cluster.resize(1);
+        TestEntity entity = (TestEntity) Iterables.get(cluster.getMembers(), 0);
+        assertEquals(entity.getCounter().get(), 1);
+        assertEquals(entity.getParent(), cluster);
+        assertEquals(entity.getApplication(), app);
+    }
+
+    @Test
+    public void currentSizePropertyReflectsActualClusterSize() throws Exception {
+        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
+                .configure("factory", new EntityFactory() {
+                    @Override public Entity newEntity(Map flags, Entity parent) {
+                        return new TestEntityImpl(flags);
+                    }}));
+
+
+        assertEquals(cluster.getCurrentSize(), (Integer)0);
+
+        cluster.start(ImmutableList.of(loc));
+        assertEquals(cluster.getCurrentSize(), (Integer)1);
+        assertEquals(cluster.getAttribute(Changeable.GROUP_SIZE), (Integer)1);
+
+        int newSize = cluster.resize(0);
+        assertEquals(newSize, 0);
+        assertEquals((Integer)newSize, cluster.getCurrentSize());
+        assertEquals(newSize, cluster.getMembers().size());
+        assertEquals((Integer)newSize, cluster.getAttribute(Changeable.GROUP_SIZE));
+
+        newSize = cluster.resize(4);
+        assertEquals(newSize, 4);
+        assertEquals((Integer)newSize, cluster.getCurrentSize());
+        assertEquals(newSize, cluster.getMembers().size());
+        assertEquals((Integer)newSize, cluster.getAttribute(Changeable.GROUP_SIZE));
+
+        newSize = cluster.resize(0);
+        assertEquals(newSize, 0);
+        assertEquals((Integer)newSize, cluster.getCurrentSize());
+        assertEquals(newSize, cluster.getMembers().size());
+        assertEquals((Integer)newSize, cluster.getAttribute(Changeable.GROUP_SIZE));
+    }
+
+    @Test
+    public void clusterSizeAfterStartIsInitialSize() throws Exception {
+        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
+                .configure("factory", new EntityFactory() {
+                    @Override public Entity newEntity(Map flags, Entity parent) {
+                        return new TestEntityImpl(flags);
+                    }})
+                .configure("initialSize", 2));
+
+        cluster.start(ImmutableList.of(loc));
+        assertEquals(cluster.getCurrentSize(), (Integer)2);
+        assertEquals(cluster.getMembers().size(), 2);
+        assertEquals(cluster.getAttribute(Changeable.GROUP_SIZE), (Integer)2);
+    }
+
+    @Test
+    public void clusterLocationIsPassedOnToEntityStart() throws Exception {
+        List<SimulatedLocation> locations = ImmutableList.of(loc);
+        final AtomicReference<Collection<? extends Location>> stashedLocations = Atomics.newReference();
+        
+        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
+                .configure("factory", new EntityFactory() {
+                    @Override public Entity newEntity(Map flags, Entity parent) {
+                        return new TestEntityImpl(parent) {
+                            @Override
+                            public void start(Collection<? extends Location> loc) {
+                                super.start(loc);
+                                stashedLocations.set(loc);
+                            }
+                        };
+                    }})
+                .configure("initialSize", 1));
+
+        cluster.start(locations);
+        TestEntity entity = (TestEntity) Iterables.get(cluster.getMembers(), 0);
+        
+        assertNotNull(stashedLocations.get());
+        assertEquals(stashedLocations.get().size(), 1);
+        assertEquals(ImmutableList.copyOf(stashedLocations.get()), locations);
+    }
+
+    @Test
+    public void resizeFromOneToZeroChangesClusterSize() throws Exception {
+        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
+                .configure("factory", new EntityFactory() {
+                    @Override public Entity newEntity(Map flags, Entity parent) {
+                        return new TestEntityImpl(flags);
+                    }})
+                .configure("initialSize", 1));
+
+        cluster.start(ImmutableList.of(loc));
+        TestEntity entity = (TestEntity) Iterables.get(cluster.getMembers(), 0);
+        assertEquals(cluster.getCurrentSize(), (Integer)1);
+        assertEquals(entity.getCounter().get(), 1);
+        
+        cluster.resize(0);
+        assertEquals(cluster.getCurrentSize(), (Integer)0);
+        assertEquals(entity.getCounter().get(), 0);
+    }
+
+    @Test
+    public void concurrentResizesToSameNumberCreatesCorrectNumberOfNodes() throws Exception {
+        final int OVERHEAD_MS = 500;
+        final int STARTUP_TIME_MS = 50;
+        final AtomicInteger numStarted = new AtomicInteger(0);
+        final DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
+                .configure("factory", new EntityFactory() {
+                    @Override public Entity newEntity(Map flags, Entity parent) {
+                        Time.sleep(STARTUP_TIME_MS);
+                        numStarted.incrementAndGet();
+                        return new TestEntityImpl(flags, parent);
+                    }}));
+
+        assertEquals(cluster.getCurrentSize(), (Integer)0);
+        cluster.start(ImmutableList.of(loc));
+
+        ExecutorService executor = Executors.newCachedThreadPool();
+        final List<Throwable> throwables = new CopyOnWriteArrayList<Throwable>();
+
+        try {
+            for (int i = 0; i < 10; i++) {
+                executor.submit(new Runnable() {
+                    public void run() {
+                        try {
+                            cluster.resize(2);
+                        } catch (Throwable e) {
+                            throwables.add(e);
+                        }
+                    }});
+            }
+
+            executor.shutdown();
+            assertTrue(executor.awaitTermination(10*STARTUP_TIME_MS+OVERHEAD_MS, TimeUnit.MILLISECONDS));
+            if (throwables.size() > 0) throw Exceptions.propagate(throwables.get(0));
+            assertEquals(cluster.getCurrentSize(), (Integer)2);
+            assertEquals(cluster.getAttribute(Changeable.GROUP_SIZE), (Integer)2);
+            assertEquals(numStarted.get(), 2);
+        } finally {
+            executor.shutdownNow();
+        }
+    }
+
+    @Test(enabled = false)
+    public void stoppingTheClusterStopsTheEntity() throws Exception {
+        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
+                .configure("factory", new EntityFactory() {
+                    @Override public Entity newEntity(Map flags, Entity parent) {
+                        return new TestEntityImpl(flags);
+                    }})
+                .configure("initialSize", 1));
+
+        cluster.start(ImmutableList.of(loc));
+        TestEntity entity = (TestEntity) Iterables.get(cluster.getMembers(), 0);
+        
+        assertEquals(entity.getCounter().get(), 1);
+        cluster.stop();
+        assertEquals(entity.getCounter().get(), 0);
+    }
+
+    /**
+     * This tests the fix for ENGR-1826.
+     */
+    @Test
+    public void failingEntitiesDontBreakClusterActions() throws Exception {
+        final int failNum = 2;
+        final AtomicInteger counter = new AtomicInteger(0);
+        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
+                .configure("initialSize", 0)
+                .configure("factory", new EntityFactory() {
+                    @Override public Entity newEntity(Map flags, Entity parent) {
+                        int num = counter.incrementAndGet();
+                        return new FailingEntity(flags, (num==failNum));
+                    }}));
+
+        cluster.start(ImmutableList.of(loc));
+        cluster.resize(3);
+        assertEquals(cluster.getCurrentSize(), (Integer)2);
+        assertEquals(cluster.getMembers().size(), 2);
+        for (Entity member : cluster.getMembers()) {
+            assertFalse(((FailingEntity)member).failOnStart);
+        }
+    }
+
+    @Test
+    public void testInitialQuorumSizeSufficientForStartup() throws Exception {
+        final int failNum = 1;
+        final AtomicInteger counter = new AtomicInteger(0);
+        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
+                .configure("initialSize", 2)
+                .configure(DynamicCluster.INITIAL_QUORUM_SIZE, 1)
+                .configure("factory", new EntityFactory() {
+                    @Override public Entity newEntity(Map flags, Entity parent) {
+                        int num = counter.incrementAndGet();
+                        return new FailingEntity(flags, (num==failNum));
+                    }}));
+
+        cluster.start(ImmutableList.of(loc));
+        
+        // note that children include quarantine group; and quarantined nodes
+        assertEquals(cluster.getCurrentSize(), (Integer)1);
+        assertEquals(cluster.getMembers().size(), 1);
+        for (Entity member : cluster.getMembers()) {
+            assertFalse(((FailingEntity)member).failOnStart);
+        }
+    }
+
+    @Test
+    public void testInitialQuorumSizeDefaultsToInitialSize() throws Exception {
+        final int failNum = 1;
+        final AtomicInteger counter = new AtomicInteger(0);
+        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
+                .configure("initialSize", 2)
+                .configure("factory", new EntityFactory() {
+                    @Override public Entity newEntity(Map flags, Entity parent) {
+                        int num = counter.incrementAndGet();
+                        return new FailingEntity(flags, (num==failNum));
+                    }}));
+
+        try {
+            cluster.start(ImmutableList.of(loc));
+        } catch (Exception e) {
+            IllegalStateException unwrapped = Exceptions.getFirstThrowableOfType(e, IllegalStateException.class);
+            if (unwrapped != null && unwrapped.getMessage().contains("failed to get to initial size")) {
+                // success
+            } else {
+                throw e; // fail
+            }
+        }
+        
+        // note that children include quarantine group; and quarantined nodes
+        assertEquals(cluster.getCurrentSize(), (Integer)1);
+        assertEquals(cluster.getMembers().size(), 1);
+        for (Entity member : cluster.getMembers()) {
+            assertFalse(((FailingEntity)member).failOnStart);
+        }
+    }
+
+    @Test
+    public void testCanQuarantineFailedEntities() throws Exception {
+        final int failNum = 2;
+        final AtomicInteger counter = new AtomicInteger(0);
+        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
+                .configure("quarantineFailedEntities", true)
+                .configure("initialSize", 0)
+                .configure("factory", new EntityFactory() {
+                    @Override public Entity newEntity(Map flags, Entity parent) {
+                        int num = counter.incrementAndGet();
+                        return new FailingEntity(flags, (num==failNum));
+                    }}));
+
+        cluster.start(ImmutableList.of(loc));
+        cluster.resize(3);
+        assertEquals(cluster.getCurrentSize(), (Integer)2);
+        assertEquals(cluster.getMembers().size(), 2);
+        assertEquals(Iterables.size(Iterables.filter(cluster.getChildren(), Predicates.instanceOf(FailingEntity.class))), 3);
+        for (Entity it : cluster.getMembers()) {
+            assertFalse(((FailingEntity)it).failOnStart);
+        }
+
+        assertEquals(cluster.getAttribute(DynamicCluster.QUARANTINE_GROUP).getMembers().size(), 1);
+        for (Entity it : cluster.getAttribute(DynamicCluster.QUARANTINE_GROUP).getMembers()) {
+            assertTrue(((FailingEntity)it).failOnStart);
+        }
+    }
+
+    @Test
+    public void testDoNotQuarantineFailedEntities() throws Exception {
+        final int failNum = 2;
+        final AtomicInteger counter = new AtomicInteger(0);
+        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
+                // default is quarantineFailedEntities==true
+                .configure("quarantineFailedEntities", false)
+                .configure("initialSize", 0)
+                .configure("factory", new EntityFactory() {
+                    @Override public Entity newEntity(Map flags, Entity parent) {
+                        int num = counter.incrementAndGet();
+                        return new FailingEntity(flags, (num==failNum));
+                    }}));
+
+        cluster.start(ImmutableList.of(loc));
+        
+        // no quarantine group, as a child
+        assertEquals(cluster.getChildren().size(), 0, "children="+cluster.getChildren());
+        
+        // Failed node will not be a member or child
+        cluster.resize(3);
+        assertEquals(cluster.getCurrentSize(), (Integer)2);
+        assertEquals(cluster.getMembers().size(), 2);
+        assertEquals(cluster.getChildren().size(), 2, "children="+cluster.getChildren());
+        
+        // Failed node will not be managed either
+        assertEquals(Iterables.size(Iterables.filter(cluster.getChildren(), Predicates.instanceOf(FailingEntity.class))), 2);
+        for (Entity member : cluster.getMembers()) {
+            assertFalse(((FailingEntity)member).failOnStart);
+        }
+    }
+
+    @Test
+    public void defaultRemovalStrategyShutsDownNewestFirstWhenResizing() throws Exception {
+        TestEntity entity;
+        final int failNum = 2;
+        final List<Entity> creationOrder = Lists.newArrayList();
+        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
+                .configure("initialSize", 0)
+                .configure("factory", new EntityFactory() {
+                    @Override public Entity newEntity(Map flags, Entity parent) {
+                        Entity result = new TestEntityImpl(flags);
+                        creationOrder.add(result);
+                        return result;
+                    }}));
+
+        cluster.start(ImmutableList.of(loc));
+        cluster.resize(1);
+        cluster.resize(2);
+        assertEquals(cluster.getCurrentSize(), (Integer)2);
+        assertEquals(ImmutableSet.copyOf(cluster.getMembers()), ImmutableSet.copyOf(creationOrder), "actual="+cluster.getMembers());
+
+        // Now stop one
+        cluster.resize(1);
+        assertEquals(cluster.getCurrentSize(), (Integer)1);
+        assertEquals(ImmutableList.copyOf(cluster.getMembers()), creationOrder.subList(0, 1));
+    }
+
+    @Test
+    public void resizeLoggedAsEffectorCall() throws Exception {
+        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
+                .configure("factory", new EntityFactory() {
+                    @Override public Entity newEntity(Map flags, Entity parent) {
+                        return new TestEntityImpl(flags);
+                    }}));
+
+        app.start(ImmutableList.of(loc));
+        cluster.resize(1);
+
+        Set<Task<?>> tasks = app.getManagementContext().getExecutionManager().getTasksWithAllTags(ImmutableList.of(
+            BrooklynTaskTags.tagForContextEntity(cluster),"EFFECTOR"));
+        assertEquals(tasks.size(), 2);
+        assertTrue(Iterables.get(tasks, 0).getDescription().contains("start"));
+        assertTrue(Iterables.get(tasks, 1).getDescription().contains("resize"));
+    }
+
+    @Test
+    public void testStoppedChildIsRemoveFromGroup() throws Exception {
+        final DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
+                .configure("initialSize", 1)
+                .configure("factory", new EntityFactory() {
+                    @Override public Entity newEntity(Map flags, Entity parent) {
+                        return new TestEntityImpl(flags);
+                    }}));
+
+        cluster.start(ImmutableList.of(loc));
+
+        final TestEntity child = (TestEntity) Iterables.get(cluster.getMembers(), 0);
+        child.stop();
+        Entities.unmanage(child);
+
+        Asserts.succeedsEventually(MutableMap.of("timeout", TIMEOUT_MS), new Runnable() {
+            @Override public void run() {
+                assertFalse(cluster.getChildren().contains(child), "children="+cluster.getChildren());
+                assertEquals(cluster.getCurrentSize(), (Integer)0);
+                assertEquals(cluster.getMembers().size(), 0);
+            }});
+    }
+
+    @Test
+    public void testPluggableRemovalStrategyIsUsed() throws Exception {
+        final List<Entity> removedEntities = Lists.newArrayList();
+
+        Function<Collection<Entity>, Entity> removalStrategy = new Function<Collection<Entity>, Entity>() {
+            @Override public Entity apply(Collection<Entity> contenders) {
+                Entity choice = Iterables.get(contenders, random.nextInt(contenders.size()));
+                removedEntities.add(choice);
+                return choice;
+            }
+        };
+
+        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
+                .configure("factory", new EntityFactory() {
+                    @Override public Entity newEntity(Map flags, Entity parent) {
+                        return new TestEntityImpl(flags);
+                    }})
+                .configure("initialSize", 10)
+                .configure("removalStrategy", removalStrategy));
+
+        cluster.start(ImmutableList.of(loc));
+        Set origMembers = ImmutableSet.copyOf(cluster.getMembers());
+
+        for (int i = 10; i >= 0; i--) {
+            cluster.resize(i);
+            assertEquals(cluster.getAttribute(Changeable.GROUP_SIZE), (Integer)i);
+            assertEquals(removedEntities.size(), 10-i);
+            assertEquals(ImmutableSet.copyOf(Iterables.concat(cluster.getMembers(), removedEntities)), origMembers);
+        }
+    }
+
+    @Test
+    public void testPluggableRemovalStrategyCanBeSetAfterConstruction() throws Exception {
+        final List<Entity> removedEntities = Lists.newArrayList();
+
+        Function<Collection<Entity>, Entity> removalStrategy = new Function<Collection<Entity>, Entity>() {
+            @Override public Entity apply(Collection<Entity> contenders) {
+                Entity choice = Iterables.get(contenders, random.nextInt(contenders.size()));
+                removedEntities.add(choice);
+                return choice;
+            }
+        };
+        
+        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
+                .configure("factory", new EntityFactory() {
+                    @Override public Entity newEntity(Map flags, Entity parent) {
+                        return new TestEntityImpl(flags);
+                    }})
+                .configure("initialSize", 10));
+
+        cluster.start(ImmutableList.of(loc));
+        Set origMembers = ImmutableSet.copyOf(cluster.getMembers());
+
+        cluster.setRemovalStrategy(removalStrategy);
+
+        for (int i = 10; i >= 0; i--) {
+            cluster.resize(i);
+            assertEquals(cluster.getAttribute(Changeable.GROUP_SIZE), (Integer)i);
+            assertEquals(removedEntities.size(), 10-i);
+            assertEquals(ImmutableSet.copyOf(Iterables.concat(cluster.getMembers(), removedEntities)), origMembers);
+        }
+    }
+
+    @Test
+    public void testResizeDoesNotBlockCallsToQueryGroupMembership() throws Exception {
+        final CountDownLatch executingLatch = new CountDownLatch(1);
+        final CountDownLatch continuationLatch = new CountDownLatch(1);
+        
+        final DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
+                .configure("initialSize", 0)
+                .configure("factory", new EntityFactory() {
+                    @Override public Entity newEntity(Map flags, Entity parent) {
+                        try {
+                            executingLatch.countDown();
+                            continuationLatch.await();
+                            return new TestEntityImpl(flags);
+                        } catch (InterruptedException e) {
+                            throw Exceptions.propagate(e);
+                        }
+                    }}));
+
+        cluster.start(ImmutableList.of(loc));
+
+        Thread thread = new Thread(new Runnable() {
+                @Override public void run() {
+                    cluster.resize(1);
+                }});
+        
+        try {
+            // wait for resize to be executing
+            thread.start();
+            executingLatch.await(TIMEOUT_MS, TimeUnit.MILLISECONDS);
+
+            // ensure can still call methods on group, to query/update membership
+            assertEquals(ImmutableList.copyOf(cluster.getMembers()), ImmutableList.of());
+            assertEquals(cluster.getCurrentSize(), (Integer)0);
+            assertFalse(cluster.hasMember(cluster));
+            cluster.addMember(cluster);
+            assertTrue(cluster.removeMember(cluster));
+
+            // allow the resize to complete
+            continuationLatch.countDown();
+            thread.join(TIMEOUT_MS);
+            assertFalse(thread.isAlive());
+        } finally {
+            thread.interrupt();
+        }
+    }
+
+    @Test
+    public void testReplacesMember() throws Exception {
+        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
+                .configure("initialSize", 1)
+                .configure("factory", new EntityFactory() {
+                    @Override public Entity newEntity(Map flags, Entity parent) {
+                        return new TestEntityImpl(flags);
+                    }}));
+
+        cluster.start(ImmutableList.of(loc));
+        Entity member = Iterables.get(cluster.getMembers(), 0);
+
+        String replacementId = cluster.replaceMember(member.getId());
+        Entity replacement = app.getManagementContext().getEntityManager().getEntity(replacementId);
+
+        assertEquals(cluster.getMembers().size(), 1);
+        assertFalse(cluster.getMembers().contains(member));
+        assertFalse(cluster.getChildren().contains(member));
+        assertNotNull(replacement, "replacementId="+replacementId);
+        assertTrue(cluster.getMembers().contains(replacement), "replacement="+replacement+"; members="+cluster.getMembers());
+        assertTrue(cluster.getChildren().contains(replacement), "replacement="+replacement+"; children="+cluster.getChildren());
+    }
+
+    @Test
+    public void testReplaceMemberThrowsIfMemberIdDoesNotResolve() throws Exception {
+        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
+                .configure("initialSize", 1)
+                .configure("factory", new EntityFactory() {
+                    @Override public Entity newEntity(Map flags, Entity parent) {
+                        return new TestEntityImpl(flags);
+                    }}));
+
+        cluster.start(ImmutableList.of(loc));
+        Entity member = Iterables.get(cluster.getMembers(), 0);
+
+        try {
+            cluster.replaceMember("wrong.id");
+            fail();
+        } catch (Exception e) {
+            if (Exceptions.getFirstThrowableOfType(e, NoSuchElementException.class) == null) throw e;
+            if (!Exceptions.getFirstThrowableOfType(e, NoSuchElementException.class).getMessage().contains("entity wrong.id cannot be resolved")) throw e;
+        }
+
+        assertEquals(ImmutableSet.copyOf(cluster.getMembers()), ImmutableSet.of(member));
+    }
+
+    @Test
+    public void testReplaceMemberThrowsIfNotMember() throws Exception {
+        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
+                .configure("initialSize", 1)
+                .configure("factory", new EntityFactory() {
+                    @Override public Entity newEntity(Map flags, Entity parent) {
+                        return new TestEntityImpl(flags);
+                    }}));
+
+        cluster.start(ImmutableList.of(loc));
+        Entity member = Iterables.get(cluster.getMembers(), 0);
+
+        try {
+            cluster.replaceMember(app.getId());
+            fail();
+        } catch (Exception e) {
+            if (Exceptions.getFirstThrowableOfType(e, NoSuchElementException.class) == null) throw e;
+            if (!Exceptions.getFirstThrowableOfType(e, NoSuchElementException.class).getMessage().contains("is not a member")) throw e;
+        }
+
+        assertEquals(ImmutableSet.copyOf(cluster.getMembers()), ImmutableSet.of(member));
+    }
+
+    @Test
+    public void testReplaceMemberFailsIfCantProvisionReplacement() throws Exception {
+        final int failNum = 2;
+        final AtomicInteger counter = new AtomicInteger(0);
+        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
+                .configure("factory", new EntityFactory() {
+                    @Override public Entity newEntity(Map flags, Entity parent) {
+                        int num = counter.incrementAndGet();
+                        return new FailingEntity(flags, (num==failNum));
+                    }}));
+
+        cluster.start(ImmutableList.of(loc));
+        Entity member = Iterables.get(cluster.getMembers(), 0);
+
+        try {
+            cluster.replaceMember(member.getId());
+            fail();
+        } catch (Exception e) {
+            if (!e.toString().contains("failed to grow")) throw e;
+            if (Exceptions.getFirstThrowableOfType(e, NoSuchElementException.class) != null) throw e;
+        }
+        assertEquals(ImmutableSet.copyOf(cluster.getMembers()), ImmutableSet.of(member));
+    }
+
+    @Test
+    public void testReplaceMemberRemovesAndThowsIfFailToStopOld() throws Exception {
+        final int failNum = 1;
+        final AtomicInteger counter = new AtomicInteger(0);
+        DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
+                .configure("initialSize", 1)
+                .configure("factory", new EntityFactory() {
+                    @Override public Entity newEntity(Map flags, Entity parent) {
+                        int num = counter.incrementAndGet();
+                        return new FailingEntity(flags, false, (num==failNum), IllegalStateException.class);
+                    }}));
+
+        cluster.start(ImmutableList.of(loc));
+        Entity member = Iterables.get(cluster.getMembers(), 0);
+
+        try {
+            cluster.replaceMember(member.getId());
+            fail();
+        } catch (Exception e) {
+            if (Exceptions.getFirstThrowableOfType(e, StopFailedRuntimeException.class) == null) throw e;
+            boolean found = false;
+            for (Throwable t : Throwables.getCausalChain(e)) {
+                if (t.toString().contains("Simulating entity stop failure")) {
+                    found = true;
+                    break;
+                }
+            }
+            if (!found) throw e;
+        }
+        assertFalse(Entities.isManaged(member));
+        assertEquals(cluster.getMembers().size(), 1);
+    }
+
+    private Throwable unwrapException(Throwable e) {
+        if (e instanceof ExecutionException) {
+            return unwrapException(e.getCause());
+        } else if (e instanceof org.codehaus.groovy.runtime.InvokerInvocationException) {
+            return unwrapException(e.getCause());
+        } else {
+            return e;
+        }
+    }
+
+    public static class FailingEntity extends TestEntityImpl {
+        final boolean failOnStart;
+        final boolean failOnStop;
+        final Class<? extends Exception> exceptionClazz;
+    
+        public FailingEntity(Map flags, boolean failOnStart) {
+            this(flags, failOnStart, false);
+        }
+        
+        public FailingEntity(Map flags, boolean failOnStart, boolean failOnStop) {
+            this(flags, failOnStart, failOnStop, IllegalStateException.class);
+        }
+        
+        public FailingEntity(Map flags, boolean failOnStart, boolean failOnStop, Class<? extends Exception> exceptionClazz) {
+            super(flags);
+            this.failOnStart = failOnStart;
+            this.failOnStop = failOnStop;
+            this.exceptionClazz = exceptionClazz;
+        }
+        
+        @Override
+        public void start(Collection<? extends Location> locs) {
+            if (failOnStart) {
+                try {
+                    Exception e = exceptionClazz.getConstructor(String.class).newInstance("Simulating entity start failure for test");
+                    throw e;
+                } catch (Exception e) {
+                    throw Exceptions.propagate(e);
+                }
+            }
+        }
+        
+        @Override
+        public void stop() {
+            if (failOnStop) {
+                try {
+                    Exception e = exceptionClazz.getConstructor(String.class).newInstance("Simulating entity stop failure for test");
+                    throw e;
+                } catch (Exception e) {
+                    throw Exceptions.propagate(e);
+                }
+            }
+        }
+    }
+}
\ No newline at end of file


[24/50] [abbrv] git commit: Merge pull request #1412 from grkvlt/enhancement/iptables-rules

Posted by ri...@apache.org.
Merge pull request #1412 from grkvlt/enhancement/iptables-rules

Fix use of service command with iptables and deprecate old methods

Project: http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/commit/48a34e41
Tree: http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/tree/48a34e41
Diff: http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/diff/48a34e41

Branch: refs/pull/1405/merge
Commit: 48a34e414bee3918ceff23c65481ab22d4a2859c
Parents: f54024f 803f9f1
Author: Aled Sage <al...@gmail.com>
Authored: Fri May 23 15:40:35 2014 +0100
Committer: Aled Sage <al...@gmail.com>
Committed: Fri May 23 15:40:35 2014 +0100

----------------------------------------------------------------------
 .../location/jclouds/JcloudsLocationConfig.java |  1 +
 .../brooklyn/util/ssh/IptablesCommands.java     | 97 +++++++++++---------
 2 files changed, 54 insertions(+), 44 deletions(-)
----------------------------------------------------------------------



[45/50] [abbrv] git commit: correct message about ctrl-c to shutdown because if running in background that does not work!

Posted by ri...@apache.org.
correct message about ctrl-c to shutdown because if running in background that does not work!


Project: http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/commit/37cf8174
Tree: http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/tree/37cf8174
Diff: http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/diff/37cf8174

Branch: refs/pull/1414/head
Commit: 37cf81745a9e32b3de2c81498cd1c65f1b6fde0f
Parents: 17ac898
Author: Alex Heneveld <al...@cloudsoftcorp.com>
Authored: Fri May 23 10:34:32 2014 -0600
Committer: Alex Heneveld <al...@cloudsoftcorp.com>
Committed: Fri May 23 10:34:32 2014 -0600

----------------------------------------------------------------------
 usage/cli/src/main/java/brooklyn/cli/Main.java | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/37cf8174/usage/cli/src/main/java/brooklyn/cli/Main.java
----------------------------------------------------------------------
diff --git a/usage/cli/src/main/java/brooklyn/cli/Main.java b/usage/cli/src/main/java/brooklyn/cli/Main.java
index 8d32c93..d9069a4 100644
--- a/usage/cli/src/main/java/brooklyn/cli/Main.java
+++ b/usage/cli/src/main/java/brooklyn/cli/Main.java
@@ -501,7 +501,7 @@ public class Main {
                 stopAllApps(ctx.getApplications());
             } else {
                 // Block forever so that Brooklyn doesn't exit (until someone does cntrl-c or kill)
-                log.info("Launched Brooklyn; now blocking to wait for cntrl-c or kill");
+                log.info("Launched Brooklyn; will now block until shutdown issued. Shutdown via GUI or API or process interrupt.");
                 waitUntilInterrupted();
             }
         }


[49/50] [abbrv] git commit: Merge 99b9e19bfbb406f30d1e6c05bcc52ccdc4acdc87 into 1c9ae9245088e6904c4ed66ec1f592e2588e6f8e

Posted by ri...@apache.org.
Merge 99b9e19bfbb406f30d1e6c05bcc52ccdc4acdc87 into 1c9ae9245088e6904c4ed66ec1f592e2588e6f8e


Project: http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/commit/3114bfa8
Tree: http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/tree/3114bfa8
Diff: http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/diff/3114bfa8

Branch: refs/pull/1414/merge
Commit: 3114bfa88395fd5b0373ce0453f9b1278362ac39
Parents: 1c9ae92 99b9e19
Author: Alex Heneveld <al...@cloudsoftcorp.com>
Authored: Fri May 23 16:36:34 2014 +0000
Committer: Alex Heneveld <al...@cloudsoftcorp.com>
Committed: Fri May 23 16:36:34 2014 +0000

----------------------------------------------------------------------
 .../location/jclouds/JcloudsLocation.java       | 16 ++++++++++++-
 .../location/jclouds/JcloudsLocationConfig.java |  7 +++++-
 .../entity/brooklynnode/BrooklynNode.java       |  3 ++-
 .../java/brooklyn/entity/java/JavaAppUtils.java |  5 ++--
 usage/cli/src/main/java/brooklyn/cli/Main.java  |  2 +-
 .../java/brooklyn/util/math/MathFunctions.java  | 24 +++++++++++++++++++-
 .../brooklyn/util/math/MathFunctionsTest.java   | 18 +++++++++++++++
 7 files changed, 67 insertions(+), 8 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/3114bfa8/locations/jclouds/src/main/java/brooklyn/location/jclouds/JcloudsLocationConfig.java
----------------------------------------------------------------------